【问题标题】:How to draw route and calculate distance between multiple markers on google map in android如何在android中的谷歌地图上绘制路线并计算多个标记之间的距离
【发布时间】:2019-07-23 02:46:28
【问题描述】:

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

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

我怎样才能做到这一点?

【问题讨论】:

    标签: android google-maps marker


    【解决方案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获得更多详细信息

    对于距离计算,您需要 Distance Matrix API 是一项为起点和目的地矩阵提供旅行距离和时间的服务

    【讨论】:

      【解决方案2】:

      使用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() {
      
                                      }
                                  });
                      }
      
      
                  }
      

      【讨论】:

        【解决方案3】:

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

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

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

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

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

        【讨论】:

          【解决方案4】:
          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**
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-01-02
            • 2016-10-16
            • 1970-01-01
            • 2016-02-27
            • 2021-05-15
            相关资源
            最近更新 更多