如何从起点A到终点B获取路线的所有纬度和经度?

4
我已经尝试创建路线,但不确定如何预先获取从起点到目的地的所有纬度和经度。在地图中搜索从起点到目的地的路线时,我会选择自己喜欢的路线,并希望获取从起点到目的地的所有纬度和经度。我必须将这些数据提供给其他Java方法进行一些计算。如果有任何解决方案,请告诉我。由于我是一个地图的初学者,所以我并没有很多想法。我已经在Google和Stack Overflow上搜索过,并没有找到类似或支持的解决方案。
提前感谢, Ash

请查看此链接:https://github.com/polok/RouteDrawer - Vivek Mishra
我听说这不能用于自动驾驶车辆。我能在我的公司应用程序中使用谷歌获取方向吗? - AlexMiller
2个回答

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&alternatives=true");
    urlString.append("&key=YOUR_API_KEY");
    return urlString.toString(); }

这个函数将生成我们发送到获取方向 API 响应的 URL。然后我们将解析该响应。解析器类是

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static 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;

}}

这个解析器会返回字符串。我们会像这样调用它。

JSONParser jParser = new JSONParser();String json = jParser.getJSONFromUrl(url);

现在我们将这个字符串发送到我们的 drawpath 函数中。drawpath 函数:
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);
       Polyline line = mMap.addPolyline(new PolylineOptions()
                                .addAll(list)
                                .width(12)
                                .color(Color.parseColor("#05b1fb"))//Google maps blue color
                                .geodesic(true)
                );
       /*
       for(int z = 0; z<list.size()-1;z++){
            LatLng src= list.get(z);
            LatLng dest= list.get(z+1);
            Polyline line = mMap.addPolyline(new PolylineOptions()
            .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
            .width(2)
            .color(Color.BLUE).geodesic(true));
        }
       */
} 
catch (JSONException e) {

}} 

上述代码将在mMap上绘制路径。decodePoly的代码如下:
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;}

由于方向调用可能需要时间,因此我们将在异步任务中完成所有操作。我的异步任务是:
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(MainActivity.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);
    }
}}

请尝试这段代码,它对我有效。

谢谢,Vishal。我现在有了一个大致的想法。那么,我们需要做很多工作才能得到经纬度,是吗? - AlexMiller
PolylineOptions 具有受保护的访问权限。如何解决此错误? - Haseb Ansari

0

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