Simple php function to get coordinates from address through google services

Here I am showing you how to get coordinates from address using google api (Thanks to Google). The result will solely depends on how google support it in the future. Because google will set the 1st index result for the most relevant, thus this works quite well in general.

Function in php:


function getCoordinates($address){

$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern

$url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=$address";

$response = file_get_contents($url);

$json = json_decode($response,TRUE); //generate array object from the response from the web

return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);

}

How to call the function in php


echo getCoordinates('740 Story Rd San Jose CA 95122');

Result :Β 37.328865,-121.8581845

Advertisements

Posted on February 12, 2013, in Education and tagged , . Bookmark the permalink. 20 Comments.

  1. non sempre funziona, come mai?

  2. grazie!!! Thanks!!

  3. Fantastic! Thanks so much πŸ™‚

  4. It is working, it wasn’t finding anything in certain address. Thanks!

  5. Thanks, you saved a lot of my time, and it works just great.

  6. codestore82@hotmail.com

    AWESOME!

  7. Still works, and this is fantastic!

  8. Hi, do you know how to do the exact opposite (reverse geocoding). Ie – generate full address based on lat and long ? many thanks. Yvan

  9. Thanks! It works like a charm!

  10. can any one give me code how to get the current location when we have longitude and latitude?

  11. How to get coordinates of places? Example an hotel, restaurant etc..
    thanks, good snippet πŸ™‚

  12. You are the man my friend. Thanks a lot!

  13. Hi, thank you for the nice script. Is it possible to get current location (coordinates ) of a visitor on the mobile site if he accept to allow access for Google map?

    In other words, I just want to save coordinates into DB of a visitor on a specific page with google map.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: