03
Aug
08

Using Google Maps in a Flex project

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”.


39 Responses to “Using Google Maps in a Flex project”


  1. 1 jarodinou Aug 4th, 2008 at 1:21 am

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

  2. 2 fox Aug 4th, 2008 at 1:33 am

    very cool!!!

  3. 3 Owen Aug 4th, 2008 at 2:25 am

    Why google Map Status is Debug?

  4. 4 Steve Aug 4th, 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)

  5. 5 Sean Halliday Aug 6th, 2008 at 7:46 am

    I would love a tutorial on how they did this:

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

    Sean B. Halliday

  6. 6 Jon Danao Aug 7th, 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

  7. 7 cyberoverdose Aug 13th, 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?

  8. 8 peterd Aug 13th, 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

  9. 9 d3zign7reak Aug 14th, 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?

  10. 10 d3zign7reak Aug 14th, 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!

  11. 11 ramya Aug 22nd, 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

  12. 12 peterd Aug 23rd, 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

  13. 13 ramya Aug 26th, 2008 at 2:47 am

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

  14. 14 ramya Aug 26th, 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),

  15. 15 ramya Aug 26th, 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?

  16. 16 ramya Aug 26th, 2008 at 5:22 am

    create XML,
    call it by using websevice or httpservice

  17. 17 Matt Sep 1st, 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

  18. 18 peterd Sep 1st, 2008 at 10:46 pm

    Matt,

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

    Peter

  19. 19 Matt Sep 2nd, 2008 at 2:06 am

    Hi Peter.

    Thank you for your reply.

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

  20. 20 peterd Sep 2nd, 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

  21. 21 Tom Sep 5th, 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));
    }
    
  22. 22 moymoy Sep 9th, 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

  23. 23 Mike Oct 1st, 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

  24. 24 Kirk Oct 7th, 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?

  25. 25 peterd Oct 7th, 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

  26. 26 Kirk Oct 7th, 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.

  27. 27 Arthi Dec 1st, 2008 at 1:57 am

    How to implement call out in google maps??

  28. 28 Ken Dec 4th, 2008 at 3:17 pm

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

  29. 29 Peter deHaan Dec 4th, 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

  30. 30 Ken O Dec 7th, 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

  31. 31 Ken O Dec 7th, 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

  32. 32 matt sheehan Dec 23rd, 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.

  33. 33 Daniel Jan 16th, 2009 at 6:09 pm

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

  34. 34 Anonymous Jan 22nd, 2009 at 5:46 am

    plz tell me how to unload gmap

  35. 35 Mark Mar 30th, 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)

  36. 36 Nicholas Jun 2nd, 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

  37. 37 Don Jun 27th, 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 :(

  38. 38 Don Jun 27th, 2009 at 4:22 pm

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

  39. 39 Don Jun 28th, 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

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




Badge Farm

  • Powered by Redoable 1.2
  • Cornify
  • Feeds burnt by Feedburner
  • Feed