在Android中获取两个位置之间的距离?

33

我需要获取两个位置之间的距离,但是我需要像图片中蓝线一样获取距离。

我尝试使用下面的方法:

public double getDistance(LatLng LatLng1, LatLng LatLng2) {
    double distance = 0;
    Location locationA = new Location("A");
    locationA.setLatitude(LatLng1.latitude);
    locationA.setLongitude(LatLng1.longitude);
    Location locationB = new Location("B");
    locationB.setLatitude(LatLng2.latitude);
    locationB.setLongitude(LatLng2.longitude);
    distance = locationA.distanceTo(locationB);

    return distance;
}

但我得到了红线距离。


1
你好,你不需要使用谷歌地图,可以使用数学计算来实现 [http://www.movable-type.co.uk/scripts/latlong.html][1]谢谢 - Felquir
1
如果您想计算路线的距离,而不是红线,则必须使用谷歌API!该API将返回您的距离和预计覆盖距离所需的时间! - Tarsem Singh
它只是返回两个位置之间的距离计算结果...如果你想要红线,可以使用Google API。 - Piyush
9个回答

33

使用 Google Maps Directions API。您需要通过 HTTP 请求方向。您可以直接从 Android 上进行请求,或通过自己的服务器进行请求。

例如,从蒙特利尔到多伦多的路线:

GET http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false

您最终将得到一些 JSON 数据。在 routes[].legs[].distance 中,您将获得这样一个对象:

     "legs" : [
        {
           "distance" : {
              "text" : "542 km",
              "value" : 542389
           },

你也可以直接从响应对象中获取折线信息。


你好,你有没有想过如何在JSON中将千米转换为米? - sweetzyl pili
不幸的是,“Keyless access to Google Maps Platform is deprecated”。请更新您的答案。 - Shashanth

12

正如Chris Broadfoot所说,解析返回的JSON需要使用 routes[].legs[].distance

"legs" : [
        {
           "distance" : {
              "text" : "542 km",
              "value" : 542389
           }

使用:

    final JSONObject json = new JSONObject(result);
    JSONArray routeArray = json.getJSONArray("routes");
    JSONObject routes = routeArray.getJSONObject(0);

    JSONArray newTempARr = routes.getJSONArray("legs");
    JSONObject newDisTimeOb = newTempARr.getJSONObject(0);

    JSONObject distOb = newDisTimeOb.getJSONObject("distance");
    JSONObject timeOb = newDisTimeOb.getJSONObject("duration");

    Log.i("Diatance :", distOb.getString("text"));
    Log.i("Time :", timeOb.getString("text"));

4
public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){
    String parsedDistance;
    String response;

    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 = org.apache.commons.io.IOUtils.toString(in, "UTF-8");

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

4
为什么你没有传递参数“&key=YOUR_API_KEY”? - gaurang

3

使用以下内容:

private String getDistanceOnRoad(double latitude, double longitude,
            double prelatitute, double prelongitude) {
        String result_in_kms = "";
        String url = "http://maps.google.com/maps/api/directions/xml?origin="
                + latitude + "," + longitude + "&destination=" + prelatitute
                + "," + prelongitude + "&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();
            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.format("%s", args.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result_in_kms;
    }

3

在 Android 中,如果您有两个位置的经纬度信息,可以使用 Location 类的以下方法来计算它们之间的近似距离(以米为单位)。

public static void distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)

解释:

该方法用于计算两个位置之间的近似距离和最短路径的初始和最终方位角。距离和方位角是基于 WGS84 椭球体定义的。

计算出的距离存储在 results[0] 中。如果结果长度大于或等于 2,则初始方位角存储在 results[1] 中。如果结果长度大于或等于 3,则最终方位角存储在 results[2] 中。 参数:

startLatitude - 起始纬度

startLongitude 起始经度

endLatitude 终点纬度

endLongitude 终点经度

results 用于存储结果的浮点数组


0

试试这段代码

public double CalculationByDistance(LatLng StartP, LatLng EndP) {
    int Radius = 6371;// radius of earth in Km
    double lat1 = StartP.latitude;
    double lat2 = EndP.latitude;
    double lon1 = StartP.longitude;
    double lon2 = EndP.longitude;
    double dLat = Math.toRadians(lat2 - lat1);
    double dLon = Math.toRadians(lon2 - lon1);
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
            + Math.cos(Math.toRadians(lat1))
            * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
            * Math.sin(dLon / 2);
    double c = 2 * Math.asin(Math.sqrt(a));
    double valueResult = Radius * c;
    double km = valueResult / 1;
    DecimalFormat newFormat = new DecimalFormat("####");
    int kmInDec = Integer.valueOf(newFormat.format(km));
    double meter = valueResult % 1000;
    int meterInDec = Integer.valueOf(newFormat.format(meter));
    Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
            + " Meter   " + meterInDec);

    return Radius * c;
}

这将从直线角度返回一个值。我不认为这是OP的意图。无论如何,这是一种很棒的方法;-)。 - Taslim Oseni

0

试试这个:

private double calculateDistance(double fromLong, double fromLat,
            double toLong, double toLat) {
        double d2r = Math.PI / 180;
        double dLong = (toLong - fromLong) * d2r;
        double dLat = (toLat - fromLat) * d2r;
        double a = Math.pow(Math.sin(dLat / 2.0), 2) + Math.cos(fromLat * d2r)
                * Math.cos(toLat * d2r) * Math.pow(Math.sin(dLong / 2.0), 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = 6367000 * c;
        return Math.round(d);
    }

希望这能有所帮助。

5
楼主想要蓝线,而不是红线。 - LuckyMe

0

您可以使用任何距离API。Google API是最受欢迎的之一,但也有其他一些替代方案,例如距离矩阵API:文档

它非常易于使用,因为如果您以前习惯使用Google Maps API,则无需重写代码。

以下是请求示例:

Get: https://api.distancematrix.ai/distancematrix?origins=51.4822656,-0.1933769&destinations=51.4994794,-0.1269979&key=<your_access_token>

这是响应示例:

{
  "destination_addresses":["Westminster Abbey, Westminster, 
  London SW1P 3PA, UK"],
  "origin_addresses":["Chapel, Fulham, London SW6 1BA, UK"],
  "rows":[
    {
      "elements":[
        {
          "distance":{
            "text": "4.7 miles",
            "value": 7563.898
          },
          "duration":{
            "text": "28 min",
            "value": 1680
          },
          "duration_in_traffic":{
            "text": "28 min",
            "value": 1680
          },
          "status": "OK"
        }
      ]
    }
  ],
  "status": "OK"
}

声明:我在一家创建此API的公司工作。


-4

如何查找两个位置之间的距离:

  1. 打开应用程序后,从左上角的下拉菜单中选择“您的时间轴”。

  2. 新窗口打开后,从右上角菜单中选择“添加地点”。

  3. 添加您的地点并将它们命名为点1、点2或任何易于记忆的名称。

  4. 一旦您的地点被添加并标记,返回到您的Google应用程序的主窗口。

  5. 点击右下角的蓝色圆圈和箭头。

  6. 一个新窗口将打开,在顶部可以看到两个文本字段,您可以在其中添加“起始位置”和“目标位置”。

  7. 单击任何文本字段并键入保存在点3中的位置。

  8. 单击另一个文本字段并添加下一个保存的位置。

  9. 这样做,谷歌地图将计算两个位置之间的距离,并在地图上显示蓝色路径。


这个问题是关于如何在Android程序中编程地找到两点之间距离的。这个答案是错误的。 - Pang

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