喵喵时光机
使用谷歌地图距离矩阵 api 通过给定代码查找从源到目的地的路径DateTime now = new DateTime(); try { DirectionsResult result = DirectionsApi.newRequest(getGeoContext()) .mode(TravelMode.DRIVING) .origin(new com.google.maps.model.LatLng(fromLat, fromLng)) .destination(new com.google.maps.model.LatLng(ToLat, ToLng)) .departureTime(now) .await(); addMarkersToMap(result, googleMap); addPolyline(result, googleMap); if (loader!=null && loader.isShowing()){ loader.dismiss(); } } catch (ApiException ignored) { Log.e("Exception"," "+ignored.getMessage()); } catch (InterruptedException | IOException e) { e.printStackTrace(); Log.e("Exception"," InterruptedException "+e.getMessage()); }添加标记private void addMarkersToMap(DirectionsResult results, GoogleMap mMap) { mMap.addMarker(new MarkerOptions().position( new LatLng(results.routes[0].legs[0].startLocation.lat,results.routes[0].legs[0].startLocation.lng)) .title(from) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))); mMap.addMarker(new MarkerOptions().position( new LatLng(results.routes[0].legs[0].endLocation.lat,results.routes[0].legs[0].endLocation.lng)) .title(to) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); }绘制折线并超时以从谷歌的服务器获取数据private GeoApiContext getGeoContext() { GeoApiContext geoApiContext = new GeoApiContext(); return geoApiContext.setQueryRateLimit(3) .setApiKey(getString(R.string.directionsApiKey)) .setConnectTimeout(1, TimeUnit.SECONDS) .setReadTimeout(1, TimeUnit.SECONDS) .setWriteTimeout(1, TimeUnit.SECONDS); }private void addPolyline(DirectionsResult results, GoogleMap mMap) { List<LatLng> decodedPath = PolyUtil.decode(results.routes[0].overviewPolyline.getEncodedPath()); int PATTERN_DASH_LENGTH_PX = 20; int PATTERN_GAP_LENGTH_PX = 20; PatternItem DASH = new Dash(PATTERN_DASH_LENGTH_PX); PatternItem GAP = new Gap(PATTERN_GAP_LENGTH_PX); List<PatternItem> PATTERN_POLYGON_ALPHA = Arrays.asList(GAP, DASH); mMap.addPolyline(new PolylineOptions() .geodesic(true) .color(getResources().getColor(R.color.colorPrimary)) .width(5) .pattern(PATTERN_POLYGON_ALPHA) .addAll(decodedPath)); }