Quantcast
Channel: atomiku » Web Development
Viewing all articles
Browse latest Browse all 10

Easiest way to get Lat/Long GPS coordinates from Google Maps API with PHP

$
0
0

So I built a properties rental website and they wanted to show a marker on a google map for where the property was. Well before I could start plotting markers I needed to get the coordinates from the supplied address. Easy! Below is a handy function with simple usage. You’ll need to go and sign up for a free API key from: https://developers.google.com/maps/documentation/javascript/tutorial#api_key.

1
2
3
4
5
6
7
8
9
10
11
12
function getCoordinates($address) {
    $apiKey = 'YOUR_KEY_HERE';
    $address = urlencode($address);
    $url = 'http://maps.google.com/maps/geo?q=' . $address . '&output=csv&key=' . $apiKey;
    $data = getURL($url);
    if ($data){
        $data = explode(',', $data);
        return array($data[2], $data[3], $data[1], $data[0]);
    }
    //return default data
    return array(0, 0, 0, 0);
}

Now, just a quick bit of information on how to use this function. You can supply almost any type of address, postcode or country that you would normally be able to do on maps.google.com. For instance: getCoordinates(’140 Shaftesbury Avenue, London, Greater London WC2H 8HD’);

The getCoordinates function returns an array. 0 = lat, 1 = lng, 2 = accuracy and 3 = status. The easiest way to deal with the return array would be to use list, though.

list($lat, $lng, $accuracy, $status) = getCoordinates('Address');

I advise you use some error checking in your system, based on $status. Here are the available status codes that Google may return:

200 – Success
500 – Server Error
602 – Unknown Address
610 – Bad API key
620 – Too many queries

You are limited to around 25,000 API queries a day – that should be more than enough. (You can see your API usage in the Google API console.)

Credits to havlena.net for the original idea and code.

The post Easiest way to get Lat/Long GPS coordinates from Google Maps API with PHP appeared first on atomiku.


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images