Advertisement
Guest User

Untitled

a guest
May 25th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.54 KB | None | 0 0
  1. public class MainActivity extends AppCompatActivity implements RoutingListener, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
  2. protected GoogleMap map;
  3. protected LatLng start;
  4. protected LatLng end;
  5. @InjectView(R.id.start)
  6. AutoCompleteTextView starting;
  7. @InjectView(R.id.destination)
  8. AutoCompleteTextView destination;
  9. @InjectView(R.id.send)
  10. ImageView send;
  11. private static final String LOG_TAG = "MyActivity";
  12. protected GoogleApiClient mGoogleApiClient;
  13. private PlaceAutoCompleteAdapter mAdapter;
  14. private ProgressDialog progressDialog;
  15. private List<Polyline> polylines;
  16. private static final int[] COLORS = new int[]{R.color.primary_dark,R.color.primary,R.color.primary_light,
  17. R.color.accent, R.color.primary_dark_material_light};
  18.  
  19.  
  20. private static final LatLngBounds BOUNDS_JAMAICA= new LatLngBounds(new LatLng(-57.965341647205726, 144.9987719580531),
  21. new LatLng(72.77492067739843, -9.998857788741589));
  22.  
  23. /**
  24. * This activity loads a map and then displays the route and pushpins on it.
  25. */
  26. @Override
  27. public void onCreate(Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.activity_main);
  30. ButterKnife.inject(this);
  31. getSupportActionBar().setDisplayShowHomeEnabled(true);
  32.  
  33. polylines = new ArrayList<>();
  34. mGoogleApiClient = new GoogleApiClient.Builder(this)
  35. .addApi(Places.GEO_DATA_API)
  36. .addConnectionCallbacks(this)
  37. .addOnConnectionFailedListener(this)
  38. .build();
  39. MapsInitializer.initialize(this);
  40. mGoogleApiClient.connect();
  41.  
  42. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
  43.  
  44. if (mapFragment == null) {
  45. mapFragment = SupportMapFragment.newInstance();
  46. getSupportFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();
  47. }
  48. map = mapFragment.getMap();
  49.  
  50. mAdapter = new PlaceAutoCompleteAdapter(this, android.R.layout.simple_list_item_1,
  51. mGoogleApiClient, BOUNDS_JAMAICA, null);
  52.  
  53.  
  54. /*
  55. * Updates the bounds being used by the auto complete adapter based on the position of the
  56. * map.
  57. * */
  58. map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
  59. @Override
  60. public void onCameraChange(CameraPosition position) {
  61. LatLngBounds bounds = map.getProjection().getVisibleRegion().latLngBounds;
  62. mAdapter.setBounds(bounds);
  63. }
  64. });
  65.  
  66.  
  67. CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(18.013610, -77.498803));
  68. CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
  69.  
  70. map.moveCamera(center);
  71. map.animateCamera(zoom);
  72.  
  73. LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
  74.  
  75. locationManager.requestLocationUpdates(
  76. LocationManager.NETWORK_PROVIDER, 5000, 0,
  77. new LocationListener() {
  78. @Override
  79. public void onLocationChanged(Location location) {
  80.  
  81. CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude()));
  82. CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
  83.  
  84. map.moveCamera(center);
  85. map.animateCamera(zoom);
  86. }
  87.  
  88. @Override
  89. public void onStatusChanged(String provider, int status, Bundle extras) {
  90.  
  91. }
  92.  
  93. @Override
  94. public void onProviderEnabled(String provider) {
  95.  
  96. }
  97.  
  98. @Override
  99. public void onProviderDisabled(String provider) {
  100.  
  101. }
  102. });
  103.  
  104.  
  105. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
  106. 3000, 0, new LocationListener() {
  107. @Override
  108. public void onLocationChanged(Location location) {
  109. CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude()));
  110. CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
  111.  
  112. map.moveCamera(center);
  113. map.animateCamera(zoom);
  114.  
  115. }
  116.  
  117. @Override
  118. public void onStatusChanged(String provider, int status, Bundle extras) {
  119.  
  120. }
  121.  
  122. @Override
  123. public void onProviderEnabled(String provider) {
  124.  
  125. }
  126.  
  127. @Override
  128. public void onProviderDisabled(String provider) {
  129.  
  130. }
  131. });
  132.  
  133. /*
  134. * Adds auto complete adapter to both auto complete
  135. * text views.
  136. * */
  137. starting.setAdapter(mAdapter);
  138. destination.setAdapter(mAdapter);
  139.  
  140.  
  141. /*
  142. * Sets the start and destination points based on the values selected
  143. * from the autocomplete text views.
  144. * */
  145.  
  146. starting.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  147. @Override
  148. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  149.  
  150. final PlaceAutoCompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
  151. final String placeId = String.valueOf(item.placeId);
  152. Log.i(LOG_TAG, "Autocomplete item selected: " + item.description);
  153.  
  154. /*
  155. Issue a request to the Places Geo Data API to retrieve a Place object with additional
  156. details about the place.
  157. */
  158. PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
  159. .getPlaceById(mGoogleApiClient, placeId);
  160. placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
  161. @Override
  162. public void onResult(PlaceBuffer places) {
  163. if (!places.getStatus().isSuccess()) {
  164. // Request did not complete successfully
  165. Log.e(LOG_TAG, "Place query did not complete. Error: " + places.getStatus().toString());
  166. places.release();
  167. return;
  168. }
  169. // Get the Place object from the buffer.
  170. final Place place = places.get(0);
  171.  
  172. start=place.getLatLng();
  173. }
  174. });
  175.  
  176. }
  177. });
  178. destination.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  179. @Override
  180. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  181.  
  182. final PlaceAutoCompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
  183. final String placeId = String.valueOf(item.placeId);
  184. Log.i(LOG_TAG, "Autocomplete item selected: " + item.description);
  185.  
  186. /*
  187. Issue a request to the Places Geo Data API to retrieve a Place object with additional
  188. details about the place.
  189. */
  190. PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
  191. .getPlaceById(mGoogleApiClient, placeId);
  192. placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
  193. @Override
  194. public void onResult(PlaceBuffer places) {
  195. if (!places.getStatus().isSuccess()) {
  196. // Request did not complete successfully
  197. Log.e(LOG_TAG, "Place query did not complete. Error: " + places.getStatus().toString());
  198. places.release();
  199. return;
  200. }
  201. // Get the Place object from the buffer.
  202. final Place place = places.get(0);
  203.  
  204. end=place.getLatLng();
  205. }
  206. });
  207.  
  208. }
  209. });
  210.  
  211. /*
  212. These text watchers set the start and end points to null because once there's
  213. * a change after a value has been selected from the dropdown
  214. * then the value has to reselected from dropdown to get
  215. * the correct location.
  216. * */
  217. starting.addTextChangedListener(new TextWatcher() {
  218. @Override
  219. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  220.  
  221. }
  222.  
  223. @Override
  224. public void onTextChanged(CharSequence s, int startNum, int before, int count) {
  225. if (start != null) {
  226. start = null;
  227. }
  228. }
  229.  
  230. @Override
  231. public void afterTextChanged(Editable s) {
  232.  
  233. }
  234. });
  235.  
  236. destination.addTextChangedListener(new TextWatcher() {
  237. @Override
  238. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  239.  
  240. }
  241.  
  242. @Override
  243. public void onTextChanged(CharSequence s, int start, int before, int count) {
  244.  
  245.  
  246. if(end!=null)
  247. {
  248. end=null;
  249. }
  250. }
  251.  
  252. @Override
  253. public void afterTextChanged(Editable s) {
  254.  
  255. }
  256. });
  257.  
  258. }
  259.  
  260. @OnClick(R.id.send)
  261. public void sendRequest()
  262. {
  263. if(Util.Operations.isOnline(this))
  264. {
  265. route();
  266. }
  267. else
  268. {
  269. Toast.makeText(this,"No internet connectivity",Toast.LENGTH_SHORT).show();
  270. }
  271. }
  272.  
  273. public void route()
  274. {
  275. if(start==null || end==null)
  276. {
  277. if(start==null)
  278. {
  279. if(starting.getText().length()>0)
  280. {
  281. starting.setError("Choose location from dropdown.");
  282. }
  283. else
  284. {
  285. Toast.makeText(this,"Please choose a starting point.",Toast.LENGTH_SHORT).show();
  286. }
  287. }
  288. if(end==null)
  289. {
  290. if(destination.getText().length()>0)
  291. {
  292. destination.setError("Choose location from dropdown.");
  293. }
  294. else
  295. {
  296. Toast.makeText(this,"Please choose a destination.",Toast.LENGTH_SHORT).show();
  297. }
  298. }
  299. }
  300. else
  301. {
  302. progressDialog = ProgressDialog.show(this, "Please wait.",
  303. "Fetching route information.", true);
  304. Routing routing = new Routing.Builder()
  305. .travelMode(AbstractRouting.TravelMode.DRIVING)
  306. .withListener(this)
  307. .alternativeRoutes(true)
  308. .waypoints(start, end)
  309. .build();
  310. routing.execute();
  311. }
  312. }
  313.  
  314.  
  315. @Override
  316. public void onRoutingFailure(RouteException e) {
  317. // The Routing request failed
  318. progressDialog.dismiss();
  319. if(e != null) {
  320. Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
  321. }else {
  322. Toast.makeText(this, "Something went wrong, Try again", Toast.LENGTH_SHORT).show();
  323. }
  324. }
  325.  
  326. @Override
  327. public void onRoutingStart() {
  328. // The Routing Request starts
  329. }
  330.  
  331. @Override
  332. public void onRoutingSuccess(List<Route> route, int shortestRouteIndex)
  333. {
  334. progressDialog.dismiss();
  335. CameraUpdate center = CameraUpdateFactory.newLatLng(start);
  336. CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
  337.  
  338. map.moveCamera(center);
  339.  
  340.  
  341. if(polylines.size()>0) {
  342. for (Polyline poly : polylines) {
  343. poly.remove();
  344. }
  345. }
  346.  
  347. polylines = new ArrayList<>();
  348. //add route(s) to the map.
  349. for (int i = 0; i <route.size(); i++) {
  350.  
  351. //In case of more than 5 alternative routes
  352. int colorIndex = i % COLORS.length;
  353.  
  354. PolylineOptions polyOptions = new PolylineOptions();
  355. polyOptions.color(getResources().getColor(COLORS[colorIndex]));
  356. polyOptions.width(10 + i * 3);
  357. polyOptions.addAll(route.get(i).getPoints());
  358. Polyline polyline = map.addPolyline(polyOptions);
  359. polylines.add(polyline);
  360.  
  361. Toast.makeText(getApplicationContext(),"Route "+ (i+1) +": distance - "+ route.get(i).getDistanceValue()+": duration - "+ route.get(i).getDurationValue(),Toast.LENGTH_SHORT).show();
  362. }
  363.  
  364. // Start marker
  365. MarkerOptions options = new MarkerOptions();
  366. options.position(start);
  367. options.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue));
  368. map.addMarker(options);
  369.  
  370. // End marker
  371. options = new MarkerOptions();
  372. options.position(end);
  373. options.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green));
  374. map.addMarker(options);
  375.  
  376. }
  377.  
  378. @Override
  379. public void onRoutingCancelled() {
  380. Log.i(LOG_TAG, "Routing was cancelled.");
  381. }
  382.  
  383. @Override
  384. public void onConnectionFailed(ConnectionResult connectionResult) {
  385.  
  386. Log.v(LOG_TAG,connectionResult.toString());
  387. }
  388.  
  389. @Override
  390. public void onConnected(Bundle bundle) {
  391. }
  392.  
  393. @Override
  394. public void onConnectionSuspended(int i) {
  395.  
  396. }
  397. }
  398.  
  399. <?xml version="1.0" encoding="utf-8"?>
  400. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  401. xmlns:card_view="http://schemas.android.com/apk/res-auto"
  402. android:layout_width="fill_parent"
  403. android:layout_height="fill_parent"
  404. android:orientation="vertical">
  405.  
  406. <fragment
  407. android:id="@+id/map"
  408. android:name="com.google.android.gms.maps.SupportMapFragment"
  409. android:layout_width="match_parent"
  410. android:layout_height="wrap_content" />
  411.  
  412. <android.support.v7.widget.CardView
  413. android:id="@+id/cardview"
  414. android:layout_width="fill_parent"
  415. android:layout_height="wrap_content"
  416. android:layout_gravity="center_horizontal|bottom"
  417. android:layout_marginBottom="20dp"
  418. android:layout_marginLeft="20dp"
  419. android:layout_marginRight="20dp"
  420. android:elevation="100dp"
  421. card_view:cardBackgroundColor="@android:color/white"
  422. card_view:cardCornerRadius="8dp">
  423.  
  424. <RelativeLayout
  425. android:layout_width="fill_parent"
  426. android:layout_height="match_parent"
  427. >
  428.  
  429. <LinearLayout
  430. android:layout_width="wrap_content"
  431. android:layout_height="wrap_content"
  432. android:orientation="vertical"
  433. android:padding="20dp">
  434.  
  435. <AutoCompleteTextView
  436. android:id="@+id/start"
  437. android:layout_width="fill_parent"
  438. android:layout_height="wrap_content"
  439. android:layout_marginBottom="10dp"
  440. android:background="@android:color/transparent"
  441. android:hint="Choose a starting point..." />
  442.  
  443. <View
  444. android:layout_width="match_parent"
  445. android:layout_height="5dp"
  446. android:layout_marginBottom="5dp"
  447. android:layout_marginRight="50dp"
  448. android:layout_marginTop="5dp"
  449. android:background="@drawable/dotted" />
  450.  
  451. <AutoCompleteTextView
  452. android:id="@+id/destination"
  453. android:layout_width="fill_parent"
  454. android:layout_height="wrap_content"
  455. android:background="@android:color/transparent"
  456. android:hint="Choose a destination..." />
  457. </LinearLayout>
  458. <ImageView
  459. android:id="@+id/send"
  460. android:layout_centerVertical="true"
  461. android:layout_marginRight="20dp"
  462. android:layout_alignParentRight="true"
  463. android:layout_width="36dp"
  464. android:src="@drawable/ic_send_grey600_48dp"
  465. android:layout_height="36dp" />
  466.  
  467. </RelativeLayout>
  468. </android.support.v7.widget.CardView>
  469. </FrameLayout>
  470.  
  471. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  472. package="com.directions.sample" >
  473. <!-- Copied from Google Maps Library/AndroidManifest.xml. -->
  474. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  475. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  476. <uses-permission android:name="android.permission.INTERNET" />
  477. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  478. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  479. <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
  480. <!-- External storage for caching. -->
  481. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  482. <!-- Maps API needs OpenGL ES 2.0. -->
  483. <uses-feature
  484. android:glEsVersion="0x00020000"
  485. android:required="true" />
  486.  
  487. <application
  488. android:allowBackup="true"
  489. android:icon="@mipmap/ic_launcher"
  490. android:label="@string/app_name"
  491. android:theme="@style/AppTheme" >
  492. <meta-data
  493. android:name="com.google.android.geo.API_KEY"
  494. android:value="AIzaSyCXb3CVEfeUQiT7-J-KOvKaqWILPVBkIqg"/>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement