Stuff & Nonsense

Reverse Geocoding in PHP

A project I’m working on at the moment had a requirement for reverse geocoding (ie: taking a set of latitude / longitude co-ordinates and returning a placename) of some data coming from an iPhone application.

There’s plenty of information available for doing address to long/lat encoding using google maps and the like, but not much on going the other way.

Luckily, I found the GeoNames database, a freely accessible geographical database which offers an easy to use api.

The specific bit I’m interested in is accessed by calling this url (with your lat/long co-ordinates of course!)

http://ws.geonames.org/findNearbyPlaceNameJSON?lat=53.4978&lng=-2.5013

This returns some JSON encoded data as follows:

{"geonames":
      [{
         "countryName":"United Kingdom",
         "adminCode1":"ENG",
         "fclName":"city,village,...",
         "countryCode":"GB",
         "lng":-2.5166667,
         "fcodeName":"populated place",
         "distance":"1.90284",
         "toponymName":"Leigh",
         "fcl":"P",
         "name":"Leigh",
         "fcode":"PPL",
         "geonameId":2644660,
         "lat":53.4833333,
         "adminName1":"England",
         "population":43626}
      ]}

There’s a lot of info there, but the specific bits I was interested in are the placename and the country.

Here’s the code:

      $url = "http://ws.geonames.org/findNearbyPlaceNameJSON?lat=$lat&lng=$long";
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
      curl_setopt($ch, CURLOPT_PROXY, 'myproxy:800');
      $json = curl_exec($ch);
      curl_close($ch);      
      $data = json_decode($json, true);
      foreach ($data["geonames"] as $key => $val) {
        $placename = $val["name"];
        $countryname = $val['countryName'];
        $countrycode = $val["countryCode"];
      }

As you can see, I’m sat behind a proxy so I have to use curl to get the page. If you’re not, you can replace all the curl stuff with a simple file_get_contents($url) (depending on your PHP config of course).

Also of note, if you live in the US you can get the nearest address instead of the nearest placename using a different GeoName api call. There’s a list of API calls available here

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.