How embed Google Maps in Flex?


Google create a special API for Flash platform to make possible use them. I will show how write a simple application to find a place or route. At first we need a special key from Google for use the map (http://code.google.com/intl/pl/apis/maps/signup.html ). When we have the key we can start.

  1. add xmlns:maps=”com.google.maps.*” to Application tag
  2. import appropriate classes
  3. add map instance
  4. <maps:Map id="myMap" width="100%" height="100%"  key="[key from the google site]" mapevent_mapready="onMapReady(event)" url="[url to our site]"/>
  5. add functions
private function onMapReady(event:MapEvent):void {
	myMap.addControl(new MapTypeControl());							//add type of map control
	myMap.addControl(new ZoomControl());							//add zoom control
	myMap.enableScrollWheelZoom();								//enable mouse scrolling
	geocoder=new ClientGeocoder();								//create geocoder
	geocoder.addEventListener(GeocodingEvent.GEOCODING_SUCCESS, handleGeocodingSuccess);	//add listeners for geocoder
	geocoder.addEventListener(GeocodingEvent.GEOCODING_FAILURE, handleGeocodingFailure);
	dirs=new Directions();									//create directions
	dirs.addEventListener(DirectionsEvent.DIRECTIONS_SUCCESS, handleDirLoad);		//add listeners for directions
	dirs.addEventListener(DirectionsEvent.DIRECTIONS_FAILURE, handleDirFail);

}

private function handleDirLoad(evt:DirectionsEvent):void{
	var dirs:Directions=evt.directions; 							//create directions from event
	var startM:Marker;
	var endM:Marker;
	startM = new Marker(dirs.getRoute(0).startGeocode.point, new MarkerOptions());		//create start marker from directions instance
	endM = new Marker(dirs.getRoute(0).endGeocode.point, new MarkerOptions());		//create end marker from directions instance
	myMap.clearOverlays();									//clear map
	myMap.addOverlay(dirs.createPolyline());						//draw route on map
	myMap.addOverlay(startM);								//add start marker
	myMap.addOverlay(endM);									//add end marker
	myMap.setZoom(myMap.getBoundsZoomLevel(dirs.bounds));					//set appropriate zoom
	myMap.setCenter(dirs.bounds.getCenter());						//show route
}

private function handleDirFail(evt:DirectionsEvent):void{					//directions failure handler
	Alert.show("Unable to found route");
}

private function handleGeocodingSuccess(evt:GeocodingEvent):void{				//geocoding success handler
	var result:Placemark = GeocodingResponse(evt.response).placemarks[0];			//create result object
	myMap.setCenter(result.point, 14);							//show finding place
}

private function handleGeocodingFailure(evt:GeocodingEvent):void{				//geocoding failure handler
	Alert.show("Unable to found: " + evt.name);
}

This is one out of many things we can do with GoogleMaps API, including e.g. adding information and photos in concrete places on the map.

(will not be published)