Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. picure

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.

like image 453
Kostya Khuta Avatar asked Aug 19 '13 09:08

Kostya Khuta


People also ask

Can Google Maps calculate distance?

You can measure distance on Google Maps to give you the approximate mileage between any two points (or more) that you place on the map. When using Google Maps on a computer, right-click a spot on the map and choose Measure distance, then just click to add more points to measure the distance.

How do you calculate travel distance?

To solve for distance use the formula for distance d = st, or distance equals speed times time. Rate and speed are similar since they both represent some distance per unit time like miles per hour or kilometers per hour. If rate r is the same as speed s, r = s = d/t.


1 Answers

Use the Google Maps Directions API. You'll need to request the directions over HTTP. You can do this directly from Android, or via your own server.

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. In routes[].legs[].distance, you'll get an object like this:

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

You can also get the polyline information directly from the response object.

like image 145
Chris Broadfoot Avatar answered Sep 24 '22 06:09

Chris Broadfoot