Advertisement
  1. Code
  2. Coding Fundamentals
  3. XML

Using Google Maps' New Features for Flash

Scroll to top
13 min read

After such a positive response to my first tutorial Implement a Map Using the Google Map API for Flash I decided to write a second. Since that first tut the Google Map API has been updated, allowing developers to (amongst other things) add 3D viewing to maps. This is a great feature and during this tutorial I'll explain how to use it.

Also, lots of people requested an explanation for adding custom markers; that's the second thing we'll discuss here today.

Step 1: Download The SDK Component

I won't build further on our previous map because we need to download the new Google Map Component. There is no way to use the component from my previous tutorial as that one does not support the 3D functions. So... go to http://code.google.com/intl/nl/apis/maps/documentation/flash/

Step 2: Install the SDK Component

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 SDK Component and find the non-Flex version of the interface library. In my case this is (lib/map_1_18.swc). Now copy the "map_1_18.swc" file.

Step 3: 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_18.swc" file inside it. Flash is now set up to
support the Google Maps API for Flash.

Step 4: The Google Map API Key

Ok we have the component now but before we can get to work we still need a Google Map API Key to get our map working online. A Google Map API Key is free and you can get one here:

http://code.google.com/intl/nl/apis/maps/documentation/flash/
.

Step 5: 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".

Step 6: 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.

Step 7: New ActionScript 3.0 File

OK, the boring work is done, now we can start with the fun stuff! Let's dive into Flash and create a new ActionScript 3.0 file, default stage size (550 x 400).

Step 8: Save It

I prefer to start off by saving the file. While I'm working I really like to Hit "Ctrl+S" all the time, so go ahead hit
"Ctrl+S" or click "File > Save" in the menu. Save it to the location you want and name it whatever you want. I will name it
"google_map".

Step 9: The GoogleMapsLibrary

Open the Components panel "Ctrl+F7" or click Window > Components in the menu. Drag the GoogleMapsLibrary into your library.

Step 10: The Actions Layer

To keep organized I like to rename the first layer to "actions".

Step 11: Import

With the actions layer selected open the actions panel (hit "F9" or click "Window > Actions") and add these lines of code:

1
2
		import com.google.maps.LatLng;
3
        import com.google.maps.Map;
4
        import com.google.maps.Map3D;
5
        import com.google.maps.MapEvent;
6
        import com.google.maps.MapType;
7
        import com.google.maps.View;
8
        import com.google.maps.geom.Attitude;

Step 12: Create the Map

Now we'll create our first function. First we want to declare our Map variable:

1
2
    	// Variables

3
        var map:Map3D;

Now we can add our function that we will call to add the main map on the stage:

1
2
    	// Function that adds the map on stage

3
        function add_map()
4
        {
5
			map = new Map3D();
6
    		map.key = "YOUR_API_KEY_HERE";
7
            map.setSize(new Point(stage.stageWidth, stage.stageHeight));
8
    		map.addEventListener(MapEvent.MAP_READY, onMapReady);
9
    		this.addChild(map);
10
		}

OK, as you can see we added an eventlistener that will fire once our map is loaded, so lets also create that function:

1
2
    	// Function that will fire once map is created

3
		function onMapReady(event:MapEvent):void 
4
		{
5
		    map.setCenter(new LatLng(50.899197766773284, 4.486040573103489), 13);
6
			map.setAttitude(new Attitude(20,30,0));
7
		}

Here we've set the map to center. This function has 3 values and will define the location where the map will open. The
values are like this "map.setCenter(new LatLng(latitude, longitude), zoom);". Then we define the view mode;
as we are using the new 3D map I will use the Perspective view. If you like a normal map view you can change this value to
"View.VIEWMODE_2D".

Then we set the Attitude. This will define how we view the map. In this case we will add a little Perspective view to it and
turn the map a little to create a nicer view angle. You can play around with these values a bit and see what you like best.

OK, it's time for a first check! What do we have so far? Well, nothing yet! We first need to call our function to create the
map! Let's add this line of code just under our variables:

1
2
        // Variables

3
        var map:Map3D;
4
        
5
        // Call the function to create the map

6
        add_map();

There we go! Now just test your movie "Ctrl+Enter" or click Control > Test Movie in the menu...

Step 13: The Navigation Tools

Yes! We have a map zoomed in on Brussels Airport! Isn't that great?! Perhaps not... Let's take a look at what we have here. We have the map and we can drag the map around. So what we need next are tools to navigate around the map, zoom in and out on the map. Let's start with those navigation tools first!

First of all let's import 3 extra classes; add these lines under the other import code in our script:

1
2
    	import com.google.maps.controls.NavigationControl;
3
    	import com.google.maps.controls.MapTypeControl;
4
    	import com.google.maps.controls.OverviewMapControl;

No go to the onMapReady() function and add these 3 lines of code under the other lines:

1
2
    	map.addControl(new MapTypeControl());
3
    	map.addControl(new OverviewMapControl());
4
    	map.addControl(new NavigationControl());

Here we're adding the map type controls, so now we can change the map type. Then we add a map overview control to the right bottom of our map. And we add the map navigation tools. This is our full source code as it should look right now:

1
2
    	import com.google.maps.LatLng;
3
		import com.google.maps.Map;
4
		import com.google.maps.Map3D;
5
		import com.google.maps.MapEvent;
6
		import com.google.maps.MapType;
7
		import com.google.maps.View;
8
		import com.google.maps.geom.Attitude;
9
		import com.google.maps.controls.NavigationControl;
10
		import com.google.maps.controls.MapTypeControl;
11
		import com.google.maps.controls.OverviewMapControl;
12
13
		// Variables

14
		var map:Map3D;
15
16
		// Call the function to create the map

17
		add_map();
18
19
		// Function that adds the map on stage

20
		function add_map()
21
		{
22
			map = new Map3D();
23
    		map.key = 'YOUR_API_KEY_HERE';
24
			map.setSize(new Point(stage.stageWidth, stage.stageHeight));
25
    		map.addEventListener(MapEvent.MAP_READY, onMapReady);
26
    		this.addChild(map);
27
		}
28
29
		// Function that will fire once map is created

30
		function onMapReady(event:MapEvent):void 
31
		{
32
			map.setCenter(new LatLng(50.899197766773284, 4.486040573103489), 13);
33
			map.viewMode = View.VIEWMODE_PERSPECTIVE;
34
			map.setAttitude(new Attitude(20,40,0));
35
			map.addControl(new MapTypeControl());
36
    		map.addControl(new OverviewMapControl());
37
    		map.addControl(new NavigationControl());
38
		}

Go ahead and test your movie again. You can see that you can move around the map very easily now with these funky looking new
controls!

Step 14: A Bar Without Beer

I think it's time to move on to the markers part; a map without markers is like a bar without beer isn't it? No silly stuff this time! Let's move to the Custom markers straight away!

We want to place our custom markers onto the map with information that will be stored in an external XML file. Let's begin by creating a custom marker, then we'll create the XML file and after that we'll load it into Flash.

Step 15: Creating the Custom Marker

I'm not much of a designer so I think you'll be able to create a much cooler marker than I have! Thats why I'm not going spend too much time on this. Just draw a few circles, put them on top of each other, select everything, hit F8, select movieClip, name it "marker_mc" and select Export For Actionscript. Hit "OK".

As I mentioned before, I hope you will create a cooler and better looking marker than this! Just draw your own marker and
covert it to a moviclip as explained above.

Once you've created the movieclip it will appear in your library. You can then delete it from the stage as we will import it using
ActionScript (that's why you had to select the option "Export For ActionScript"). In our library we now have 2 items; the
GoogleMapsLibrary and our marker_mc.

Step 16: The XML file

OK, here we are. We have a map and (in your case) a very good looking marker! Now let's create the XML file. Open your favorite code editor, create this file and save it as locations.xml.

1
2
<?xml version="1.0" encoding="utf-8"?>
3
 <map_xml>
4
 
5
  <location>
6
   <lat>50.899197766773284</lat>
7
   <lon>4.486040573103489</lon>
8
   <name_tip>Brussels</name_tip>
9
   <title_tip><![CDATA[Brussels]]></title_tip>
10
   <content_tip><![CDATA[Brussels Airport.]]></content_tip>
11
  </location>
12
  
13
  <location>
14
   <lat>49.004024443647324</lat>
15
   <lon>2.571113562006575</lon>
16
   <name_tip>Paris</name_tip>
17
   <title_tip><![CDATA[Paris]]></title_tip>
18
   <content_tip><![CDATA[Paris Airport.]]></content_tip>
19
  </location>
20
  
21
  <location>
22
   <lat>51.4699229971675</lat>
23
   <lon>-0.45367874251784013</lon>
24
   <name_tip>London</name_tip>
25
   <title_tip><![CDATA[London]]></title_tip>
26
   <content_tip><![CDATA[London Airport.]]></content_tip>
27
  </location>
28
 
29
 </map_xml>

Step 17: Loading the XML

We need to get the XML data into our flash movie. To do so we need to create a new function that will load our xml. Add
this piece of code to the bottom of the script. Inside our onMapReady() function we call this new load_xml() function. Once our map is ready we will start loading the xml.

1
2
        // Function that will load the xml

3
    	function loadXML(e:Event):void
4
        {
5
	        XML.ignoreWhitespace = true; 
6
	        var map_xml:XML = new XML(e.target.data);
7
        }
8
        
9
        function load_xml()
10
        {
11
			var xmlLoader:URLLoader = new URLLoader();
12
			xmlLoader.addEventListener(Event.COMPLETE, loadXML);
13
			xmlLoader.load(new URLRequest("locations.xml"));
14
		}

Step 18: 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
        {
4
		    trace(map_xml.location[i].title_tip);	
5
	    }

If we test our movie now we can see our movie outputs the xml data. Now let's work with it.

Step 19: Create the 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;

You can delete the "trace()" line we used before as we know things are working.

Step 20: Adding the Markers on the Map

Now that we have all of our xml data stored in variables we can get over to load our markers onto the map. First we add some extra classes to our code. Add this piece of code under the other classes:

1
2
    	import com.google.maps.overlays.*;
3
		import com.google.maps.InfoWindowOptions;
4
        import com.google.maps.MapMouseEvent;

Create a new function called createMarker(). We want to add this function just before our loadXML() function.

1
2
    	// Add Markers On The Map

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

We can call the createMarker() function for every marker we need to add to the map, so inside our For Loop we add this line of code:

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

If you test the movie now you can see that we have markers on our map on the locations we specified in our xml file! That's great, but we didn't create that great custom marker for nothing did we? We'll remove those standard markers and add our custom markers.

Step 21: Add Custom Marker

First we need to create our custom marker object. Add this code into the createMarker() function, above the rest of the code:

1
2
    	// create Custom marker object

3
        var markerPin:marker_mc = new marker_mc();     
4
        // If your marker is to big you can scale it down here

5
	    markerPin.width = 20;
6
	    markerPin.height = 20;

Afterwards, we'll go to the next piece of code where we have to add a line to the markerOptions. Search for this piece of code:

1
2
    	new MarkerOptions({
3
                               hasShadow: true,
4
				               tooltip: ""+tip  
5
                         })

and change it to:

1
2
    	new MarkerOptions({
3
                               hasShadow: true,
4
                               icon: this.addChild(markerPin),
5
				               tooltip: ""+tip  
6
                         })

Ok! Test your movie and check the result!

Step 22: Moving On

OK, what's next? The Info windows! When we click our marker we need to get the information we added to our XML file.Before we add the information windows I just want to remove that ugly yellow line around our map, have you noticed already? When you focus on the map it shows a yellow line around it. I personally really don't like that, so let's remove it. Just add this line of code under our variables section:

1
2
    	// No focus line

3
        stage.stageFocusRect = false;

Ok thats done! Let's add Info windows. Add 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
		});

This is what our createMarker() function now looks like:

1
2
    	function createMarker(latlng:LatLng, number:Number, tip, myTitle, myContent):Marker 
3
		{
4
			// create Custom marker object

5
			var markerPin:marker_mc = new marker_mc();
6
			// If your marker is to big you can scale it down here

7
			markerPin.width = 20;
8
			markerPin.height = 20;
9
	
10
			var i:Marker = new Marker(
11
							  		latlng,
12
							  		new MarkerOptions({
13
														    hasShadow: true,
14
															icon: this.addChild(markerPin),
15
				            		                        tooltip: ""+tip  
16
                    		                           })
17
									 );
18
			i.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent):void 
19
    		{
20
				map.openInfoWindow(event.latLng, new InfoWindowOptions({
21
																	       titleHTML: ""+myTitle, 
22
                    		                                               contentHTML: ""+myContent
23
            		                                                  }));
24
																			  											 
25
    		});
26
			return i;
27
		}

Test your movie and you will now have info windows too.

Step 23: Complete Code

Well thats it! Congratulations, you just created a Google Map With 3D navigation and Custom markers! Very good job! Let's have a
final look at our code:

1
2
    	import com.google.maps.LatLng;
3
import com.google.maps.Map;
4
import com.google.maps.Map3D;
5
import com.google.maps.MapEvent;
6
import com.google.maps.MapType;
7
import com.google.maps.View;
8
import com.google.maps.geom.Attitude;
9
import com.google.maps.controls.NavigationControl;
10
import com.google.maps.controls.MapTypeControl;
11
import com.google.maps.controls.OverviewMapControl;
12
import com.google.maps.overlays.*;
13
import com.google.maps.InfoWindowOptions;
14
import com.google.maps.MapMouseEvent; 
15
16
// Variables

17
var map:Map3D;
18
19
// No focus line

20
stage.stageFocusRect = false; 
21
22
// Call the function to create the map

23
add_map();
24
25
26
// Function that adds the map on stage

27
function add_map()
28
{
29
	map = new Map3D();
30
    map.key = 'YOUR_API_KEY_HERE';
31
	map.setSize(new Point(stage.stageWidth, stage.stageHeight));
32
    map.addEventListener(MapEvent.MAP_READY, onMapReady);
33
    this.addChild(map);
34
}
35
36
// Function that will fire once map is created

37
function onMapReady(event:MapEvent):void 
38
{
39
	map.setCenter(new LatLng(50.899197766773284, 4.486040573103489), 13);
40
	map.viewMode = View.VIEWMODE_PERSPECTIVE;
41
	map.setAttitude(new Attitude(20,40,0));
42
	map.addControl(new MapTypeControl());
43
    map.addControl(new OverviewMapControl());
44
    map.addControl(new NavigationControl());
45
	
46
	// Load the xml

47
	load_xml();
48
}
49
50
51
// Add Markers On The Map

52
function createMarker(latlng:LatLng, number:Number, tip, myTitle, myContent):Marker 
53
{
54
	// create Custom marker object

55
	var markerPin:marker_mc = new marker_mc();
56
	// If your marker is to big you can scale it down here

57
	markerPin.width = 20;
58
	markerPin.height = 20;
59
	
60
	var i:Marker = new Marker(
61
							  latlng,
62
							  new MarkerOptions({
63
												    hasShadow: true,
64
													icon: this.addChild(markerPin),
65
				                                    tooltip: ""+tip  
66
                                               })
67
							 );
68
	i.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent):void 
69
    {
70
		map.openInfoWindow(event.latLng, new InfoWindowOptions({
71
															       titleHTML: ""+myTitle, 
72
                                                                   contentHTML: ""+myContent
73
                                                              }));
74
																			  											 
75
    });
76
	return i;
77
}
78
79
80
// Function that will load the xml

81
function loadXML(e:Event):void
82
{
83
	XML.ignoreWhitespace = true; 
84
    var map_xml:XML = new XML(e.target.data);	
85
	for (var i:Number = 0; i < map_xml.location.length(); i++)
86
	{
87
		var latlng:LatLng = new LatLng(map_xml.location[i].lat, map_xml.location[i].lon);
88
		var tip = map_xml.location[i].name_tip;
89
		var myTitle:String = map_xml.location[i].title_tip;
90
		var myContent:String = map_xml.location[i].content_tip;
91
		
92
		map.addOverlay(createMarker(latlng, i, tip, myTitle, myContent)); 
93
	}
94
}
95
96
function load_xml()
97
{
98
	var xmlLoader:URLLoader = new URLLoader();
99
	xmlLoader.addEventListener(Event.COMPLETE, loadXML);
100
	xmlLoader.load(new URLRequest("locations.xml"));
101
}

Conclusion

You can use this map 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.