Friday, September 5, 2008

Google Maps Flash/Flex API

Been playing around with Google's flash API with a simple flex example. I am very impressed at just how simple it is to get something going. I started off with a simple panel and added a child map container -

<mx:UIComponent id="mapContainer" initialize="init(event);" resize="resizeMap(event)" width="100%" height="100%"/>

Then, in the init method, I created a new Map object and added it to the container just defined. Note that you have to get a key from Google's map API web site.

public function init(event:Event):void {
map = new Map();
map.key="your_gmap_key_goes_here";
map.addEventListener(MapEvent.MAP_READY, onMapReady);
mapContainer.addChild(map);
}

When the map has been rendered, the MAP_READY event handler registered above is called. This is the clever part. Google's geocoder allows you to enter an address or partial address, and it magically converts it into its best attempt at a latitude/longitude.

public function onMapReady(event:MapEvent):void {
geocoder = new ClientGeocoder();
geocoder.addEventListener(GeocodingEvent.GEOCODING_SUCCESS, onGeocodingSuccess);
geocoder.setBaseCountryCode("US");
geocoder.geocode("Los Angeles, CA");
}

Finally, tying it all together -

public function onGeocodingSuccess(event:GeocodingEvent):void
{
var placemarks:Array = event.response.placemarks;
if (placemarks.length > 0)
{
map.setCenter(placemarks[0].point);
var marker:Marker = new Marker(placemarks[0].point);
map.addOverlay(marker);
marker.openInfoWindow(new InfoWindowOptions({title: "Address", content: placemarks[0].address}));
map.setCenter(marker.getLatLng(),15,MapType.NORMAL_MAP_TYPE);
}
}


Yes, I know its a very simple contrived example, but I can't get over how quick and simple it was to get this all going. There is a geocoder web service so that any language can use it. Going to try this with another language and then maybe explore some more APIs.

1 comment:

Brad Wiederholt said...

Cool. Thanks for posting, Andrew.

I had a spare hour this morning, tried to embed this in an Adobe Air app, received the following error:
SecurityError: Error #3207: Application-sandbox content cannot access this feature.
at flash.system::Security$/allowDomain()

Did not google this too hard (found some 4 month old threads), but it looks like this API was only licensed to be used off of web sites? There is a workaround to fake it, but I need to read further about google's stance on embedding this on the desktop. As of May, they were discouraging it....

Anyway, followed your lead, have this working in a flex app. Now I have my very own Google Map API key as well....

Thanks for laying out this path for us... Brad