and like us on FB

This article won’t mean much to you unless you you have a specific problem to solve. I was working on a project that required mapping with Google’s Geocoding API, and I had to extract the City, State and Country (most notably the state) from an address… and I encountered numerous issues with relation to how the json data was returned. After playing around, this function seems to serve my purpose. Initially published on Internoetics, it was one of the site’s most downloaded snippets of PHP code.

From Google Maps, Geocoding is the process of converting an addresses into geographic [latitude and longitude] coordinates, which you can use to place markers or position the map. The Google Geocoding API provides a direct way to access a geocoder via an HTTP request. Additionally, the service allows you to perform the converse operation (turning coordinates into addresses); this process is known as “reverse geocoding.”

A Geocoding API request must be in the following format: http://maps.googleapis.com/maps/api/geocode/output?parameters (where output may be either json or XML). Full details of the mapping functionality is available on Google’s Geocoding website .

In my case, obtaining the state (defined by administrative_area_level_1 in the json data) was problematic because it wasn’t a consistent element within the object array. The solution was to decode the json data and iterate over the resulting array (using in_array() to check the value).

The PHP Code

Returns: Australia, New South Wales, Sydney

Considerations

  • Since Google introduced a requirement to have an API key for many of their products, this code may not work unless you whitelist your server IP address.
  • If you’re looking to reverse geocode multiple addresses, it’d be best to avoid Google’s services for such activity. There are plenty of applications that’ll do this for you.

Download

Title: Get Country, State & City from Google's Geocoding API
Description: Get Country, State & City from Google's Geocoding API.
Download: PHP Code (V0.2) | Plugin Page

Shortt URL for this post: http://shor.tt/1PkA