Get the distance between two locations in android?

前端 未结 10 514
醉梦人生
醉梦人生 2020-11-28 07:57

i need to get distance between two location, but i need to get distance like blue line in the picture. \"picure\"

相关标签:
10条回答
  • 2020-11-28 08:28

    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;
    }
    
    0 讨论(0)
  • 2020-11-28 08:34

    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.

    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.

    The computed distance is stored in results[0]. If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]. Parameters:

    startLatitude - the starting latitude

    startLongitude the starting longitude

    endLatitude the ending latitude

    endLongitude the ending longitude

    results an array of floats to hold the results

    0 讨论(0)
  • 2020-11-28 08:39

    To find the distance between 2 locations:

    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.

    4. Once your places are added and flagged, go back to the main Window in your Google app.

    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.

    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.

    0 讨论(0)
  • 2020-11-28 08:46

    You can use any Distance API. Google API is one of the most popular, but there are also some alternatives, like Distance Matrix API: Documentation

    It is very easy to use because you don't need to rewrite code if you were used to using Google Maps API before.

    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.

    0 讨论(0)
  • 2020-11-28 08:47

    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;
        }
    
    0 讨论(0)
  • 2020-11-28 08:48

    As Chris Broadfoot is correct, to parse returned 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"));
    
    0 讨论(0)
提交回复
热议问题