A Blog about latest jobs updates, trending topics and different ways of earning money online.

How to calculate distance between two coordinates using Google Map API in PHP

Program to get distance using MAP API

This is a tech post if you are not a Software person or not related to programming field then its not for you.
Today in this post we are going to answer very common asked question on internet that how do we calculate actual distance between two points or two coordinates in PHP using google map API.
For this we must need a google map API other wise there is a different formula to calculate distance (not actually distance but displacement) without any Google map API.

Note: Google map API is still free but you need to enter your Credit Card details first to use there services.

Hence we know during development some time we need to calculate the distance and have to save that distance and time also (there is another way you can auto calculate the distance and time but its actually redirect you to google map page you can only see that record not allowed to fetch that record inn your web or portal.)

So lets start..

First of we need two points Coordinates. like point one (30.3939002,67.7168905) and point two is (33.5651107,73.0169135) . Note: we can also find distance using location addresss but we discuess that method in some other post. We can also find coordinates of an address using google map API.

Now we have two coordinates.
2nd we need Google map API to get started.
To get google map API Click here get API

get map api from google developer panel

Code to calculate distance and time between two coordinates using google map api.
get distance between two points using map api in php
Code here:
<?php
        $point1 = '30.3939002,67.7168905';
        $point2 = '33.5651107,73.0169135';
        
        $data = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$point1."&destinations=".$point2."&key=MAP_API_KEY_HERE");
        
        $record = json_decode($data);
        
        echo round(((int)$record->rows[0]->elements[0]->distance->value / 1000),1).' kilometers';
        
        echo $record->rows[0]->elements[0]->duration->text;
              

?>

If you dont want to use MAP API and only want to get see distance then you can use Google MAP URL and put coordinates in it.


https://www.google.com/maps/dir/(point_one_coordinates)/(point_two_coordinates)

Click here to see live demo

Previous
Next Post »

Popular posts