简体   繁体   English

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

[英]Get the distance between two locations in android?

i need to get distance between two location, but i need to get distance like blue line in the picture.我需要获得两个位置之间的距离,但我需要获得像图中蓝线这样的距离。图片

I try next:我接下来尝试:

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

but i get red line distance.但我得到了红线距离。

Use the Google Maps Directions API .使用Google 地图路线 API You'll need to request the directions over HTTP.您需要通过 HTTP 请求路线。 You can do this directly from Android, or via your own server.您可以直接从 Android 或通过您自己的服务器执行此操作。

For example, directions from Montreal to Toronto :例如,从蒙特利尔到多伦多的路线:

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

You'll end up with some JSON.你最终会得到一些 JSON。 In routes[].legs[].distance , you'll get an object like this:routes[].legs[].distance ,你会得到一个像这样的对象:

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

You can also get the polyline information directly from the response object.您还可以直接从响应对象中获取折线信息。

As Chris Broadfoot is correct, to parse returned JSON routes[].legs[].distance由于 Chris Broadfoot 是正确的,解析返回的 JSON routes[].legs[].distance

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

Use:采用:

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

You can use following method of Location class in android (if u have lat, longs of both the locations) the method returns approximate distance in meters.您可以在 android 中使用 Location 类的以下方法(如果您有两个位置的经纬度),该方法返回以米为单位的近似距离。

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

Explanation:解释:

Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them.计算两个位置之间的近似距离(以米为单位),并可选择计算它们之间最短路径的初始和最终方位。 Distance and bearing are defined using the WGS84 ellipsoid.距离和方位是使用 WGS84 椭球定义的。

The computed distance is stored in results[0] .计算出的距离存储在results[0] If results has length 2 or greater, the initial bearing is stored in results[1] .如果结果的长度为 2 或更大,则初始方位存储在results[1] If results has length 3 or greater, the final bearing is stored in results[2] .如果结果的长度为 3 或更大,则最终方位存储在results[2] Parameters:参数:

startLatitude - the starting latitude startLatitude - 起始纬度

startLongitude the starting longitude startLongitude 起始经度

endLatitude the ending latitude endLatitude 结束纬度

endLongitude the ending longitude endLongitude 结束经度

results an array of floats to hold the results结果 用于保存结果的浮点数组

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

Use This:用这个:

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

Try this:试试这个:

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

Hope this helps.希望这可以帮助。

You can use any Distance API.您可以使用任何距离 API。 Google API is one of the most popular, but there are also some alternatives, like Distance Matrix API: Documentation Google API 是最受欢迎的 API 之一,但也有一些替代方案,例如距离矩阵 API:文档

It is very easy to use because you don't need to rewrite code if you were used to using Google Maps API before.它非常易于使用,因为如果您以前使用过 Google Maps API,则无需重写代码。

Here is an example of the request:这是请求的示例:

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

And this is the response example:这是响应示例:

{
  "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"
}

Disclaimer: I work at a company that creates this API.免责声明:我在一家创建此 API 的公司工作。

try this code试试这个代码

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

To find the distance between 2 locations:要查找 2 个位置之间的距离:

  1. When you first open the app, go to "your timeline" from the drop menu on the top left.首次打开应用程序时,从左上角的下拉菜单中转到“您的时间线”。

  2. Once the new window opens, choose from the settings on your top right menu and choose "add place".新窗口打开后,从右上角菜单的设置中进行选择,然后选择“添加地点”。

  3. Add your places and name them like point 1, point 2, or any easy name to remember.添加您的地点并将它们命名为第 1 点、第 2 点或任何易于记住的名称。

  4. Once your places are added and flagged, go back to the main Window in your Google app.添加并标记您的地点后,返回 Google 应用程序的主窗口。

  5. Click on the blue circle with the arrow in your bottom right.单击右下角带有箭头的蓝色圆圈。

  6. A new window will open, and you can see on the top there are two text fields in which you can add your "from location" and "distance location".将打开一个新窗口,您可以在顶部看到两个文本字段,您可以在其中添加“从位置”和“距离位置”。

  7. Click on any text field and type in your saved location in point 3.单击任何文本字段并在第 3 点中输入您保存的位置。

  8. Click on the other text field and add your next saved location.单击另一个文本字段并添加下一个保存的位置。

  9. By doing so, Google Maps will calculate the distance between the two locations and show you the blue path on the map.通过这样做,谷歌地图将计算两个位置之间的距离,并在地图上显示蓝色路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM