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

问题描述 投票:3回答:4

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

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

我怎么能实现这个?

android google-maps marker
4个回答
1
投票

使用方向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获得更多细节

对于距离计算,您需要距离矩阵API是一种服务,它为起始和目的地矩阵提供行程距离和时间


0
投票

使用方向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() {

                                }
                            });
                }


            }

0
投票

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

我会按照以下方式构建我的应用程序。

  1. 使用Retrofit 2连接到网络。 (https://square.github.io/retrofit/
  2. 使用谷歌API,您将需要超过1个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

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**
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.