Get Latitude and Longitude from Address using Google Maps API and PHP


For Pointing the exact location on Google Map it will always be a good idea to pass the latitude and longitude with Google Maps API. In this article, you’ll know how to get latitude and longitude from address using Google Maps API in PHP. Here we’ll combine all code into a PHP function and you only need to use this function to find latitude and longitude from an address.

getLatLong() function accept one parameter ($address), into the $address you need to provide the full address from where you want to get latitude and longitude. This function returns the latitude and longitude of address as an array if found, otherwise, return FALSE.

getLatLong() function is given below:

* Author: CodexWorld
* Author URI:
* Function Name: getLatLong()
* $address => Full address.
* Return => Latitude and longitude of the given address.
function getLatLong($address){
//Formatted address
$formattedAddr str_replace(' ','+',$address);
//Send request and receive json data by address
$geocodeFromAddr file_get_contents(''.$formattedAddr.'&sensor=false'); 
$output json_decode($geocodeFromAddr);
//Get latitude and longitute from json data
$data['latitude']  = $output->results[0]->geometry->location->lat
$data['longitude'] = $output->results[0]->geometry->location->lng;
//Return latitude and longitude of the given address


Use getLatLong() function like the following.

$address 'White House, Pennsylvania Avenue Northwest, Washington, DC, United States';
$latLong getLatLong($address);
$latitude $latLong['latitude']?$latLong['latitude']:'Not found';
$longitude $latLong['longitude']?$latLong['longitude']:'Not found';

To specify a Google API key in your request, include it as the value of a key parameter.

$geocodeFromAddr file_get_contents(''.$formattedAddr.'&sensor=true_or_false&key=GoogleAPIKey');

Leave a reply

CodexWorld Newsletter

Subscribe CodexWorld updates via email and get every new post delivered to your inbox.