Get Latitude & Longitude from Google Geocoding API in PHP

By June 24, 2018API, Blog, Google, Maps, PHP
Allure Web Solutions Code Snippet
// Google Geocoding API Key
$apiKey  = 'API KEY GOES HERE';
$address = urlencode( '1600 Amphitheatre Pkwy, Mountain View, CA 94043' );
$url     = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}key={apiKey}";
$resp    = json_decode( file_get_contents( $url ), true );

// Latitude and Longitude (PHP 7 syntax)
$lat    = $resp['results'][0]['geometry']['location']['lat'] ?? '';
$long   = $resp['results'][0]['geometry']['location']['lng'] ?? '';

PHP Helper Class & Usage

We’ve created a helper class to quickly start using the Google Geocoding API. Instructions are very simple. Place the class file (you can copy it below from the gist) somewhere in your project. Update the path to the helper class, address, and API key in the code below.

// Include our class
require_once( dirname( __DIR__ ) . '/classes/class.googleGeocoding.php' );

// Google Geocoding API key
// Free from https://developers.google.com/maps/documentation/geocoding/start
$apiKey = 'API_KEY_GOES_HERE';

// Init object
$obj = new googleGeocoding( $apiKey );

// Get coordinates and print info
$address = '1600 Amphitheatre Pkwy, Mountain View, CA 94043';

print '<pre>';
print_r( $obj->getCoordinates( $address ) );
print '</pre>';

Gist

Mike Doubintchik

Author Mike Doubintchik

More posts by Mike Doubintchik

Leave a Reply