【问题标题】:Convert Polyline to Route将折线转换为路线
【发布时间】:2013-10-21 23:28:07
【问题描述】:

我有一个应用程序可以跟踪车辆并在地图上绘制其行驶路径的折线。我想使用方向服务路由将此折线转换为路线。这将使我能够拖动路径并对其进行操作等。

问题是我想不出一个好的解决方案,而且我不确定这是否可能。如果我将折线的坐标数组传递给方向服务路线,它只使用折线的起点和终点绘制路线,它不会考虑中间的任何坐标。

我尝试使用折线坐标数组生成一个“航点”数组,方法是平均划分它并在其间获取 8 个坐标并将它们作为航点传递,但它现在根本无法渲染。如果我使用通过绘制路线生成的坐标数组来测试代码,它可以工作,所以我知道代码正在工作。我假设它失败了,因为其中一些坐标可能会稍微偏离道路(它是从 GPS 定位绘制的折线,所以它不是 100% 准确的),而且 Google 不只是将它捕捉到最近的接受位置。

谁能想到解决办法?

下面是代码示例,使其更清晰:

// In the polyline app
var encoded_path = google.maps.geometry.encoding.encodePath(coordinate_array)



// In the route app
var coordinates = google.maps.geometry.encoding.decodePath(encoded_path);

var waypoints = [];

// Evenly get coordinates across the entire array to be used as waypoints
for (var i = 1; i <= 8; ++i) {
   var index = Math.floor((coordinates.length/10) * i);

   if (index >= coordinates.length - 1)
      break;

   waypoints.push({
      'location': new google.maps.LatLng(coordinates[index].lat(), coordinates[index].lng()),
      'stopover': false
   });
}

var request = {
   origin: coordinates[0],
   destination: coordinates[coordinates.length - 1],
   travelMode: google.maps.DirectionsTravelMode.DRIVING,
   waypoints: waypoints
};

MapService.directionsService.route(request, function(response, status) {
   if (status == google.maps.DirectionsStatus.OK) {
      MapService.directionsDisplay.setDirections(response);
   }
});

【问题讨论】:

  • 我有一些想法,但我需要数据来测试。你能发布一个你正在使用的坐标数组吗?
  • 你试过“optimizeWaypoints”标志吗?
  • 我没有 Tomasz,但根据选项的描述,使用它并不理想,因为它会严重地重新安排路线。司机有时会采取非有效的方式来避开某些道路/桥梁等。乍得,抱歉,我找不到任何好的例子,我丢失了测试数据。
  • 您是否将折线作为输入?您的应用程序没有其他输入吗?

标签: google-maps google-maps-api-3


【解决方案1】:

已经有一段时间了,现在有一个更好的答案,Roads API: https://developers.google.com/maps/documentation/roads/intro

Directions API 不适用于此用例,有几个很好的理由甚至不尝试:

  • 停靠点(默认)在捕捉到最近的道路时将允许任何行驶方向(进出),无论上一个/下一个航点如何。

  • 在捕捉道路时,非中途停留(通过:) 的航点将非常严格,典型的 GPS 偏移会使其偏离并导致 ZERO_RESULTS(无路线)-

  • 即使所有航路点都运行良好,该路线也将是一般驾驶员的最佳路线,不一定是对用作航路点的位置进行采样的车辆所遵循的路线。

  • 如果车辆在 2 条不同高度的道路(高架通道、桥梁、隧道等)的交汇处采样位置,如果 GPS 偏移使该点位于错误的道路上,则可以抛出路由大开眼界。

【讨论】:

    【解决方案2】:

    您可以使用方向 api 来检查路点在道路上的终点:Map of all points below a certain time of travel?。然后删除其他的以从整个折线创建路线。

    【讨论】:

      【解决方案3】:
      public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
          StringBuilder urlString = new StringBuilder();
          urlString.append("http://maps.googleapis.com/maps/api/directions/json");
          urlString.append("?origin=");// from
          urlString.append(Double.toString(sourcelat));
          urlString.append(",");
          urlString
                  .append(Double.toString( sourcelog));
          urlString.append("&destination=");// to
          urlString
                  .append(Double.toString( destlat));
          urlString.append(",");
          urlString.append(Double.toString( destlog));
          urlString.append("&sensor=false&mode=driving");
          return urlString.toString();
      

      }

      private List<LatLng> decodePoly(String encoded) {
      
          List<LatLng> poly = new ArrayList<LatLng>();
          int index = 0, len = encoded.length();
          int lat = 0, lng = 0;
      
          while (index < len) {
              int b, shift = 0, result = 0;
              do {
                  b = encoded.charAt(index++) - 63;
                  result |= (b & 0x1f) << shift;
                  shift += 5;
              } while (b >= 0x20);
              int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
              lat += dlat;
      
              shift = 0;
              result = 0;
              do {
                  b = encoded.charAt(index++) - 63;
                  result |= (b & 0x1f) << shift;
                  shift += 5;
              } while (b >= 0x20);
              int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
              lng += dlng;
      
              LatLng p = new LatLng( (((double) lat / 1E5)),
                       (((double) lng / 1E5) ));
              poly.add(p);
          }
      
          return poly;
      }
      
      
      public class JSONParser {
      
          InputStream is = null;
          JSONObject jObj = null;
          String json = "";
          // constructor
          public JSONParser() {
          }
          public String getJSONFromUrl(String url) {
      
              // Making HTTP request
              try {
                  // defaultHttpClient
                  DefaultHttpClient httpClient = new DefaultHttpClient();
                  HttpPost httpPost = new HttpPost(url);
      
                  HttpResponse httpResponse = httpClient.execute(httpPost);
                  HttpEntity httpEntity = httpResponse.getEntity();
                  is = httpEntity.getContent();           
      
              } catch (UnsupportedEncodingException e) {
                  e.printStackTrace();
              } catch (ClientProtocolException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              }
              try {
                  BufferedReader reader = new BufferedReader(new InputStreamReader(
                          is, "iso-8859-1"), 8);
                  StringBuilder sb = new StringBuilder();
                  String line = null;
                  while ((line = reader.readLine()) != null) {
                      sb.append(line + "\n");
                  }
      
                  json = sb.toString();
                  is.close();
              } catch (Exception e) {
                  Log.e("Buffer Error", "Error converting result " + e.toString());
              }
              return json;
      
          }
      }
      
      public void drawPath(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);
      
                 for(int z = 0; z<list.size()-1;z++){
                      LatLng src= list.get(z);
                      LatLng dest= list.get(z+1);
                      theMap.addPolyline(new PolylineOptions()
                      .add(src,dest)
                      .width(2)
                      .color(Color.BLUE).geodesic(true));
                  }
      
          } 
          catch (JSONException e) {
      
          }
      } 
      
      
      private class connectAsyncTask extends AsyncTask<Void, Void, String>{
              private ProgressDialog progressDialog;
              String url;
              connectAsyncTask(String urlPass){
                  url = urlPass;
      
              }
              @Override
              protected void onPreExecute() {
                  // TODO Auto-generated method stub
                  super.onPreExecute();
                  progressDialog = new ProgressDialog(YOUR_Activity.this);
                  progressDialog.setMessage("Fetching route, Please wait...");
                  progressDialog.setIndeterminate(true);
                  progressDialog.show();
              }
              @Override
              protected String doInBackground(Void... params) {
                  JSONParser jParser = new JSONParser();
                  String json = jParser.getJSONFromUrl(url);
                  return json;
              }
              @Override
              protected void onPostExecute(String result) {
                  super.onPostExecute(result);   
                  progressDialog.hide();        
                  if(result!=null){
                      drawPath(result);
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2013-02-04
        • 2020-06-16
        • 1970-01-01
        • 2019-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        相关资源
        最近更新 更多