【问题标题】:Finding road distance between two coordinates in google map android在谷歌地图android中查找两个坐标之间的道路距离
【发布时间】:2014-09-13 05:07:03
【问题描述】:

我正在使用下面这段代码在android中查找两组坐标之间的道路距离:

public String getDistance(double lat1, double lon1, double lat2, double lon2) {
        String result_in_kms = "";
        String url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
        String tag[] = {"text"};
        HttpResponse response = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            response = httpClient.execute(httpPost, localContext);
            InputStream is = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            org.w3c.dom.Document doc = builder.parse(is);
            if (doc != null) {
                NodeList nl;
                ArrayList args = new ArrayList();
                for (String s : tag) {
                    nl = doc.getElementsByTagName(s);
                    if (nl.getLength() > 0) {
                        Node node = nl.item(nl.getLength() - 1);
                        args.add(node.getTextContent());
                    } else {
                        args.add(" - ");
                    }
                }
                result_in_kms =String.valueOf( args.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //Float f=Float.valueOf(result_in_kms);
        return result_in_kms;
    }

但我得到的不是它们之间的距离而是一个'-'。上面的代码有什么问题,我从这篇文章中得到了它:

How to find distance (by road) between 2 geo points in Android application without using google map direction api?

【问题讨论】:

标签: java android eclipse google-maps-api-2


【解决方案1】:

请尝试如下所示的工作代码:

public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){

        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
                    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    response = iStreamToString(in);

                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray array = jsonObject.getJSONArray("routes");
                    JSONObject routes = array.getJSONObject(0);
                    JSONArray legs = routes.getJSONArray("legs");
                    JSONObject steps = legs.getJSONObject(0);
                    JSONObject distance = steps.getJSONObject("distance");
                    parsedDistance=distance.getString("text");

                    Log.v("Distsnce","Distance>>"+parsedDistance);

                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return parsedDistance;
    }


  public String iStreamToString(InputStream is1)
    {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
        String line;
        StringBuilder sb =  new StringBuilder();
        try {
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String contentOfMyInputStream = sb.toString();
        return contentOfMyInputStream;
    }

//用你的出发地和目的地的经纬度调用上面的方法。

例如:

  getDistance(23.0225,72.5714,21.1702,72.8311);

【讨论】:

    【解决方案2】:

    使用下面的方法,你会得到两个 lat long 的差异。

    public float getDistance(double lat1, double lon1, double lat2, double lon2) {
                   android.location.Location homeLocation = new android.location.Location("");
                    homeLocation .setLatitude(lat1);
                    homeLocation .setLongitude(lon1);
    
                    android.location.Location targetLocation = new android.location.Location("");
                    targetLocation .setLatitude(lat2);
                    targetLocation .setLongitude(lon2);
    
                     float distanceInMeters =  targetLocation.distanceTo(homeLocation);
                     return distanceInMeters ;
    }
    

    如果您想要以公里为单位的距离,请将其转换为公里。

    【讨论】:

    • 那个距离是直线距离,我要道路距离。
    • 如果你想要最短的路径距离,你可以使用'distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)'请看link
    猜你喜欢
    • 1970-01-01
    • 2012-04-29
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2014-10-28
    相关资源
    最近更新 更多