Using Google Maps in a Flex project

by Peter deHaan on August 3, 2008

in Google, Google Maps, Mapping

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:

View MXML

<?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 }

1 jarodinou August 4, 2008 at 1:21 am

Nice example !
You can see another example of an app using Google Maps here :
http://beta.navx.com/en/

Reply

2 fox August 4, 2008 at 1:33 am

very cool!!!

Reply

3 Owen August 4, 2008 at 2:25 am

Why google Map Status is Debug?

Reply

4 Steve August 4, 2008 at 11:38 am

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)

Reply

5 Sean Halliday August 6, 2008 at 7:46 am

I would love a tutorial on how they did this:

http://beta.navx.com/en/

Sean B. Halliday

Reply

6 Jon Danao August 7, 2008 at 12:02 am

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

Reply

7 cyberoverdose August 13, 2008 at 9:31 am

i don’t get one thing with the appid.txt are there any quotes or anything u have to put around key?

Reply

8 peterd August 13, 2008 at 10:02 am

cyberoverdose,

No, you just need to sign up for your own API key and then paste it into that file (without quotes).

Peter

Reply

9 d3zign7reak August 14, 2008 at 12:23 pm

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?

Reply

10 d3zign7reak August 14, 2008 at 1:02 pm

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!

Reply

11 ramya August 22, 2008 at 11:08 pm

wat did i do,run my googlemap in localhost,that means i got o/p in debugmode,how it go out

Reply

12 peterd August 23, 2008 at 2:37 am

ramya,

To get rid of the debugmode, I believe you need to upload the SWF file to a webserver.

Peter

Reply

13 ramya August 26, 2008 at 2:47 am

Thank u Mr.Peterd,but tell me the process,wat m doing?,i ve no idea abt that

Reply

14 ramya August 26, 2008 at 2:57 am

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),

Reply

15 ramya August 26, 2008 at 3:03 am

i got one idea,in XML gives all lat&lang&call it by using or ,is it correct r not?

Reply

16 ramya August 26, 2008 at 5:22 am

create XML,
call it by using websevice or httpservice

Reply

17 Matt September 1, 2008 at 9:21 am

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

Reply

18 peterd September 1, 2008 at 10:46 pm

Matt,

And you pasted your Google Maps API key in appid.txt?

Peter

Reply

19 Matt September 2, 2008 at 2:06 am

Hi Peter.

Thank you for your reply.

Yes, the API key is included in the appid.txt file.

Reply

20 peterd September 2, 2008 at 8:13 am

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

Reply

21 Tom September 5, 2008 at 3:44 am

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));
}

Reply

22 moymoy September 9, 2008 at 7:46 pm

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

Reply

23 Mike October 1, 2008 at 4:37 am

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

Reply

24 Kirk October 7, 2008 at 6:23 am

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?

Reply

25 peterd October 7, 2008 at 7:33 am

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

Reply

26 Kirk October 7, 2008 at 9:35 am

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.

Reply

27 Arthi December 1, 2008 at 1:57 am

How to implement call out in google maps??

Reply

28 Ken December 4, 2008 at 3:17 pm

appid.txt is missing where do I get this file from ?

Reply

29 Peter deHaan December 4, 2008 at 3:50 pm

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

Reply

30 Ken O December 7, 2008 at 3:39 pm

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

Reply

31 Ken O December 7, 2008 at 3:43 pm

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

Reply

32 matt sheehan December 23, 2008 at 6:19 am

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.

Reply

33 Shawn Yale July 8, 2009 at 2:52 pm

Great example Matt.

Reply

34 Daniel January 16, 2009 at 6:09 pm

hi, is there a way to use google adds in flex?

Reply

35 Anonymous January 22, 2009 at 5:46 am

plz tell me how to unload gmap

Reply

36 Mark March 30, 2009 at 8:43 pm

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)

Reply

37 Nicholas June 2, 2009 at 10:12 pm

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

Reply

38 Othman September 9, 2009 at 5:01 pm

Hey there,

I got the same issue… Did you find a fix for it please?

Tnkx,

Othman

Reply

39 Don June 27, 2009 at 4:20 pm

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 :(

Reply

40 Don June 27, 2009 at 4:22 pm

location of this: mx:String id=”APP_ID” source=”appid.txt”

Reply

41 Don June 28, 2009 at 3:29 am

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

Reply

42 Ben September 24, 2009 at 4:24 pm

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.

Reply

43 oliver merx October 6, 2009 at 1:03 pm

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!!!!

####################################

private function init():void{
 
    googleMap = new Map();
    googleMap.key = "xyz"
 
    googleMap.addEventListener( MapMoveEvent.MOVE_END, moveEnd );
    googleMap.addEventListener( MapZoomEvent.ZOOM_END, zoomEnd );
    googleMap.addEventListener( MapEvent.MAPTYPE_CHANGED, mapTypes );
    if( !parentApplication.googleMapReady ){
        googleMap.addControl( new ZoomControl() );// causes Error on reload!
        googleMap.addControl( new MapTypeControl() );// causes Error on reload!
    }
    else{
        parentApplication.googleMapRead = true;
    }
    googleMap.addEventListener( MapEvent.MAP_READY, googleMap_mapReady );
    if( !parentApplication.googleMapReady ){
        googleMap.setSize( new Point( mapContainer.width, mapContainer.height) );// causes Error on reload
    }
    else{
        this.width += 0.001;
        this.height += 0.001;
        this.validateNow();
    }
 
    mapContainer.addChild( googleMap );
}

Reply

44 Henry Mustafa October 12, 2009 at 3:22 pm

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

Reply

45 Naso October 14, 2009 at 6:00 pm

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.

Reply

46 Jay November 13, 2009 at 3:48 pm

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

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: