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


get-address-from-latitude-longitude-using-google-maps-api-php-by-codexworld

In this article, you’ll know how to get address from latitude and longitude using Google Maps API in PHP. Here we’ll provide a simple PHP script to get location from latitude and longitude. The whole script combines into a PHP function and you only need to use this function to find address from latitude and longitude.

getAddress() function accept two parameters ($latitude,$longitude), you need to provide the latitude and longitude from where you want to get the address. This function returns the address of based on given latitude and longitude if found, otherwise, return FALSE.

getAddress() function is given below:

/**
* Author: CodexWorld
* Author URI: http://www.codexworld.com
* Function Name: getAddress()
* $latitude => Latitude.
* $longitude => Longitude.
* Return =>  Address of the given Latitude and longitude.
**/
function getAddress($latitude,$longitude){
    if(!empty(
$latitude) && !empty($longitude)){
        
//Send request and receive json data by address
        
$geocodeFromLatLong file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($latitude).','.trim($longitude).'&sensor=false'); 
        
$output json_decode($geocodeFromLatLong);
        
$status $output->status;
        
//Get address from json data
        
$address = ($status=="OK")?$output->results[1]->formatted_address:'';
        
//Return address of the given latitude and longitude
        
if(!empty($address)){
            return 
$address;
        }else{
            return 
false;
        }
    }else{
        return 
false;   
    }
}

Uses:

Use getAddress() function like the following.

$latitude '38.897952';
$longitude '-77.036562';
$address getAddress($latitude,$longitude);
$address $address?$address:'Not found';

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

$geocodeFromLatLong file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($latitude).','.trim($longitude).'&sensor=true_or_false&key=GoogleAPIKey');

Conclusion

Hope this simple script would be very useful for getting the address from latitude and longitude. If you want to use the Google Maps Geocode API for getting the other information, see some other useful scripts from the below tutorial links.

1 Comment

  1. Naqqash Rana Said...

Leave a reply

Connect With CodexWorld