Generating distances between two points using google maps api?

Is it possible to send two long points to google to calculate the distance between two?

+3
source share
8 answers

there is a convenient function

http://code.google.com/apis/maps/documentation/reference.html#GLatLng.distanceFrom

basically create 2 GlatLng objects, then use the above method

0
source

If you want to use the google maps v3 API, here is the function I use: Note: you must add the &libraries=geometrysource to your script

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>

Now the function:

//calculates distance between two points in km's
function calcDistance(p1, p2){
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
+10
source

. Google, . script ( JavaScript) .

+7

, Google

google api docs

java script,

function initialize() {
      if (GBrowserIsCompatible()) {
          map = new GMap2(document.getElementById("map_canvas"));
          map.setCenter(new GLatLng(52.6345701, -1.1294433), 13);
          map.addControl(new GLargeMapControl());          
          map.addControl(new GMapTypeControl());
          geocoder = new GClientGeocoder();

          // NR14 7PZ
          var loc1 = new GLatLng(52.5773139, 1.3712427);
          // NR32 1TB
          var loc2 = new GLatLng(52.4788314, 1.7577444);          
          alert(loc2.distanceFrom(loc1) / 1000);
      }
    }

+3

cal #:

// this returns the distance in miles. for km multiply result: * 1.609344
public static double CalculateDistance(double lat1, double lon1, double lat2, double lon2)
{
    double t = lon1 - lon2;
    double distance = Math.Sin(Degree2Radius(lat1)) * Math.Sin(Degree2Radius(lat2)) + Math.Cos(Degree2Radius(lat1)) * Math.Cos(Degree2Radius(lat2)) * Math.Cos(Degree2Radius(t));
    distance = Math.Acos(distance);
    distance = Radius2Degree(distance);
    distance = distance * 60 * 1.1515;

    return distance;
}

private static double Degree2Radius(double deg)
{
    return (deg * Math.PI / 180.0);
}

private static double Radius2Degree(double rad)
{
    return rad / Math.PI * 180.0;
}
+3

, , . Javascript .

- (): http://boulter.com/gps/distance/?from=51.5329855+-0.1303506&to=40.757584+-73.985642&units=m

, , . .


According to Rob, Google added it, but they still use the big circle formula, which may be 1/300 inaccurate.

+2
source

It has been many years since I did this, but you can use the Great Circle Distance

0
source

If you just want to get the distance as a number, try something like this.

function InitDistances() {
    var startLocation = new GLatLng(startLat, startLon);
    var endLocation = new GLatLng(endLat, endLon);
    var dist = startLocation .distanceFrom(endLocation);

    // Convert distance to miles with two decimal points precision
    return (dist / 1609.344).toFixed(2);
}
0
source

Source: https://habr.com/ru/post/1702626/


All Articles