The following example shows how you can embed a Google map into a Flex/ActionScript 3.0 project.
Full code after the jump.
Before getting started, you need to first get an API key from Google and then download the mapping component and put it in your /libs/ folder in your Flex Builder 3 project:
- Click here to get Google Maps API key.
- Click here to download the Google Maps ActionScript 3.0 component.
- Copy the map_flex_1_5.swc file from the .ZIP file’s /lib/ directory and copy it into your Flex Project’s /libs/ directory.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/03/using-google-maps-in-a-flex-project/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init();">
<mx:Script>
<![CDATA[
import com.google.maps.LatLng;
import com.google.maps.Map;
import com.google.maps.MapEvent;
import com.google.maps.controls.MapTypeControl;
import com.google.maps.controls.PositionControl;
import com.google.maps.controls.ZoomControl;
import com.google.maps.services.ClientGeocoder;
import com.google.maps.services.GeocodingEvent;
import com.google.maps.services.GeocodingResponse;
import com.google.maps.services.Placemark;
import mx.controls.Alert;
import mx.events.ResizeEvent;
private var googleMap:Map;
private var geocoder:ClientGeocoder;
private function init():void {
googleMap = new Map();
googleMap.key = APP_ID;
googleMap.addEventListener(MapEvent.MAP_READY, googleMap_mapReady);
googleMap.setSize(new Point(mapContainer.width, mapContainer.height));
googleMap.addControl(new ZoomControl());
googleMap.addControl(new MapTypeControl());
mapContainer.addChild(googleMap);
}
private function geocoder_geocodingSuccess(evt:GeocodingEvent):void {
var result:Placemark = GeocodingResponse(evt.response).placemarks[0];
googleMap.setCenter(result.point, 13);
}
private function geocoder_geocodingFailure(evt:GeocodingEvent):void {
Alert.show("Unable to geocode address: " + evt.name);
}
private function googleMap_mapReady(evt:MapEvent):void {
geocoder = new ClientGeocoder();
geocoder.addEventListener(GeocodingEvent.GEOCODING_SUCCESS, geocoder_geocodingSuccess);
geocoder.addEventListener(GeocodingEvent.GEOCODING_FAILURE, geocoder_geocodingFailure);
geocoder.geocode(textInput.text);
}
private function button_click(evt:MouseEvent):void {
geocoder.geocode(textInput.text);
}
private function mapContainer_resize(evt:ResizeEvent):void {
if (googleMap) {
googleMap.setSize(new Point(mapContainer.width, mapContainer.height));
}
}
]]>
</mx:Script>
<mx:String id="APP_ID" source="appid.txt" />
<mx:ApplicationControlBar dock="true">
<mx:Form styleName="plain">
<mx:FormItem label="Address:"
direction="horizontal">
<mx:TextInput id="textInput"
text="601 Townsend St, San Francisco, CA 94103" />
<mx:Button id="button"
label="Submit"
click="button_click(event);" />
</mx:FormItem>
</mx:Form>
</mx:ApplicationControlBar>
<mx:UIComponent id="mapContainer"
width="100%"
height="100%"
resize="mapContainer_resize(event);" />
</mx:Application>
View source is enabled in the following example.
For more information and examples, see the “Google Maps API for Flash homepage”.

{ 46 comments… read them below or add one }
Nice example !
You can see another example of an app using Google Maps here :
http://beta.navx.com/en/
very cool!!!
Why google Map Status is Debug?
Thanks for the example, Peter.
@Owen – you’re getting the debug message because you’re running the flex app on localhost. If you upload your resulting swf to be served from beneath the domain you gave when you registered for an API key, you’ll find that the debug message is gone (and GeoCoding works)
I would love a tutorial on how they did this:
http://beta.navx.com/en/
Sean B. Halliday
Hi! This is a shameless plug. I’m also building a series of tutorials utilizing GoogleMaps in Flex.
http://danao.org/2008/05/28/google-maps-flex-basic/
http://danao.org/2008/08/06/google-maps-flex-with-overlays/
Cheers! :)
Jon
i don’t get one thing with the appid.txt are there any quotes or anything u have to put around key?
cyberoverdose,
No, you just need to sign up for your own API key and then paste it into that file (without quotes).
Peter
I keep getting a 1046 error for all the events (Geocoding Event and Map Event). The error is specifically for the event functions geocoder_geocodingSuccess, geocoder_geocodingFailure, googleMap_mapReady. Not sure what the problem may be?
oh, ok I got it to work. I thought you needed to create a libs folder within assets. However, I just realized you could use the libs folder that automatically is built by Flex Builder 3. Thanks for the example. This site is made of delicious awesomeness!
wat did i do,run my googlemap in localhost,that means i got o/p in debugmode,how it go out
ramya,
To get rid of the debugmode, I believe you need to upload the SWF file to a webserver.
Peter
Thank u Mr.Peterd,but tell me the process,wat m doing?,i ve no idea abt that
And how to give the all lat&lang dynamically for particular city in one country(eg:France,in this lot of cities r present,when i clicked particular city on combobox like ‘NICE’,it shows ‘NICE’ city on France map),
i got one idea,in XML gives all lat&lang&call it by using or ,is it correct r not?
create XML,
call it by using websevice or httpservice
Hi.
this site is awesome, thank you! :)
I’ve tried the map demo. On localhost, it showed the debug mode, which is to be expected.
When I uploaded it to the server, the container is visible, but displays this message:
Initialization failed: please check the API key,
swf location, version and network availability.
Any ideas?
Many thanks,
Matt
Matt,
And you pasted your Google Maps API key in appid.txt?
Peter
Hi Peter.
Thank you for your reply.
Yes, the API key is included in the appid.txt file.
Matt,
I haven’t seen that error before (but I’ve only tried a few simple things with Google Maps).
Does this help? http://groups.google.co.ke/group/Google-Maps-API/browse_thread/thread/afb8173049b08cee?fwc=1
Peter
Cool, like the map blinds when I resize it, I add a lazy resize:
private var _lazy_resize_timer:uint = 0; private function mapContainer_resize(evt:ResizeEvent):void { if (googleMap) { clearTimeout(this._lazy_resize_timer); this._lazy_resize_timer = setTimeout(_do_lazy_resize,50); } } private function _do_lazy_resize():void { googleMap.setSize(new Point(mapContainer.width, mapContainer.height)); }hi everyone!
have you ever encountered this error code:
“1026: Constructor functions must be instance methods.”
this applies to this line of code -> private var googleMap:Map;
i guess these codes only works for map_flex_1_5.swc ? hope someone cud send me a link to where to find this version, i would really appreciate it.
otherwise, hope someone could help me to make this work with map_flex_1_6.swc..
moymoy
If I want to decode a set of address stored in an array
how can I pass the array index in the geocode_success function?
for …
geocoder.geocode(address.text)
end
Catch 22
When I go to run the example, I get six different errors (all 1046) for the Geocodingevent and the Mapevent.
I understand that if I move the SWF file to my web server this will go away.
The Flex Builder will not finish compiling the SWF file with the errors – so I can move a “good’ file to my hosted server.
What is the trick to getting this to work?
Kirk,
And you imported the GeocodingEvent and MapEvent classes in your application?
I don’t recall having any coding errors in Flex Builder when I published this, but I can try taking another look when I get home tonight.
Peter
I downloaded the latest swc file which is map_flex_1_7a.swc. Perhaps you could try using the this file – I am curious if I need to try to get the map_flex_1_5.swc version.
How to implement call out in google maps??
appid.txt is missing where do I get this file from ?
You don’t get that file. It was just a plain-text file with my Google API application ID (which I didn’t include in the source ZIP).
Peter
Thanks for your info but if I may ask one more thing. I would like to add a from feild that would give directions to my default location. Any help would be great. Heres my link below.
http://kbodesign.com/ostendo/bin-release/ostendo.html
And possibly a marker of the location. Been looking at the coding on the google site and since I’m new at this it’s all chinese for the moment anyway. thanks
The Google map Flex API is cool . Thought it worth mentioning the Modest Maps Flex library. It pulls tiles from Google but allows you to develop a rich application without being tied solely to the google api. I have an example of a ski map mash up at:
http://www.flexmappers.com/arkade
which shows some of the possibilities.
Great example Matt.
hi, is there a way to use google adds in flex?
plz tell me how to unload gmap
Thank you for posting all of your information and tutorials online. What a wealth of information and knowledge you have going on here. I checked out your site and tutorials for like 5 hours tonight.
Love the google maps app for flex 3.
Was wondering if you had a version that included dynamic marker points using longitude and latitude coordinates from a text file?
I am trying to follow your example from youtube of how to do this with yahoo maps BUT I can’t seem to find the source code/files that you said would be here. I found a more generic google map display – one from August 2008 – but it does not use markers. I like google maps more than yahoo. Do you happen to have a flex 3 file that uses google maps with markers (pulling data from a dynamic file using longitude and latitude degrees) in the same way as in your yahoo maps example? Can you help?
Mark
(if you could respond to email as well – that would be great)
Hi.
I used your example on a pop-up window to show the map, and it worked just fine. BUT, when I close the window and open it again, the map doesn’t load and there are no error messages, just an empty blue screen (wich is the component’s default color).
Is there anything else I should code to make it work when re-opening the map pop-up?
PS: I am using it on localhost
Hey there,
I got the same issue… Did you find a fix for it please?
Tnkx,
Othman
plse help,
ok I did everything above,
When I try the swf locally and click the button I get:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at myfolder/button_click()
at myfolder/__button_click()
When I try the swf after uploading to the webserver, I see the google white box, the address i put in and the button, plus a blank screen below (where the map should be). Pushing the button does nothing. Should this map_flex_1_5.swc file also be on the webserver?
How do i get the map to work? plse help!!!
ps. I had to change the location of this:
totally upward right below mx.application because during debugging it would give me error.
noob needs help :(
location of this: mx:String id=”APP_ID” source=”appid.txt”
I found the solution and for noobs like me I have some tips:
1. Make sure the google file swc is attached to the project via:
Project/properties/flex build path/library path/add swc
2. put the appid.txt (including your own google key) file on the webserver in folder src
3. put the google file swc on the webserver in the folder libs
this made it work for me. Thanks for this great code, you are the best!
cheers Don
Has anyone had a problem with a viewStack and the google map API? My view stack has 3 views, the transitions work fine until the view with the google map in it loads, then im stuck on that view, my only way to solve this problem was to call the unload function to unload the google map then the transitions worked fine. I dont like doing that since whenever they go back to that view the map has to reload all over again. Anyone seen this problem and have a better solution. I tried making the map object not visible that did nto fix the problem either.
Hello,
I had exactly the same problem … here are my results:
It seems that there is some information left in the cache after the initial loading so whenever you load google maps a second time into the same holder it will come to a crash.
What I did was to set a rootvariable with the initial loadingprocess to true. This helps to avoid to fire three critical commands a second time:
googleMap.addControl
googleMap.addControl
googleMap.setSize
Because setSize crashes too I resize the holder arround the Map (eg. Canvas or Box).
This workaround works fine for me now – yep!
Regards
Oliver
btw: Thanks a lot for this great blog!!!!
####################################
Yes,
I am using Flex 3 Builder… I pasted my key to the appId.txt and uploaded my the main.swf to my server. I get an “Init failed error. Please check swf location. “It runs locally in Flex builder (debug mode). When I applied for the key it said it would work on all sub domain????? I want to include google maps with others api’s (ie papervisions,youtube..etc)..So can you compile the google maps swf and then load it????
My root domain is
http://www.ihearyah.com
and the sub domain is
http://www.besttennis.org
Help!
Sincerely,
Henry Mustafa
Great example Peter!
Guys, I have an issue and I would appreciate it if somebody could help me.
As advised, I got an API Key, I downloaded the API, I copied the example source and everything worked nicely both locally and from a designated domain. Next morning, when I resumed working, however, the map would load but the geocoding would return the error:
“Unable to geocode address: …”
I get this effect again locally and from the respective domain. I also noticed that the example in this page returns absolutely the same error message, although it was working nicely yesterday.
Does anyone know what causes the issue?
Thanks!
Naso.
Hey guys, I keep getting an error when init geocoder. I am trying to create a .as file and in that I have to following code
…
private var geocoder:ClientGeocoder;
..
..
public function setMap():void{
geocoder = new ClientGeocoder();
gc.addEventListener(GeocodingEvent.GEOCODING_SUCCESS, geocoder_geocodingSuccess);
gc.addEventListener(GeocodingEvent.GEOCODING_FAILURE, geocoder_geocodingFailure);
gc.reverseGeocode(new LatLng(lat,lon));
}
..
..
but I keep getting an error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
when i say geocoder = new ClientGeocoder();
Any Ideas?? I have even tried
geocoder = new ClientGeocoder(new ClientGeocoderOptions(…..));
but the result is the same. I am using map_flex_1_17.swc.
Thank you
Jaysheel