Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active November 15, 2022 15:34
Show Gist options
  • Save morgyface/d37e755daac1094a612fc5c7b82e1bed to your computer and use it in GitHub Desktop.
Save morgyface/d37e755daac1094a612fc5c7b82e1bed to your computer and use it in GitHub Desktop.
A PHP function that uses Google Maps Geocode API to return coordinates from a postal address
<?php
function geolocation( $address ) {
$coordinates = null;
if( $address ) {
$address = rawurlencode( $address ); // Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits.
$key = 'YOUR_API_KEY'; // The Geolocation API Key
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&key=' . $key;
$data = file_get_contents( $url ); // Get the JSON file.
if ( $data ) {
$json = json_decode( $data, true ); // Turns the JSON into an array
if( is_array( $json ) ) {
$status = $json['status'];
if ( $status == 'OK' ) {
$lat = $json['results'][0]['geometry']['location']['lat'];
$lng = $json['results'][0]['geometry']['location']['lng'];
$coordinates['lat'] = $lat;
$coordinates['lng'] = $lng;
}
}
}
return $coordinates;
}
}
@morgyface
Copy link
Author

Getting latitude and longitude from a postal address

I used this as part of a project to obtain the coordinates of retailers addresses. It worked well though I noticed that at around 900 consecutive requests the API would time out for me. Could be isolated but worth mentioning.

Another thing worth mentioning is the status check, I got a few errors whereby the API would return but it wouldn't contain lat/lng due to the address being incomplete or incorrect, so to ensure the coordinates are there I check the status first.

I used this within WordPress by placing this in functions.php and I used it like this:

$coordinates = geolocation( $address );
if( $coordinates ) {
    $lat = $coordinates['lat'];
    $lng = $coordinates['lng'];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment