sloppycode.net
C# Google maps postcode parser
Does a Google maps lookup on all postcodes from a webpage, and plots them with Google maps.


Download example solution

This example/download was made to retrieve all UK postcodes from a webpage you give, and then plot them onto google maps. It was made to make up for the shortcomings of some sites that don't plot onto maps, or those that do but only individually. 

The version on this page uses the Recaptcha library to attempt to stop any abuse of the service. It does both UK and US codes, plus if you have a regex for your own country it can use that. The US zip code regex hasn't been rigidly tested so any improvements will be welcomed.

The code contains a small wrapper class to represent a single postcode and its longitude and latitude, and another class for downloading the webpage and grabbing all codes. I chose not to extend it beyond that although you could probably go a lot further with the KML parser. The longitude and latitude are stored as simple strings along with the response code.

Full information on the google maps API is found here . I had a problem that seems quite common with the KML node having a namespace, which I got around with the namespace manager and prefixing in the xpath (thanks to this example ). None of the nodes underneath the root use the namespace prefix which throws the parser into a fit.

Remember to change the google maps key to your own inside GoogleMapsGeoLookup.cs. The key is available for free at the google maps api site.

The snippet below shows the KML/Geocode lookup and XML parsing.

Example

Sites that rely on cookies aren't catered for in this example. The source has example code for it, however you will normally find it is easier to download the pages to disk and use them there than try to decypher cryptic cookies like those found on some Websphere ecommerce sites.

N.B. There is a problem with the Geo service and UK postcodes that means only the first 4 digits are used. This can mean that the latitude/longitude are out by streets, so double check with maps.google.com as this uses a different postcode lookup service than the Geo service. Royal Mail are the reason behind this - they charge for their postcode lookup service and obviously don't want google giving it away for free.

URL:  
Postcode/Zipcode type:



Example URLs:
Walmart - has a map already, this is just to demonstrate.
Boots - UK chemist
Homebase - UK DIY store
Custom - Enter NL for the country, and "([1-9]{4}\s+[A-Z]{2})" for the regex (without the quotes).

› Home
› C#
› Snippets
› Articles
› Tools
› Taglines
› ASP
› Dictionary Object
› FSO
› Unix cheat sheet
› Gaming
› CSS
› Yak
› Umbraco
› About
› Contact
› Privacy
› Projects
› Search