Monthly Archives: September 2012

Find a city in wunderground when there is more than one entry

Wunderground’s API website seem to cover every single possible thing you might want to do with their service, apart from, inexplicably, actually having a list of cities and corresponding codes for you to look at in order to get the weather as accurately as possible for outlying regions (in other words, to work out what the nearest city to the place you want is that they have data on).

What you have to do is go to their main website and search for your country, it’ll give you a list of names of cities. You can use these and just add %20 instead of spaces, etc, and shove it into the code example they give you, such as :

$json_string = file_get_contents("http://api.wunderground.com/api/417de1380f19b8bc/geolookup/forecast/q/ZA/Cape%20Town.json");
$parsed_json = json_decode($json_string);

But you’ll run into problems when there is more than one entry for the city you’re searching for, for example Pietermaritzberg or Nelspruit in South Africa both (oddly) have two entries – seeĀ http://www.wunderground.com/global/ZA.html?MR=1.

As far as I can see there’s nothing mentioned on their API documentation about this. It’d be fine if the json you got given back contained forecasts for both of the locations, but sadly it doesn’t. So what you have to do is cunningly look at the main website’s code, check various links to see if you can work out a possible way to query stuff, google fruitlessly, try random combinations and then (!!) take the zmw code for the city you want out of the array of responses you get, and use it like this:

$json_string = file_get_contents("http://api.wunderground.com/api/417de1380f19b8bc/geolookup/forecast/q/zmw:00000.1.68289.json");
 $parsed_json = json_decode($json_string);

In general their new website, service and api website seem very nice and organised so it’s entirely possible this information is somewhere and I was just blindly not seeing it, but I did look quite a bit and sometimes the most simple obvious things just get overlooked.