如何在Android中绘制路线并计算谷歌地图上多个标记之间的距离

时间:2019-03-01 05:17:02

标签: android google-maps marker

在我的应用中,用户可以插入多个位置并在地图中显示。我怎样才能做到这一点?我知道如何在两个位置之间绘制路线,但我想像图像一样在多个标记之间绘制路线。 enter image description here

在图像标记中显示用户输入的位置。我还想计算标记之间的距离,例如计算B到C和C到D的距离。

我该如何实现?

4 个答案:

答案 0 :(得分:1)

使用Direction api,它使用一系列航路点返回多部分路线。

Direction api Documentation

private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,-73.998585);
private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);
private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094);

    private String getMapsApiDirectionsUrl() {
        String origin = "origin=" + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude;
        String waypoints = "waypoints=optimize:true|" + BROOKLYN_BRIDGE.latitude + "," + BROOKLYN_BRIDGE.longitude + "|";
        String destination = "destination=" + WALL_STREET.latitude + "," + WALL_STREET.longitude;

        String sensor = "sensor=false";
        String params = origin + "&" + waypoints + "&"  + destination + "&" + sensor;
        String output = "json";
        String url = "https://maps.googleapis.com/maps/api/directions/"
                + output + "?" + params;
        return url;
    }
}

当您收到上述请求的回复时。您需要从响应中绘制路线

public void drawRoute(String result) {

    try {
        //Tranform the string into a json object
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");
        List<LatLng> list = decodePoly(encodedString);

        Polyline line = mMap.addPolyline(new PolylineOptions()
                .addAll(list)
                .width(12)
                .color(Color.parseColor("#05b1fb"))//Google maps blue color
                .geodesic(true)
        );

    } catch (JSONException e) {

    }
}  

您将从Draw-route-github

中获得更多详细信息

对于距离计算,您需要 Distance Matrix API (距离矩阵API),该服务为起点和目的地矩阵提供行进距离和时间

答案 1 :(得分:0)

使用Direction api可以实现此目的。 您只需要按照以下步骤传递用户插入的标记作为路标

https://maps.googleapis.com/maps/api/directions/json?
origin=sydney,au&destination=perth,au
&waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008
&key=YOUR_API_KEY

您将获得到点之间的距离的路线列表

//改造

  @GET("https://maps.googleapis.com/maps/api/directions/json")
    Observable<DirectionResults> getDirectionWithWayPoints(@Query("origin") String origin, @Query("destination") String destination, @Query("waypoints") String wayPoints, @Query("key") String key);

//绘图逻辑

 api.getDirectionWithWayPoints(startPoint, endPoint, stringBuilder.toString(), getString(R.string.API_KEY))
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribeWith(new Observer<DirectionResults>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(DirectionResults directionResults) {
                                    hideDialog();
                                    if (null == directionResults) {
                                        return;
                                    }


                                    ArrayList<LatLng> routelist = new ArrayList<>();
                                    routelist.add(latLngStart);
                                    if (directionResults.getRoutes().size() > 0) {
                                        List<LatLng> decodelist;
                                        RoutesItem routeA = directionResults.getRoutes().get(0);

                                        if (routeA.getLegs().size() > 0) {

                                            for (int j = 0; j < routeA.getLegs().size(); j++) {


                                            List<StepsItem> steps = routeA.getLegs().get(j).getSteps();

                                            StepsItem step;
                                            Location location;
                                            String polyline;
                                            for (int i = 0; i < steps.size(); i++) {
                                                step = steps.get(i);


                                                polyline = step.getPolyline().getPoints();
                                                decodelist = DirectionsJSONParser.decodePoly(polyline);
                                                routelist.addAll(decodelist);


                                            }
                                        }
                                        }
                                    }

                                    if (routelist.size() > 0) {


                                        routelist.add(latLngEnd);

                                        rectLine = new PolylineOptions().width(12).color(
                                                Color.CYAN);

                                        for (int i = 0; i < routelist.size(); i++) {
                                            rectLine.add(routelist.get(i));
                                        }
                                        // Adding route on the map

                                        if (null != mMap) {
                                            mMap.addPolyline(rectLine);

                                            fixZoom(rectLine, mMap);
                                            getVehicleId();

                                        }
                                    }

                                }

                                @Override
                                public void onError(Throwable e) {
                                    hideDialog();
                                    e.printStackTrace();
                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                }


            }

答案 2 :(得分:0)

Google提供了开箱即用的库来解决此类问题。

我将以以下方式构建应用程序。

  1. 使用Retrofit 2连接到网络。 (https://square.github.io/retrofit/
  2. 使用google API,您将需要多个API来完成这两项任务。

    2.a要找出两点之间的距离,请使用Google Distance Matrix API(https://developers.google.com/maps/documentation/distance-matrix/start)。

    2.b要添加多个标记,您可以参考以下答案 Google Maps JS API v3 - Simple Multiple Marker Example

答案 3 :(得分:0)

For draw route you can use :

PolylineOptions options = new 
      PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
      for (int z = 0; z < list.size(); z++) {
      LatLng point = list.get(z);
      options.add(point);
    }
   line = myMap.addPolyline(options);

And calculating distance for usimg **Google Maps Direction API**