Advertisement
  1. Code
  2. JavaScript

Implement a Map Using the Google Map API for Flash

Scroll to top
Read Time: 13 min

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This tutorial was first published in May, 2009.

In this tutorial we'll see how we can create a map in Flash using the Google Map API. We'll cover some of the basics such as zooming in on the map and adding some controls. We'll also look at how we can add markers to our map and how we can load data using an XML file.


Step 1: The Google Map API Key

Before we can start creating our map in Flash we need to setup a few things. To use the Google Map API you will need a personal API Key. To get this go to http://code.google.com/intl/nl/apis/maps/documentation/flash/ and click the link on the right side of the page "Sign up for a Google Maps API Key".

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 2: Sign Up

Clicking the "Sign up for a Google Maps API Key" link brings us to the next page where we can generate our personal API Key. Scroll down the page, agree with the terms and conditions (you could read these too if you're really interested) and add the url of the website where you want to use the application (you will need a different API Key for every domain where you want to place a map). After that, click "Generate API Key".

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 3: Save It!

Now you'll see your personal API Key for the selected domain. Copy the API Key and paste or save it somewhere as we'll need it very soon.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 4: The Google Map SWC Component

Ok, now we have our API Key but we still need one more thing before we can start to create our map in Flash. We need to download the Google Map SWC component. To do so, go to http://code.google.com/intl/nl/apis/maps/documentation/flash/ and click "Download the Google Maps API for Flash SDK". A popup window will appear, choose to Save the "sdk.zip" file and download it.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 5: Install the SDK Component

Now we need to install the SDK component to use it in Flash. To do so, navigate to the location where you saved the Google Maps API for Flash SDK and find the non-Flex version of the interface library. In my case this is (lib/map_1_9.swc). Now copy the "map_1_9.swc" file.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 6: Folders

Afterwards, if you have Flash currently open, quit the application and search for this folder:

  • (Windows) C:\Program Files\Adobe\Adobe Flash CS3 (or your Flash version)\en (or your language)\Configuration\Components
  • (Mac OS X) Macintosh HD/Applications/Adobe Flash CS3 (or your Flash version)/Configuration/Components

Inside that folder create a new folder named "google" and Paste the "map_1_9.swc" file inside it. Flash is now set up to support the Google Maps API for Flash.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 7: New ActionScript 3.0 File

Ok. That's all done and dusted! Now we can finally start creating our map in Flash. Start Flash CS3 or CS4 and create a new ActionScript 3.0 file, default stage size (550 x 400).

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 8: Save It!

Now simply save the file; hit "Ctrl+S" or go to File > Save in the menu. Save it to the location you want and name it whatever you want. I'll name it "google_map".

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 9: The GoogleMapsLibrary

Open the Components panel "Ctrl+F7" or click Window > Components in the menu and drag the GoogleMapsLibrary onto the stage.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 10: The Actions Layer

Create a new layer, double-click on its name and rename it to "actions".

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 11: Import..

Now with the actions layer selected open the actions panel by hitting "F9" or clicking Window > Actions. Add these lines of code:

1
2
import com.google.maps.LatLng;
3
import com.google.maps.Map;
4
import com.google.maps.MapEvent;
5
import com.google.maps.MapType;
google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 12: Create the Map

Now let's add the map! When we load the movie this piece of code will create a map and set it on the stage. Inside the code we see the variable "map.key"; here we have to add our personal API Key. Open the file where you saved the API Key and Copy/Paste it into the variable.

1
2
// Create The Map

3
var map:Map = new Map();
4
map.key = "Your API Key here";
5
map.setSize(new Point(stage.stageWidth, stage.stageHeight));
6
this.addChild(map);
google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 13: Test Movie

Ok, now go and test your movie "Ctrl+Enter" or click Control > Test Movie in the menu and you will see that you've just created a map.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 14: Controls

At this stage we can only drag the map around. That's not really what we're looking for, so let's add some controls to the map which will allow us to zoom and move about. To add controls to our map we need to update our code. First we need to call a few extra classes:

1
2
import com.google.maps.controls.ZoomControl;
3
import com.google.maps.controls.PositionControl;
4
import com.google.maps.controls.MapTypeControl;

After that we need to create a new function to call once the map is created. We name that function "onMapReady()". Inside this function we add our controls to the map.

1
2
function onMapReady(event:MapEvent):void {
3
  map.addControl(new ZoomControl());
4
  map.addControl(new PositionControl());
5
  map.addControl(new MapTypeControl());
6
}

Now we just need to call the "onMapReady()" function whenever our map is loaded. To do that we need to add a extra line to our first piece of code.

1
2
map.addEventListener(MapEvent.MAP_READY, onMapReady);

Our full code now looks like this:

1
2
import com.google.maps.LatLng;
3
import com.google.maps.Map;
4
import com.google.maps.MapEvent;
5
import com.google.maps.MapType;
6
import com.google.maps.controls.ZoomControl;
7
import com.google.maps.controls.PositionControl;
8
import com.google.maps.controls.MapTypeControl;
9
10
// Create The Map

11
var map:Map = new Map();
12
map.key = "Your API Key Here";
13
map.setSize(new Point(stage.stageWidth, stage.stageHeight));
14
map.addEventListener(MapEvent.MAP_READY, onMapReady);
15
this.addChild(map);
16
17
function onMapReady(event:MapEvent):void {
18
  map.addControl(new ZoomControl());
19
  map.addControl(new PositionControl());
20
  map.addControl(new MapTypeControl());
21
}
google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 15: More..

Now test your movie "Ctrl+Enter" or click Control > Test Movie in the menu and you will see our map now has controls. We're able to zoom in and even change our map to Satellite, Hybrid and Terrain view. That's very cool but we want more..

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 16: Latitude and Longitude

Let's zoom into a specific location once our map loads for the first time. Say I'm a surfer and I want to create a map of the surf spots in my home town. We don't want people to manually have to zoom in and search for the area, so we'll fix that in a sec. The only thing we have to add is one small line of code to our "onMapReady()" function.

1
2
map.setCenter(new LatLng(28.74659,-13.93447), 9, MapType.HYBRID_MAP_TYPE);

What we actually do here is create a new LatLng point on the map. First we specify 2 values: the "latitude" and the "longitude" from our region. Then we set our zoom value; I opted to use 9. The zoom ranges from 0 to about 16 (this can vary from region to region). Lastly we set the map type; I opted here for the HYBRID_MAP_TYPE.

Our "onMapReady()" function now looks like this:

1
2
function onMapReady(event:MapEvent):void {
3
  map.setCenter(new LatLng(28.74659,-13.93447), 9, MapType.HYBRID_MAP_TYPE);
4
  map.addControl(new ZoomControl());
5
  map.addControl(new PositionControl());
6
  map.addControl(new MapTypeControl());
7
}

If we test our movie you can see that lots of things have changed. Once the map is loaded we zoom into our specific region and our map type is now Hybrid. To determine the latitude and longitude for your region you could use Google Earth or an online tool like http://itouchmap.com/latlong.html.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 17: Add a Marker

Now let's add a simple marker to our map. Just add 2 more classes:

1
2
import com.google.maps.overlays.MarkerOptions;
3
import com.google.maps.overlays.Marker;

and update the "onMapReady()" function with this piece of code:

1
2
var marker:Marker = new Marker(
3
							     new LatLng(28.74659, -13.93447)	     		           
4
		     		            );
5
map.addOverlay(marker);

Again we create a LatLng point with some specific latitude/longitude values for our location. Then we call the "addOverlay()" to put our marker on the map. Our full code now looks like this:

1
2
import com.google.maps.LatLng;
3
import com.google.maps.Map;
4
import com.google.maps.MapEvent;
5
import com.google.maps.MapType;
6
import com.google.maps.controls.ZoomControl;
7
import com.google.maps.controls.PositionControl;
8
import com.google.maps.controls.MapTypeControl;
9
import com.google.maps.overlays.MarkerOptions;
10
import com.google.maps.overlays.Marker;
11
12
// Create The Map

13
var map:Map = new Map();
14
map.key = "ABQIAAAAUeTGkbea0ftVnzbVMwAPKxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTlsMw9FdPd5mJqEw01CzwnlVdxDw";
15
map.setSize(new Point(stage.stageWidth, stage.stageHeight));
16
map.addEventListener(MapEvent.MAP_READY, onMapReady);
17
this.addChild(map);
18
19
function onMapReady(event:MapEvent):void {
20
  map.setCenter(new LatLng(28.74659,-13.93447), 9, MapType.HYBRID_MAP_TYPE);
21
  map.addControl(new ZoomControl());
22
  map.addControl(new PositionControl());
23
  map.addControl(new MapTypeControl());
24
  
25
  var marker:Marker = new Marker(
26
							     new LatLng(28.74659, -13.93447)	     		           
27
		     		            );
28
  map.addOverlay(marker);
29
}

Go and test your movie. You'll see our marker on the map.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 18: Still More..

Now let's take everything to the next level. We have a map with zoom controls and a marker. What more do we need? Well I'll tell you. We need MORE MARKERS, TOOLTIPS, INFO WINDOWS and we want to load everything from an XML file. So let's get started. First we'll create our XML file. Open your Favorite XML editor and create this file:

1
2
<?xml version="1.0" encoding="utf-8"?>
3
 <map_xml>
4
 
5
  <location>
6
   <lat>28.74659</lat>
7
   <lon>-13.93447</lon>
8
   <name_tip>Majanicho</name_tip>
9
   <title_tip><![CDATA[Majanicho]]></title_tip>
10
   <content_tip><![CDATA[Majanicho is a very good surf spot for longboarding it offers very long rides.]]></content_tip>
11
  </location>
12
  
13
  <location>
14
   <lat>28.738764</lat>
15
   <lon>-13.955126</lon>
16
   <name_tip>Derecha de los Alemanes</name_tip>
17
   <title_tip><![CDATA[La Derecha de los Alemanes]]></title_tip>
18
   <content_tip><![CDATA[La Derecha de los Alemanes is another very good spot for longboarders but shortboarders will have some epic days out here to.]]></content_tip>
19
  </location>
20
  
21
  <location>
22
   <lat>28.741022</lat>
23
   <lon>-13.951821</lon>
24
   <name_tip>The Bubbel</name_tip>
25
   <title_tip><![CDATA[The Bubbel aka La Derecha]]></title_tip>
26
   <content_tip><![CDATA[The Bubbel is one of the most famouse waves in Fuerteventura its a really hollow reef break and it has some epic barrels on offer.]]></content_tip>
27
  </location>
28
 
29
 </map_xml>

Step 19: onMapReady()

Once our map is loaded we need to pull the XML data into our Flash file. Create a new function named "xmlLoader()" and we'll call that function in our "onMapReady()" function. First we need to delete the code we added to create our marker just a few steps before. Then we'll add the line to call the "xmlLoader()" function. Our "onMapReady()" function should now look like this:

1
2
function onMapReady(event:MapEvent):void {
3
  map.setCenter(new LatLng(28.74659,-13.93447), 9, MapType.HYBRID_MAP_TYPE);
4
  map.addControl(new ZoomControl());
5
  map.addControl(new PositionControl());
6
  map.addControl(new MapTypeControl());
7
  xmlLoader();
8
}

Next we want to create the "xmlLoader()" function.

1
2
function xmlLoader(){
3
	
4
}

In the next step we'll fill it up.


Step 20: Load XML

Ok here we are. Let's load our XML data. Inside the "xmlLoader()" function we add this code:

1
2
 function loadXML(e:Event):void{
3
	 XML.ignoreWhitespace = true; 
4
	 var map_xml:XML = new XML(e.target.data);
5
 }// end of loadXML function

6
7
 var xmlLoader:URLLoader = new URLLoader();
8
 xmlLoader.addEventListener(Event.COMPLETE, loadXML);
9
 xmlLoader.load(new URLRequest("xml.xml"));

This will get us our XML data to work with.


Step 21: Loop Through the Locations

As we have 3 locations in our XML file we'll need to create a "For" loop and store all the data in some Arrays. Inside our "loadXML()" function we add this piece of code to create the For loop:

1
2
for (var i:Number = 0; i < map_xml.location.length(); i++){
3
		 trace(map_xml.location[i].title_tip);
4
		 		
5
	 }// end of for loop

To test if things are working for us we'll trace the "title_tip" variable. Test your movie and you should get the following output:

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 22: Variables

Next we have to create some variables to store our data loaded from the XML file. Inside our For loop we add these variables:

1
2
var latlng:LatLng = new LatLng(map_xml.location[i].lat, map_xml.location[i].lon);
3
var tip = map_xml.location[i].name_tip;
4
var myTitle:String = map_xml.location[i].title_tip;
5
var myContent:String = map_xml.location[i].content_tip;

If you want you can delete the "trace()" line we used before. Our For loop now looks like this:

1
2
for (var i:Number = 0; i < map_xml.location.length(); i++){
3
		 
4
		 var latlng:LatLng = new LatLng(map_xml.location[i].lat, map_xml.location[i].lon);
5
		 var tip = map_xml.location[i].name_tip;
6
		 var myTitle:String = map_xml.location[i].title_tip;
7
		 var myContent:String = map_xml.location[i].content_tip;		 		
8
	 }// end of for loop

Step 23: Additional Markers..

Ok! We need to add a marker to the map for each of our three locations. Now that we have all the data stored in our variables we'll have to create a new function named "createMarker()". Inside our "loadXML()" function we add this new function:

1
2
// Add Markers On The Map

3
function createMarker(latlng:LatLng, number:Number, tip, myTitle, myContent):Marker {
4
               var i:Marker = new Marker(
5
										 latlng,
6
										 new MarkerOptions({ 
7
                                                           hasShadow: true,
8
				                                           tooltip: ""+tip  
9
                                                           })
10
										 );
11
               return i;
12
}// end function createMarker

We still need to call this "createMarker()" function in order to see our markers on the map. To do that we need to add a extra line of code at the end of our For loop:

1
2
map.addOverlay(createMarker(latlng,i, tip, myTitle, myContent));

This is what our "loadXML()" function should look like now:

1
2
function loadXML(e:Event):void{
3
	 XML.ignoreWhitespace = true; 
4
	 var map_xml:XML = new XML(e.target.data);
5
	 
6
	 for (var i:Number = 0; i < map_xml.location.length(); i++){
7
		 
8
		 var latlng:LatLng = new LatLng(map_xml.location[i].lat, map_xml.location[i].lon);
9
		 var tip = map_xml.location[i].name_tip;
10
		 var myTitle:String = map_xml.location[i].title_tip;
11
		 var myContent:String = map_xml.location[i].content_tip;
12
		 
13
		 map.addOverlay(createMarker(latlng,i, tip, myTitle, myContent));
14
	 }// end of for loop

15
	 
16
	 // Add Markers On The Map

17
	 function createMarker(latlng:LatLng, number:Number, tip, myTitle, myContent):Marker {
18
               var i:Marker = new Marker(
19
										 latlng,
20
										 new MarkerOptions({ 
21
                                                           hasShadow: true,
22
				                                           tooltip: ""+tip  
23
                                                           })
24
										 );
25
               return i;
26
      }// end function createMarker

27
 }// end of loadXML function

Test your movie and you will see the markers on the map! Note that our 3 points are very close to each other so you may want to zoom in a bit to see them more clearly.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Step 24: Info Windows

Finally we need to add some Info Windows. If we click on the markers we'll then get some information about their locations. To do so we need to add 2 more classes:

1
2
import com.google.maps.InfoWindowOptions;
3
import com.google.maps.MapMouseEvent;

..a little more code to our "createMarker()" function..

1
2
i.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent):void 
3
        {
4
         map.openInfoWindow(event.latLng, new InfoWindowOptions({
5
                                      titleHTML: ""+myTitle, 
6
                                      contentHTML: ""+myContent
7
                                                               }));
8
																			  											 
9
		});

Now test your movie and you'll see that our markers are now clickable and that they create an info window with text from the XML file.

google maps api for flashgoogle maps api for flashgoogle maps api for flash

Conclusion

Thats it! Take a look at our final code:

1
2
import com.google.maps.LatLng;
3
import com.google.maps.Map;
4
import com.google.maps.MapEvent;
5
import com.google.maps.MapType;
6
import com.google.maps.controls.ZoomControl;
7
import com.google.maps.controls.PositionControl;
8
import com.google.maps.controls.MapTypeControl;
9
import com.google.maps.overlays.MarkerOptions;
10
import com.google.maps.overlays.Marker;
11
import com.google.maps.InfoWindowOptions;
12
import com.google.maps.MapMouseEvent;
13
14
// Create The Map

15
var map:Map = new Map();
16
map.key = "Your API Key Here";
17
map.setSize(new Point(stage.stageWidth, stage.stageHeight));
18
map.addEventListener(MapEvent.MAP_READY, onMapReady);
19
this.addChild(map);
20
21
function onMapReady(event:MapEvent):void {
22
  map.setCenter(new LatLng(28.74659,-13.93447), 9, MapType.HYBRID_MAP_TYPE);
23
  map.addControl(new ZoomControl());
24
  map.addControl(new PositionControl());
25
  map.addControl(new MapTypeControl());
26
  xmlLoader();
27
}
28
29
function xmlLoader(){
30
 function loadXML(e:Event):void{
31
	 XML.ignoreWhitespace = true; 
32
	 var map_xml:XML = new XML(e.target.data);
33
	 
34
	 for (var i:Number = 0; i < map_xml.location.length(); i++){
35
		 
36
		 var latlng:LatLng = new LatLng(map_xml.location[i].lat, map_xml.location[i].lon);
37
		 var tip = map_xml.location[i].name_tip;
38
		 var myTitle:String = map_xml.location[i].title_tip;
39
		 var myContent:String = map_xml.location[i].content_tip;
40
		 
41
		 map.addOverlay(createMarker(latlng,i, tip, myTitle, myContent));
42
	 }// end of for loop

43
	 
44
	 // Add Markers On The Map

45
	 function createMarker(latlng:LatLng, number:Number, tip, myTitle, myContent):Marker {
46
               var i:Marker = new Marker(
47
										 latlng,
48
										 new MarkerOptions({ 
49
                                                           hasShadow: true,
50
				                                           tooltip: ""+tip  
51
                                                           })
52
										 );
53
			   i.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent):void 
54
																			  {
55
																			  map.openInfoWindow(event.latLng, new InfoWindowOptions({
56
																																	 titleHTML: ""+myTitle, 
57
																																	 contentHTML: ""+myContent
58
																																	 }));
59
																			  											 
60
																			  });
61
               return i;
62
      }// end function createMarker

63
 }// end of loadXML function

64
65
 var xmlLoader:URLLoader = new URLLoader();
66
 xmlLoader.addEventListener(Event.COMPLETE, loadXML);
67
 xmlLoader.load(new URLRequest("xml.xml"));
68
}

Test your movie Ctrl+Enter to check the outcome. You'll have your own xml based Flash map! You can use it on your website, edit the locations as you want, it's up to you. Go ahead and experiment, if you have any cool results be sure to share them with us.

I hope you liked this tutorial, thanks for reading!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.