使用Androids Google Maps API查找路线

前端之家收集整理的这篇文章主要介绍了使用Androids Google Maps API查找路线前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望能够使用适用于 Android的Google Maps API在两个用户定义的地理点之间显示路线.我还希望能够让用户选择要显示的路线类型,无论是步行,骑车,汽车等.此外,我希望能够计算使用此路线所需的时间和距离.我试过在网上搜索并查看其他stackoverflow问题,但无济于事.我怎么会这样呢?我怎么能编码这个.

// – – 编辑 – – //

我还想得到交通信息,如繁忙的路线,拥堵等.

解决方法

使用Wrapper库的Android Google Maps Routing示例代码

使用Android Studio Gradle条目:

  1. compile 'com.github.jd-alexander:library:1.1.0'

MainActivity.java

  1. import android.Manifest;
  2. import android.content.pm.PackageManager;
  3. import android.graphics.Color;
  4. import android.location.Location;
  5. import android.location.LocationListener;
  6. import android.location.LocationManager;
  7. import android.support.design.widget.FloatingActionButton;
  8. import android.support.design.widget.Snackbar;
  9. import android.support.v4.app.ActivityCompat;
  10. import android.support.v4.app.FragmentActivity;
  11. import android.os.Bundle;
  12. import android.view.View;
  13. import android.widget.TextView;
  14. import android.widget.Toast;
  15.  
  16. import com.directions.route.Route;
  17. import com.directions.route.RouteException;
  18. import com.directions.route.Routing;
  19. import com.directions.route.RoutingListener;
  20. import com.google.android.gms.maps.CameraUpdateFactory;
  21. import com.google.android.gms.maps.GoogleMap;
  22. import com.google.android.gms.maps.OnMapReadyCallback;
  23. import com.google.android.gms.maps.SupportMapFragment;
  24. import com.google.android.gms.maps.model.LatLng;
  25. import com.google.android.gms.maps.model.LatLngBounds;
  26. import com.google.android.gms.maps.model.Marker;
  27. import com.google.android.gms.maps.model.MarkerOptions;
  28. import com.google.android.gms.maps.model.Polyline;
  29. import com.google.android.gms.maps.model.PolylineOptions;
  30.  
  31. import java.util.ArrayList;
  32. import java.util.Iterator;
  33. import java.util.List;
  34.  
  35. public class MainActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener,GoogleMap.OnMarkerClickListener,RoutingListener {
  36.  
  37. private GoogleMap mMap = null;
  38. private LocationManager locationManager = null;
  39. private FloatingActionButton fab = null;
  40. private TextView txtDistance,txtTime;
  41.  
  42. //Global UI Map markers
  43. private Marker currentMarker = null;
  44. private Marker destMarker = null;
  45. private LatLng currentLatLng = null;
  46. private Polyline line = null;
  47.  
  48. //Global flags
  49. private boolean firstRefresh = true;
  50.  
  51. @Override
  52. protected void onCreate(Bundle savedInstanceState) {
  53. super.onCreate(savedInstanceState);
  54. setContentView(R.layout.activity_map);
  55. Constants.POINT_DEST = new LatLng(18.758663,73.382025); //Lonavala destination.
  56. //Load the map fragment on UI
  57. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
  58. mapFragment.getMapAsync(this);
  59. txtDistance = (TextView)findViewById(R.id.txt_distance);
  60. txtTime = (TextView)findViewById(R.id.txt_time);
  61. fab = (FloatingActionButton)findViewById(R.id.fab);
  62. fab.setOnClickListener(new View.OnClickListener() {
  63. @Override
  64. public void onClick(View v) {
  65. MainActivity.this.getRoutingPath();
  66. Snackbar.make(v,"Fetching Route",Snackbar.LENGTH_SHORT).show();
  67. }
  68. });
  69.  
  70. }
  71.  
  72. @Override
  73. protected void onResume() {
  74. super.onResume();
  75. firstRefresh = true;
  76. //Ensure the GPS is ON and location permission enabled for the application.
  77. locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
  78. if (!PermissionCheck.getInstance().checkGPSPermission(this,locationManager)) {
  79. //GPS not enabled for the application.
  80. } else if (!PermissionCheck.getInstance().checkLocationPermission(this)) {
  81. //Location permission not given.
  82. } else {
  83. Toast.makeText(MainActivity.this,"Fetching Location",Toast.LENGTH_SHORT).show();
  84. try {
  85. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,this);
  86. locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,5000,this);
  87. } catch(Exception e)
  88. {
  89. Toast.makeText(MainActivity.this,"ERROR: Cannot start location listener",Toast.LENGTH_SHORT).show();
  90. }
  91. }
  92. }
  93.  
  94. @Override
  95. protected void onPause() {
  96. if (locationManager != null) {
  97. //Check needed in case of API level 23.
  98.  
  99. if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  100. }
  101. try {
  102. locationManager.removeUpdates(this);
  103. } catch (Exception e) {
  104. }
  105. }
  106. locationManager = null;
  107. super.onPause();
  108. }
  109.  
  110. @Override
  111. protected void onStop() {
  112. super.onStop();
  113. }
  114.  
  115. @Override
  116. public void onMapReady(GoogleMap googleMap)
  117. {
  118. mMap = googleMap;
  119. //mMap.getUiSettings().setZoomControlsEnabled(true);
  120. mMap.getUiSettings().setCompassEnabled(true);
  121. mMap.getUiSettings().setAllGesturesEnabled(true);
  122. mMap.setOnMarkerClickListener(this);
  123. }
  124.  
  125. /**
  126. * @desc LocationListener Interface Methods implemented.
  127. */
  128.  
  129. @Override
  130. public void onLocationChanged(Location location)
  131. {
  132. double lat = location.getLatitude();
  133. double lng = location.getLongitude();
  134. currentLatLng = new LatLng(lat,lng);
  135. if(firstRefresh)
  136. {
  137. //Add Start Marker.
  138. currentMarker = mMap.addMarker(new MarkerOptions().position(currentLatLng).title("Current Position"));//.icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
  139. firstRefresh = false;
  140. destMarker = mMap.addMarker(new MarkerOptions().position(Constants.POINT_DEST).title("Destination"));//.icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
  141. mMap.moveCamera(CameraUpdateFactory.newLatLng(Constants.POINT_DEST));
  142. mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
  143. getRoutingPath();
  144. }
  145. else
  146. {
  147. currentMarker.setPosition(currentLatLng);
  148. }
  149. }
  150.  
  151. @Override
  152. public void onStatusChanged(String provider,int status,Bundle extras) {}
  153.  
  154. @Override
  155. public void onProviderEnabled(String provider) {}
  156.  
  157. @Override
  158. public void onProviderDisabled(String provider) {}
  159.  
  160. /**
  161. * @desc MapMarker Interface Methods Implemented.
  162. */
  163.  
  164. @Override
  165. public boolean onMarkerClick(Marker marker)
  166. {
  167. if(marker.getTitle().contains("Destination"))
  168. {
  169. //Do some task on dest pin click
  170. }
  171. else if(marker.getTitle().contains("Current"))
  172. {
  173. //Do some task on current pin click
  174. }
  175. return false;
  176. }
  177.  
  178. /**
  179. *@desc Routing Listener interface methods implemented.
  180. **/
  181. @Override
  182. public void onRoutingFailure(RouteException e)
  183. {
  184. Toast.makeText(MainActivity.this,"Routing Failed",Toast.LENGTH_SHORT).show();
  185. }
  186.  
  187. @Override
  188. public void onRoutingStart() { }
  189.  
  190. @Override
  191. public void onRoutingSuccess(ArrayList<Route> list,int i)
  192. {
  193. try
  194. {
  195. //Get all points and plot the polyLine route.
  196. List<LatLng> listPoints = list.get(0).getPoints();
  197. PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
  198. Iterator<LatLng> iterator = listPoints.iterator();
  199. while(iterator.hasNext())
  200. {
  201. LatLng data = iterator.next();
  202. options.add(data);
  203. }
  204.  
  205. //If line not null then remove old polyline routing.
  206. if(line != null)
  207. {
  208. line.remove();
  209. }
  210. line = mMap.addPolyline(options);
  211.  
  212. //Show distance and duration.
  213. txtDistance.setText("Distance: " + list.get(0).getDistanceText());
  214. txtTime.setText("Duration: " + list.get(0).getDurationText());
  215.  
  216. //Focus on map bounds
  217. mMap.moveCamera(CameraUpdateFactory.newLatLng(list.get(0).getLatLgnBounds().getCenter()));
  218. LatLngBounds.Builder builder = new LatLngBounds.Builder();
  219. builder.include(currentLatLng);
  220. builder.include(Constants.POINT_DEST);
  221. LatLngBounds bounds = builder.build();
  222. mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,50));
  223. }
  224. catch (Exception e)
  225. {
  226. Toast.makeText(MainActivity.this,"EXCEPTION: Cannot parse routing response",Toast.LENGTH_SHORT).show();
  227. }
  228. }
  229.  
  230. @Override
  231. public void onRoutingCancelled()
  232. {
  233. Toast.makeText(MainActivity.this,"Routing Cancelled",Toast.LENGTH_SHORT).show();
  234. }
  235.  
  236. /**
  237. * @method getRoutingPath
  238. * @desc Method to draw the google routed path.
  239. */
  240. private void getRoutingPath()
  241. {
  242. try
  243. {
  244. //Do Routing
  245. Routing routing = new Routing.Builder()
  246. .travelMode(Routing.TravelMode.DRIVING)
  247. .withListener(this)
  248. .waypoints(currentLatLng,Constants.POINT_DEST)
  249. .build();
  250. routing.execute();
  251. }
  252. catch (Exception e)
  253. {
  254. Toast.makeText(MainActivity.this,"Unable to Route",Toast.LENGTH_SHORT).show();
  255. }
  256. }
  257.  
  258. }

Constants.java

  1. /**
  2. * @class Constants
  3. * @desc Constant class for holding values at runtime.
  4. */
  5. public class Constants
  6. {
  7.  
  8. //Map LatLong points
  9. public static LatLng POINT_DEST = null;
  10.  
  11. }

activity_map.xml

  1. <android.support.design.widget.CoordinatorLayout
  2. xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:map="http://schemas.android.com/apk/res-auto"
  5. xmlns:tools="http://schemas.android.com/tools"
  6.  
  7. android:layout_width="match_parent"
  8. android:layout_height="match_parent">
  9.  
  10. <LinearLayout android:layout_width="match_parent"
  11. android:layout_height="match_parent"
  12. android:orientation="vertical">
  13.  
  14. <LinearLayout
  15. android:id="@+id/viewA"
  16. android:layout_width="match_parent"
  17. android:layout_height="match_parent"
  18. android:layout_weight="0.1"
  19. android:orientation="horizontal">
  20.  
  21. <fragment
  22. android:id="@+id/map"
  23. android:name="com.google.android.gms.maps.SupportMapFragment"
  24. android:layout_width="match_parent"
  25. android:layout_height="match_parent"
  26. tools:context="com.packagename.MainActivity" />
  27.  
  28.  
  29. </LinearLayout>
  30.  
  31. <LinearLayout
  32. android:id="@+id/viewB"
  33. android:layout_width="match_parent"
  34. android:layout_height="match_parent"
  35. android:layout_weight="0.9"
  36. android:gravity="center|left"
  37. android:paddingLeft="20dp"
  38. android:background="#FFFFFF"
  39. android:orientation="vertical" >
  40.  
  41. <TextView
  42. android:layout_width="wrap_content"
  43. android:layout_height="wrap_content"
  44. android:textSize="16dp"
  45. android:text="Distance ?"
  46. android:paddingTop="3dp"
  47. android:paddingLeft="3dp"
  48. android:paddingBottom="3dp"
  49. android:id="@+id/txt_distance" />
  50.  
  51. <TextView
  52. android:layout_width="wrap_content"
  53. android:layout_height="wrap_content"
  54. android:textSize="17dp"
  55. android:paddingLeft="3dp"
  56. android:text="Duration ?"
  57. android:id="@+id/txt_time" />
  58.  
  59. </LinearLayout>
  60.  
  61. </LinearLayout>
  62.  
  63. <android.support.design.widget.FloatingActionButton
  64. android:id="@+id/fab"
  65. android:layout_width="wrap_content"
  66. android:layout_height="wrap_content"
  67. android:layout_margin="16dp"
  68. android:clickable="true"
  69. android:src="@android:drawable/ic_dialog_map"
  70. app:layout_anchor="@id/viewA"
  71. app:layout_anchorGravity="bottom|right|end"/>
  72.  
  73. </android.support.design.widget.CoordinatorLayout>

猜你在找的Android相关文章