Calculate distance between two points in google maps V3
Asked Answered
K

17

358

How do you calculate the distance between two markers in Google maps V3? (Similar to the distanceFrom function inV2.)

Thanks..

Kuo answered 1/10, 2009 at 8:18 Comment(1)
S
519

If you want to calculate it yourself, then you can use the Haversine formula:

var rad = function(x) {
  return x * Math.PI / 180;
};

var getDistance = function(p1, p2) {
  var R = 6378137; // Earth’s mean radius in meter
  var dLat = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
    Math.sin(dLong / 2) * Math.sin(dLong / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d; // returns the distance in meter
};
Southsoutheast answered 1/10, 2009 at 9:7 Comment(11)
Why you suggest using Math.atan2(Math.sqrt(a),Math.sqrt(1-a)) instead of the simplest Math.asin(Math.sqrt(a)) ?Mohun
@TomHart Guess you found out already it returns km - I needed metres so changed the second line to var R = 6371000; // earth's mean radius in metresCharwoman
I am trying to make use this formula, but having trouble understanding what p1.lat() etc stands for - it seems to be a function - but where is it defined? I am trying to pass two objects p1 and p2 with lat and lng properties as coordinates, but it then returns d=0 - where am I going wrong?Surcingle
@EmanuelePaolini - Mathematically, atan2(sqrt(a),sqrt(1-a)) = asin(sqrt(a)) = acos(sqrt(1-a)), but the atan2 version remains numerically better conditioned for all values of a.Soniferous
Worked like a charm. Divide result by 1000 to convert to km, and by 1600 to convert to miles.Ayah
Guys. Question. Why you like it so much to use 1 letter variable names solving problems that require some imagination where good variable name could be helpful? Just asking :)Androgen
Shouldn't it be var R = 6371; for Km?Command
I am getting this errot ... lat() lng() are not a function.Mosul
The p1.lat() and p1.lng() functions assume that your input data is google.maps.LatLng objects. If you just have raw data like {lat: __, lon: __} then you would instead use p1.lat, for example.Amoreta
Hi, I am new to this. I am not able to understand what is p1 and p2. I am using like below script for calculating latitude and longitude: from_lat = from_location.geometry.location.lat(); from_long = from_location.geometry.location.lng(); // to calculate originating coordinates and to_lat = to_location.geometry.location.lat(); to_long = to_location.geometry.location.lng(); // to calculate coordinates of destination. How to implement this in your function. Please let me knowExtrusion
useful 'copypast and play' answer.Myogenic
T
325

There actually seems to be a method in GMap3. It's a static method of the google.maps.geometry.spherical namespace.

It takes as arguments two LatLng objects and will utilize a default Earth radius of 6378137 meters, although the default radius can be overridden with a custom value if necessary.

Make sure you include:

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

in your head section.

The call will be:

google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);
Tinder answered 2/2, 2011 at 12:59 Comment(14)
So why is there a 1% difference in the answer given by Google's spherical computeDistanceBetween and the Haversine distance formula?Kore
@RamenRecon I'm not certain but a quess would be that they use different values for the earths radius.Tinder
@RamenRecon yes, Emil is correct on this. The documentation says: The The default radius is Earth's radius of 6378137 meters. But Mike in the Haversine above uses 6371km instead.Huckster
The link above is now broken, but the explanation of the method makes that not much of an issue.Migrant
@Migrant Fixed the link.Tinder
I am getting different results searching google than doing a calculation myself but I wondered if it's because my calculation is 'as the crow flies' whereas google's distance probably factors in the driving distance on winding roads which would normally be longer. What do you think?Flock
@ABCD.ca, look at the commens above, you are probably using a slightly different value for the earths radius.Tinder
@EmilBadh I'm using 6371 KM which is what's documented in MongoDB's manual and seems to be what you find if you google around too. I believe I'm correct in saying that Google's calculation is based on driving distance which is longer than a as the crow flies (a direct line from point A to point BFlock
@Flock Well, google uses a radius value of 6 378 137 meters, or 6 378,137 KM compared to your 6371 KM.Tinder
@EmilBadh I wonder which is more widely accepted? Doing a google search I find my number is pretty common. Do you have a link to yours?Flock
@Flock It's not my number. This question is about version 3 of Google Maps Library. You asked why your calculation differed from theirs. It's because they use a different value for the earth's radius than you do. The reference for the number? developers.google.com/maps/documentation/javascript/… Right below the headline.Tinder
Why don't they use the elevation at the specified Lat/Lon as a default for the radius? Would be nice, but maybe too hard since a couple lookups would be required.Paracelsus
They do not use elevation because it would not effectively increase the accuracy of the measurement. The error from using the spherical approximation is too large to benefit from using what would otherwise be additional precision from using elevation.Dehydrogenase
How to get the distance between two set of longitudes and latitudes? eg lat: "24.174298041920533,17.94474539356555,16.264754926836357," lng: "-8.860805618118786,-14.134243118118786,-2.1811181181187855," and lat: "23.856953970230652,2.0773340406051526,11.147413760…3760177779,-7.568076010017119,-6.870529535424255,", lng: "0.63720703125,12.59033203125,34.73876953125,24.191…125,35.44189453125,24.01611328125,20.67626953125,"Shear
S
39

Example using GPS latitude/longitude of 2 points.

var latitude1 = 39.46;
var longitude1 = -0.36;
var latitude2 = 40.40;
var longitude2 = -3.68;

var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(latitude1, longitude1), new google.maps.LatLng(latitude2, longitude2));       
Satinwood answered 7/4, 2015 at 12:4 Comment(2)
Distance results are expressed in meters.Satinwood
@Satinwood how to require google.maps.geometry in node.js. i want to use above code in node.js . which module should i install and what files should i require.Romaineromains
D
16

Just add this to the beginning of your JavaScript code:

google.maps.LatLng.prototype.distanceFrom = function(latlng) {
  var lat = [this.lat(), latlng.lat()]
  var lng = [this.lng(), latlng.lng()]
  var R = 6378137;
  var dLat = (lat[1]-lat[0]) * Math.PI / 180;
  var dLng = (lng[1]-lng[0]) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
  Math.cos(lat[0] * Math.PI / 180 ) * Math.cos(lat[1] * Math.PI / 180 ) *
  Math.sin(dLng/2) * Math.sin(dLng/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return Math.round(d);
}

and then use the function like this:

var loc1 = new GLatLng(52.5773139, 1.3712427);
var loc2 = new GLatLng(52.4788314, 1.7577444);
var dist = loc2.distanceFrom(loc1);
alert(dist/1000);
Dorris answered 10/3, 2011 at 19:31 Comment(2)
Excellect solution but I want to know in what units it is returning the result. I got 3.013.. is that in miles,km ??Waters
The returned value is in metres. Hence dist/1000 gives you the value in km.Vitality
U
15
//p1 and p2 are google.maps.LatLng(x,y) objects

function calcDistance(p1, p2) {
          var d = (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
          console.log(d);              
}
Unbodied answered 12/10, 2015 at 13:28 Comment(3)
this is the best answer. Why add a function when Google API already has the functionsRetractor
Is there a java variant available for this API ? I could not find it after a lot of searching.Lilly
@felixfbecker, because you might be working in an environment where you cannot insert google maps API into a script tag and call those methods. Like react-native.Stepchild
C
12

With google you can do it using the spherical api, google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);.

However, if the precision of a spherical projection or a haversine solution is not precise enough for you (e.g. if you're close to the pole or computing longer distances), you should use a different library.

Most information on the subject I found on Wikipedia here.

A trick to see if the precision of any given algorithm is adequate is to fill in the maximum and minimum radius of the earth and see if the difference might cause problems for your use case. Many more details can be found in this article

In the end the google api or haversine will serve most purposes without problems.

Castorena answered 22/1, 2013 at 10:39 Comment(0)
J
11

Here is the c# implementation of the this forumula

 public class DistanceAlgorithm
{
    const double PIx = 3.141592653589793;
    const double RADIO = 6378.16;

    /// <summary>
    /// This class cannot be instantiated.
    /// </summary>
    private DistanceAlgorithm() { }

    /// <summary>
    /// Convert degrees to Radians
    /// </summary>
    /// <param name="x">Degrees</param>
    /// <returns>The equivalent in radians</returns>
    public static double Radians(double x)
    {
        return x * PIx / 180;
    }

    /// <summary>
    /// Calculate the distance between two places.
    /// </summary>
    /// <param name="lon1"></param>
    /// <param name="lat1"></param>
    /// <param name="lon2"></param>
    /// <param name="lat2"></param>
    /// <returns></returns>
    public static double DistanceBetweenPlaces(
        double lon1,
        double lat1,
        double lon2,
        double lat2)
    {
        double dlon =  Radians(lon2 - lon1);
        double dlat =  Radians(lat2 - lat1);

        double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(Radians(lat1)) * Math.Cos(Radians(lat2)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));
        double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
        return (angle * RADIO) * 0.62137;//distance in miles
    }

}    
Jozef answered 18/2, 2011 at 11:16 Comment(3)
This doesn't apply to the original question of how to do it in Google Maps.Ovotestis
There is no inbuilt function to calcuate distance directly, you have to use directory services for two points and extract the distance out of the returned XML/JSON.Jozef
My comment was on the fact that it would have been better to supply a solution in javascript, as the thread starter didn't say if he/she was using php, .net or static html.Ovotestis
L
9

Using PHP, you can calculate the distance using this simple function :

// to calculate distance between two lat & lon

function calculate_distance($lat1, $lon1, $lat2, $lon2, $unit='N') 
{ 
  $theta = $lon1 - $lon2; 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344); 
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

// function ends here
Light answered 21/6, 2012 at 7:32 Comment(2)
There is a condition in the function that if you pass the unit as K then it will give you the distance in Km. Check it.Delhi
this function works very well and it gives distance from star location to all locations. can it b travers in a way first it find the first cloasest location and it becomes as the source or start and then find it's next closest but not the first source one and so on to all?Bilbrey
M
8

OFFLINE SOLUTION - Haversine Algorithm

In Javascript

var _eQuatorialEarthRadius = 6378.1370;
var _d2r = (Math.PI / 180.0);

function HaversineInM(lat1, long1, lat2, long2)
{
    return (1000.0 * HaversineInKM(lat1, long1, lat2, long2));
}

function HaversineInKM(lat1, long1, lat2, long2)
{
    var dlong = (long2 - long1) * _d2r;
    var dlat = (lat2 - lat1) * _d2r;
    var a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r) * Math.pow(Math.sin(dlong / 2.0), 2.0);
    var c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
    var d = _eQuatorialEarthRadius * c;

    return d;
}

var meLat = -33.922982;
var meLong = 151.083853;


var result1 = HaversineInKM(meLat, meLong, -32.236457779983745, 148.69094705162837);
var result2 = HaversineInKM(meLat, meLong, -33.609020205923713, 150.77061469270831);

C#

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");

        var meLat = -33.922982;
        double meLong = 151.083853;


        var result1 = HaversineInM(meLat, meLong, -32.236457779983745, 148.69094705162837);
        var result2 = HaversineInM(meLat, meLong, -33.609020205923713, 150.77061469270831);

        Console.WriteLine(result1);
        Console.WriteLine(result2);
    }

    static double _eQuatorialEarthRadius = 6378.1370D;
    static double _d2r = (Math.PI / 180D);

    private static int HaversineInM(double lat1, double long1, double lat2, double long2)
    {
        return (int)(1000D * HaversineInKM(lat1, long1, lat2, long2));
    }

    private static  double HaversineInKM(double lat1, double long1, double lat2, double long2)
    {
        double dlong = (long2 - long1) * _d2r;
        double dlat = (lat2 - lat1) * _d2r;
        double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);
        double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));
        double d = _eQuatorialEarthRadius * c;

        return d;
    }
}

Reference: https://en.wikipedia.org/wiki/Great-circle_distance

Mesoderm answered 20/1, 2016 at 19:12 Comment(0)
C
3

Had to do it... The action script way

//just make sure you pass a number to the function because it would accept you mother in law...
public var rad = function(x:*) {return x*Math.PI/180;}

protected  function distHaversine(p1:Object, p2:Object):Number {
    var R:int = 6371; // earth's mean radius in km
    var dLat:Number = rad(p2.lat() - p1.lat());
    var dLong:Number = rad(p2.lng() - p1.lng());

    var a:Number = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
    var c:Number = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d:Number = R * c;

    return d;
}
Cupo answered 13/12, 2012 at 5:6 Comment(0)
T
3

In my case it was best to calculate this in SQL Server, since i wanted to take current location and then search for all zip codes within a certain distance from current location. I also had a DB which contained a list of zip codes and their lat longs. Cheers

--will return the radius for a given number
create function getRad(@variable float)--function to return rad
returns float
as
begin
declare @retval float 
select @retval=(@variable * PI()/180)
--print @retval
return @retval
end
go

--calc distance
--drop function dbo.getDistance
create function getDistance(@cLat float,@cLong float, @tLat float, @tLong float)
returns float
as
begin
declare @emr float
declare @dLat float
declare @dLong float
declare @a float
declare @distance float
declare @c float

set @emr = 6371--earth mean 
set @dLat = dbo.getRad(@tLat - @cLat);
set @dLong = dbo.getRad(@tLong - @cLong);
set @a = sin(@dLat/2)*sin(@dLat/2)+cos(dbo.getRad(@cLat))*cos(dbo.getRad(@tLat))*sin(@dLong/2)*sin(@dLong/2);
set @c = 2*atn2(sqrt(@a),sqrt(1-@a))
set @distance = @emr*@c;
set @distance = @distance * 0.621371 -- i needed it in miles
--print @distance
return @distance;
end 
go


--get all zipcodes within 2 miles, the hardcoded #'s would be passed in by C#
select *
from cityzips a where dbo.getDistance(29.76,-95.38,a.lat,a.long) <3
order by zipcode
Troth answered 14/4, 2014 at 19:23 Comment(2)
Not sure this is efficient for a client side usage.Underlayer
May be not a front end solution, but definitely what I was looking for. Thanks.Driftwood
E
3
//JAVA
    public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {
    final int RADIUS_EARTH = 6371;

    double dLat = getRad(latitude2 - latitude1);
    double dLong = getRad(longitude2 - longitude1);

    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return (RADIUS_EARTH * c) * 1000;
    }

    private Double getRad(Double x) {
    return x * Math.PI / 180;
    }
Extremely answered 5/6, 2014 at 10:51 Comment(0)
B
2
  /**
   * Calculates the haversine distance between point A, and B.
   * @param {number[]} latlngA [lat, lng] point A
   * @param {number[]} latlngB [lat, lng] point B
   * @param {boolean} isMiles If we are using miles, else km.
   */
  function haversineDistance(latlngA, latlngB, isMiles) {
    const squared = x => x * x;
    const toRad = x => (x * Math.PI) / 180;
    const R = 6371; // Earth’s mean radius in km

    const dLat = toRad(latlngB[0] - latlngA[0]);
    const dLon = toRad(latlngB[1] - latlngA[1]);

    const dLatSin = squared(Math.sin(dLat / 2));
    const dLonSin = squared(Math.sin(dLon / 2));

    const a = dLatSin +
              (Math.cos(toRad(latlngA[0])) * Math.cos(toRad(latlngB[0])) * dLonSin);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    let distance = R * c;

    if (isMiles) distance /= 1.609344;

    return distance;
  }

I found a version online which is 80% right but plugged in the wrong parameter and is inconsistent in using the inputs, this version fixed that completely

Birdsong answered 7/8, 2018 at 6:43 Comment(0)
W
1

It's Quite easy using Google Distance Matrix service

First step is to activate Distance Matrix service from google API console. it returns distances between a set of locations. And apply this simple function

function initMap() {
        var bounds = new google.maps.LatLngBounds;
        var markersArray = [];

        var origin1 = {lat:23.0203, lng: 72.5562};
        //var origin2 = 'Ahmedabad, India';
        var destinationA = {lat:23.0436503, lng: 72.55008939999993};
        //var destinationB = {lat: 23.2156, lng: 72.6369};

        var destinationIcon = 'https://chart.googleapis.com/chart?' +
            'chst=d_map_pin_letter&chld=D|FF0000|000000';
        var originIcon = 'https://chart.googleapis.com/chart?' +
            'chst=d_map_pin_letter&chld=O|FFFF00|000000';
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 55.53, lng: 9.4},
          zoom: 10
        });
        var geocoder = new google.maps.Geocoder;

        var service = new google.maps.DistanceMatrixService;
        service.getDistanceMatrix({
          origins: [origin1],
          destinations: [destinationA],
          travelMode: 'DRIVING',
          unitSystem: google.maps.UnitSystem.METRIC,
          avoidHighways: false,
          avoidTolls: false
        }, function(response, status) {
          if (status !== 'OK') {
            alert('Error was: ' + status);
          } else {
            var originList = response.originAddresses;
            var destinationList = response.destinationAddresses;
            var outputDiv = document.getElementById('output');
            outputDiv.innerHTML = '';
            deleteMarkers(markersArray);

            var showGeocodedAddressOnMap = function(asDestination) {
              var icon = asDestination ? destinationIcon : originIcon;
              return function(results, status) {
                if (status === 'OK') {
                  map.fitBounds(bounds.extend(results[0].geometry.location));
                  markersArray.push(new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    icon: icon
                  }));
                } else {
                  alert('Geocode was not successful due to: ' + status);
                }
              };
            };

            for (var i = 0; i < originList.length; i++) {
              var results = response.rows[i].elements;
              geocoder.geocode({'address': originList[i]},
                  showGeocodedAddressOnMap(false));
              for (var j = 0; j < results.length; j++) {
                geocoder.geocode({'address': destinationList[j]},
                    showGeocodedAddressOnMap(true));
                //outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] + ': ' + results[j].distance.text + ' in ' +                    results[j].duration.text + '<br>';
                outputDiv.innerHTML += results[j].distance.text + '<br>';
              }
            }

          }
        });
      }

Where origin1 is your location and destinationA is destindation location.you can add above two or more data.

Rad Full Documentation with an example

Wilbanks answered 16/6, 2018 at 6:34 Comment(0)
A
0

To calculate distance on Google Maps, you can use Directions API. That will be one of the easiest way to do it. To get data from Google Server, you can use Retrofit or Volley. Both has their own advantage. Take a look at following code where I have used retrofit to implement it:

private void build_retrofit_and_get_response(String type) {

    String url = "https://maps.googleapis.com/maps/";

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitMaps service = retrofit.create(RetrofitMaps.class);

    Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,dest.latitude + "," + dest.longitude, type);

    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Response<Example> response, Retrofit retrofit) {

            try {
                //Remove previous line from map
                if (line != null) {
                    line.remove();
                }
                // This loop will go through all the results and add marker on each location.
                for (int i = 0; i < response.body().getRoutes().size(); i++) {
                    String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
                    String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
                    ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
                    String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
                    List<LatLng> list = decodePoly(encodedString);
                    line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(20)
                                    .color(Color.RED)
                                    .geodesic(true)
                    );
                }
            } catch (Exception e) {
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.d("onFailure", t.toString());
        }
    });

}

Above is the code of function build_retrofit_and_get_response for calculating distance. Below is corresponding Retrofit Interface:

package com.androidtutorialpoint.googlemapsdistancecalculator;


import com.androidtutorialpoint.googlemapsdistancecalculator.POJO.Example;

import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;

public interface RetrofitMaps {


/*
 * Retrofit get annotation with our URL
 * And our method that will return us details of student.
 */
@GET("api/directions/json?key=AIzaSyC22GfkHu9FdgT9SwdCWMwKX1a4aohGifM")
Call<Example> getDistanceDuration(@Query("units") String units, @Query("origin") String origin, @Query("destination") String destination, @Query("mode") String mode);

}

I hope this explains your query. All the best :)

Source: Google Maps Distance Calculator

Anesthetist answered 22/9, 2016 at 12:29 Comment(1)
No- this calculates travel distance (on roads etc), not point-to-point geodesic distance.Elide
P
0

First, are you referring to distance as in length of the entire path or you want to know only the displacement (straight line distance)? I see no one is pointing the difference between distance and displacement here. For distance calculate each route point given by JSON/XML data, as for displacement there is a built-in solution using Spherical class

//calculates distance between two points in km's
function calcDistance(p1, p2) {
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
Perplex answered 18/1, 2021 at 4:6 Comment(0)
H
0

In PHP, with Google Map Distance Matrix API:

//Get the Driving(Mode) distance between two Geo-location points(Latitude, Longitude) pair.
function get_distance($lat1, $lat2, $long1, $long2)
{
    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving"."&units=imperial";
    //You can request distance data for different travel modes, request distance data in different units such as kilometers or miles, and estimate travel time in traffic.
    try{
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $response = curl_exec($ch);
        curl_close($ch);
        $response_a = json_decode($response, true);
        //Invalid request OR Empty response
        if(isset($response_a['error_message']) || empty($response_a['rows'])) 
            throw new Exception($response_a['error_message']);
        
    } catch(Exception $e){
        //Handle error here.
        return [];
    }
    
    //The unit parameter in the request URL only affects the text displayed within distance fields. The distance fields in response also contain values that are always expressed in meters.
    $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
    $time = $response_a['rows'][0]['elements'][0]['duration']['text'];

    return ['distance' => $dist, 'time' => $time];
}

Reference: Distance Matrix API request and response

Here answered 28/12, 2022 at 17:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.