AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home PHP and MySQL

Distance Between Two Addresses using Google Maps API and PHP

Google Maps API and PHP

Lakshika Mathur by Lakshika Mathur
December 20, 2019
Reading Time: 3 mins read
0
Distance Between Two Addresses using Google Maps API and PHP

The use of the geocoding process is to change the address into geographic coordinates. Therefore, the Google Maps Geocoding API offers an easy way to fetch geographic data from the address. Usually, We need Geocoding API to get the latitude and longitude of an address in the web application. Apart from this, You can use Google Maps Geocoding API for a lot of purposes linked to the Geocoding data.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

The distance calculation is valuable when your web application works with the user’s location. So, you can calculate the distance among addresses using Google Maps API and PHP. In this tutorial, we will explain to you how to calculate the distance between two addresses with Google Maps Geocoding API using PHP.

To use the Google Maps Geocoding API, you only need to stipulate the API Key in your appeal. Before proceeding, create an API key on Google Cloud Platform Console for Geocoding API.

All the distance calculation code is gathered into a PHP function to make it reusable. The getDistance() function receives three parameters and calculates the distance between two addresses using Google Maps Geocoding API and PHP.

  • $addressFrom  – Staring point address. Required. 
  • $addressTo  – The endpoint address. Required.
  • $unit  – Optional. You can specify your desired unit (K – kilometer, M – meters). But, the default unit is miles. 

SEE ALSO: Add Custom Marker Icons to Google Map Dynamically from the Database with PHP and MySQL

Calculate Distance Between Two Address

The getDistance() function helps to get the distance between two addresses using PHP.

  • Specify your Google Maps API key.
  • Choose the new format of the addresses.
  • Initiate the Geocoding API request and specify the output format and address to fetch the geographic data.
  • Recover the latitude and longitude from the geodata.
  • Calculate the distance between latitude and longitude.
  • Change unit and return distance.
/**
 * @function getDistance()
 * Calculates the distance between two address
 * 
 * @params
 * $addressFrom - Starting point
 * $addressTo - End point
 * $unit - Unit type
 * 
 * @author Allsweb
 * @url https://www.allsweb.com
 *
 */
function getDistance($addressFrom, $addressTo, $unit = ''){
    // Google API key
    $apiKey = 'Your_Google_API_Key';
    
    // Change address format
    $formattedAddrFrom    = str_replace(' ', '+', $addressFrom);
    $formattedAddrTo     = str_replace(' ', '+', $addressTo);
    
    // Geocoding API request with start address
    $geocodeFrom = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false&key='.$apiKey);
    $outputFrom = json_decode($geocodeFrom);
    if(!empty($outputFrom->error_message)){
        return $outputFrom->error_message;
    }
    
    // Geocoding API request with end address
    $geocodeTo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false&key='.$apiKey);
    $outputTo = json_decode($geocodeTo);
    if(!empty($outputTo->error_message)){
        return $outputTo->error_message;
    }
    
    // Get latitude and longitude from the geodata
    $latitudeFrom    = $outputFrom->results[0]->geometry->location->lat;
    $longitudeFrom    = $outputFrom->results[0]->geometry->location->lng;
    $latitudeTo        = $outputTo->results[0]->geometry->location->lat;
    $longitudeTo    = $outputTo->results[0]->geometry->location->lng;
    
    // Calculate distance between latitude and longitude
    $theta    = $longitudeFrom - $longitudeTo;
    $dist    = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
    $dist    = acos($dist);
    $dist    = rad2deg($dist);
    $miles    = $dist * 60 * 1.1515;
    
    // Convert unit and return distance
    $unit = strtoupper($unit);
    if($unit == "K"){
        return round($miles * 1.609344, 2).' km';
    }elseif($unit == "M"){
        return round($miles * 1609.344, 2).' meters';
    }else{
        return round($miles, 2).' miles';
    }
}

Call the getdistance () function and pass two addresses between which you want to calculate the distance.

$addressFrom = 'Insert start address';
$addressTo   = 'Insert end address';

// Get distance in km
$distance = getDistance($addressFrom, $addressTo, "K");

Also, read our previous blog- How to Capture Screenshot of Website from URL using PHP

Tags: API and PHPGoogle Maps
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
How to Generate QR Code with PHP using Google Chart API
PHP and MySQL

How to Generate QR Code with PHP using Google Chart API

January 1, 2020
83
Next Post
Geolocation from IP Address using PHP

Geolocation from IP Address using PHP

Radius Based Location Search with PHP and MySQL

Radius Based Location Search with PHP and MySQL

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version