将折线转换为路径

14
我有一个应用程序,可以跟踪车辆并在地图上绘制它们的路径。我想使用路线指示服务将此折线转换为路线。这将允许我拖动路径并进行操作等。
问题是我无法想到一个好的解决方案,并且我不确定是否可能。如果我将折线的坐标数组传递给路线指示服务,它只会使用折线的起点和终点来绘制路线,而不考虑中间的任何坐标。
我尝试使用折线坐标数组生成“途经点”数组,通过平均分割它并获取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);
   }
});

我有一些想法,但我需要数据来测试。你能发布一组你正在使用的坐标数组吗? - Chad Killingsworth
你尝试过使用“optimizeWaypoints”标志吗? - Tomasz Rozmus
我没有Tomasz,但根据选项的描述,使用它并不理想,因为它会严重重新排列路线。司机有时会走非高效的路线以避开某些道路/桥梁等。Chad,抱歉,我找不到任何好的例子给你,我丢失了测试数据。 - andro1d
你的输入是折线吗?难道你的应用没有其他输入吗? - Sagar Nayak
3个回答

2

有一个更好的答案,现在是Roads API:

https://developers.google.com/maps/documentation/roads/intro

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

  • 停留点(默认)将允许任何方向的行驶,在吸附到最近的道路时,无论前一个/后一个路标如何。

  • 不是停留点(via:)的路标在吸附到道路时会非常严格,典型的GPS偏移会使其偏离并导致ZERO_RESULTS(没有路线)。

  • 即使所有路标都很好,路线也是通用司机的最佳路线,不一定是采样位置的车辆实际行驶路线。

  • 如果车辆在不同高度的2条道路交叉口处采样位置(高架桥、隧道等),如果GPS偏移使点位于错误的道路上,则可能会使路由大幅偏离。


0

-1
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);
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接