Monday, April 1, 2013

Find the place name using latitude and longitude in PHP with google geocoder


We can find the place name using google geocoder by giving the Latitude and Longitude.

For example we want to get the place name of the latitude: '17.434545' and longitude: '82.124575' we need to pass this values to the google api to get the place details.

Following code explains how to work with that.

function getPlaceName($latitude, $longitude)
{
   //This below statement is used to send the data to google maps api and get the place
 name in different formats. we need to convert it as required. 
   $geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='
                                         .$latitude.','.$longitude.'&sensor=false');

   
   $output= json_decode($geocode);

   //Here "formatted_address" is used to display the address in a user friendly format.
   echo $output->results[0]->formatted_address;
}


We can use this function in PHP. when we execute the above method the following output will be displayed.

call the function as
<?php getPlaceName(17.434545, 82.124575); ?>

Output : Andhra Pradesh 533436, India

Thank you.

16 comments:

  1. Thanks it's working fine

    ReplyDelete
  2. Just to clarify some point, your code is returning location name NOT place name , and there are differences between them , do get place name you have to use place API or Library :
    https://developers.google.com/maps/documentation/javascript/examples/place-details

    ReplyDelete
  3. Just Awesome trick. It works fine.Thanx a lot..

    ReplyDelete
  4. what if just need city

    ReplyDelete
  5. Thanks Helping finding a solution for it

    ReplyDelete
  6. Thanks!!!!!!!!!!!!!!!!
    For sharing this code..i was tried its working and helpful for me.

    ReplyDelete
  7. Thanks very much for sharing this.

    ReplyDelete
  8. Thank you very much and great work. It's working nicely... :)

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Nice article, i am using this method in my webstie https://www.openacessjournal.com
    Thanks

    ReplyDelete