This post has been sitting for quite a while now, pending me having time to sit down and write some text to go alongside the code.
It would appear that I now have the time to write it up.
Back when
I was writing my Google Maps property finder I was using Google’s Geocoding API to get a set of co-ordinates based on a search string.
Specifically I was using the getLocations method of the GClientGeocoder object.
This would return a number of Placemark objects with a bunch of information about the potential matches.
They don’t really document this object, but to be honest they don’t really need to, below is an example Placemark expressed in JSON-ish notation.
{ "id": "p1", "address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA", "AddressDetails": { "Country": { "CountryNameCode": "US", "AdministrativeArea": { "AdministrativeAreaName": "CA", "SubAdministrativeArea": { "SubAdministrativeAreaName": "Santa Clara", "Locality": { "LocalityName": "Mountain View", "Thoroughfare": { "ThoroughfareName": "1600 Amphitheatre Pkwy"}, "PostalCode": { "PostalCodeNumber": "94043" } } } } }, "Accuracy": 8 }, "Point": { "coordinates": [-122.081783,37.423111,0] } }
The only thing is, if you want to get a specific element, the tree will not necessarily be the same each time, so traversal is a pain.
The code below will condense all this into the root level of an object, so you can pick out the key/value pairs you want, and easily tell if some aren’t there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var Placemark = new Class({ initialize: function(placemark){ this.traverse(placemark); }, traverse: function(item, key) { for (var key in item) { if (key == 'prototype') continue; if(typeof(item[key]) != 'object') this[key] = item[key]; else this.traverse(item[key]); } } }); |
One thing to note is that this was written for to use the Mootools class system, though it shouldn’t be very hard to remove this dependancy.
Categories: Programming
Tags: Google Maps, Hack, Javascript, Programming
Comments: 1 Comment.