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

问题描述 投票:28回答:10

我需要在两个位置之间获得距离,但我需要像图中的蓝线一样得到距离。

我接下来尝试:

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

但我得到红线距离。

android google-maps android-location
10个回答
30
投票

使用Google Maps Directions API。您需要通过HTTP请求指示。您可以直接从Android或通过自己的服务器执行此操作。

例如,来自Montreal to Toronto的路线:

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
           },

您还可以直接从响应对象获取折线信息。


-4
投票

要查找2个位置之间的距离:

  1. 首次打开应用程序时,请从左上角的下拉菜单中转到“您的时间轴”。
  2. 打开新窗口后,从右上方菜单中选择设置,然后选择“添加地点”。
  3. 添加您的地点并将其命名为点1,点2或任何容易记住的名称。
  4. 添加并标记您的地点后,请返回Google应用中的主窗口。
  5. 点击右下方带箭头的蓝色圆圈。
  6. 将打开一个新窗口,您可以在顶部看到有两个文本字段,您可以在其中添加“从位置”和“距离位置”。
  7. 单击任何文本字段,然后在第3点中键入您保存的位置。
  8. 单击其他文本字段并添加下一个保存的位置。
  9. 通过这样做,Google地图将计算两个位置之间的距离,并在地图上显示蓝色路径。

10
投票

正如克里斯布罗德福特是正确的,要解析返回的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"));

3
投票

您可以在android中使用以下Location方法(如果你有lat,两个位置的长度),该方法返回以米为单位的近似距离。

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结束经度

得到一个浮点数组来保存结果


2
投票

用这个:

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

2
投票
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;
}

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

希望这可以帮助。


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

-1
投票

试试这段代码

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

-1
投票
private String getDistance(double lat2, double lon2){
    Location loc1 = new Location("A");
    loc1.setLatitude("A1");
    loc1.setLongitude("B1");
    Location loc2 = new Location("B");
    loc2.setLatitude(lat2);
    loc2.setLongitude(lon2);
    float distanceInMeters = loc1.distanceTo(loc2);
    float mile = distanceInMeters / 1609.34f;
    String sm = String.format("%.2f", mile);
    return sm;
}
© www.soinside.com 2019 - 2024. All rights reserved.