Using the Google Maps API with AS3

When I start using a new API in an application I generally start by making an abstraction layer to simplify my calls and so I can swap out the API at a later date if needed.  Tonight when I started working with the Google Maps API I wasn’t sure if I was going to need an abstraction layer, but after creating a few maps I realized I was constantly copying and pasting the same code over and over. I went ahead and wrote a quick wrapper that handled all of my initial needs. As I progress this layer will be extended and updated, but a good foundation is a requirement up front.

With the application I’m currently developing most of the maps needed to be 700×400 so I made that the default while still allowing custom sizing.  One requirement I had was to lock the user to a very specific point on the map so I begin with all dragging, zooming, and clicking disabled.  For a bit of style I tossed on a DropShadowFilter and a black border so it didn’t look so flat and in no time I had a working wrapper that produced nice looking, locked Google Maps.

	/**
	 * Google Maps API Abstraction Layer
	 *
	 * @author StupIdiocy.com
	 */
	public class GoogleMap extends Sprite
	{
		private var _Map:Map;

		private var _Location:LatLng;
		private var _Zoom:Number;

		public function GoogleMap(lat:Number, lng:Number, zoom:Number, width:Number = 700, height:Number = 400)
		{
			trace("GoogleMap:tStarting map API.");

			// Set the internal vars
			_Location = new LatLng(lat, lng);
			_Zoom = zoom;

			// Create and add the map
			_Map = new Map();
			_Map.filters = [new DropShadowFilter()];
			_Map.setSize(new Point(width, height));
			_Map.key = "GOOGLE MAPS API KEY";
			_Map.addEventListener(MapEvent.MAP_READY, onMapReady);

			addChild(_Map);

			// Add a black border
			graphics.lineStyle(2, 0x000000);
			graphics.drawRect(0, 0, width, height);
		}

		private function onMapReady(event:Event):void
		{
			// Lock the map in every way possible
			_Map.disableDragging();
			_Map.disableScrollWheelZoom();
			_Map.disableControlByKeyboard();
			_Map.disableContinuousZoom();
			_Map.disableCrosshairs();
			_Map.mouseEnabled = false;
			_Map.mouseChildren = false;
			_Map.doubleClickEnabled = false;

			// Set the map location, zoom level, and type
			trace("onMapReady:tSetting location.");

			_Map.setCenter(_Location, _Zoom, MapType.SATELLITE_MAP_TYPE);
		}
	}

As you can see the Google Maps API is very easy to use and a wrapper such as this is probably overkill if you will only be displaying one map. However if you find yourself copy and pasting the same thing again and again, it’s probably safe to assume you should develop an abstraction object for that task. The longer you wait to abstract your repetitive tasks the harder it gets to build a useful abstraction layer and remove all of the ties through the application.

Posted in Development and tagged , .