This site is now just an archive over the rise and fall of Flash. The domain is available for sale
Login | Register
Integrate Google Maps into your application

Integrate Google Maps into your application

For businesses with traditional brick-and-mortar locations, providing patrons with driving directions to their location is a way to make these businesses easier to find. Many sites that provide such directions do so using mapping sites such as Google Maps through specific URLs. Allowing users to leverage Google Maps without leaving your site is a great way to enhance your page while keeping them there so they can view more of your content.

This article introduces you to the Google Maps application programming interface (API), which enables you to use Google’s mapping services inside your Web application. You can build a Web application that uses the Google Maps API in a traditional HTML Web application or a rich Internet application (RIA) built using Adobe Flash Builder. After reading this article, you’ll see how easy it is to use such APIs with Adobe Flex and Flash Builder.


Before getting started, you’ll need Flash Builder, a Google Maps API key from Google, and the Google Maps Adobe ActionScript 3 (AS3) mapping component. You can quickly set these components up by following the steps listed in the sections that follow.

Installing Flash Builder

If you don’t already have Flash Builder installed, you can download it from the Adobe site. You can install Flash Builder either as a stand-alone product or as a plug-in to an existing Eclipse integrated development environment (IDE).

Getting a Google Maps API key

You need a Google Maps API key for each domain that uses the Google Maps API. To obtain a key, go to the Google Maps API Family site to sign up. Enter the name of your domain, and then click Generate API Key if you agree to the terms and conditions. The site generates a key for you and provides samples for using it in JavaScript and Adobe Flash. For now, either print this page to PDF or save the page so that you can use the key later in your code.

Downloading the Google Maps AS3 component

The AS3 component that you can use in your application is included in the Google Maps API for Flash software development kit (SDK). Download the SDK and save it in a location that is easy to remember. Don’t worry about extracting the ZIP file yet: you’ll import the component directly from the archive file into Flash Builder. At this point, you should have Flash Builder installed, a Google Maps API key generated, and the Google Maps AS3 component downloaded. Now that you have your tools, you’re ready to build a simple yet cool application!


You need to create a new project in Flash Builder for your sample application. To do so, perform the following steps:

1.Click File > New > Flex Project.

2.In the New Flex Project window, enter the name for your project in Project Name (for example, My First Map).

3.Accept the defaults for the remainder of the options, including leaving the Application Type a web application, as shown in Figure 1.


Figure 1. Creating the new Flex project

Now that you’ve created your Flex project, import the map_flex_1_18b.swc file from the SDK archive file lib directory into your Flex project’s libs directory.

Import the Google Maps AS3 component

To import the file, click File > Import, and then click General\Archive File. Navigate to the SDK’s archive file that you downloaded. Inside the libs directory, select the map_flex_1_18b.swc file, and then click OK.

Adding this SWC file to your Flash Builder project adds all of Google Maps’ available components, methods, and properties to your Flash Builder project, as Figure 2 shows.


Figure 2. Importing the SWC file into the project’s libs directory

Create the application’s MXML file

If you want to dive right into the code and see what’s going on, simply modify the MyFirstMap.mxml file until it appears as shown in Listing 1. Make sure you change the key and url properties of your Map object to reflect your Google Maps API key and URL.

Listing 1. MyFirstMap.mxml


Now, build and run your application by clicking Run > Run MyFirstMap in Flash Builder. You should see a map similar to the one shown in Figure 3.


Figure 3. The application in action, showing the map from Google Maps

If you want the full details on what this code is doing, grab your favorite beverage and keep reading.


The sample application is broken down into MXML and AS3 code. The sample application is written using a single MXML file, located in the src directory of the project.

Create the basic interface

Begin building the basic application by declaring an initial along with the labels, text input controls, and button controls shown in Listing 2.

Listing 2. The base application MXML


The application contains two input controls: one to allow the user to enter the source and the other for the destination. In the sample here, the initial destinations are hardcoded.

Add the map component

The Google Maps API offers native support for the component when you include Google’s SWC library. This means you won’t have to extend the Map class but can use the component directly in your MXML code.

To add the Map component, first add the namespace as an attribute to the root node, then add the Map component as shown in Listing 3.

Listing 3. Adding the Map component


The applications you create in Flash Builder are event-driven applications that use AS3 code to handle the events. You will add an event listener named mapevent_mapready later in this article that simply listens for when the map is in a ready state, and then executes your custom ActionScript code.


You define ActionScript code that is your application’s logic inside a object in your MXML file. The object is a Flash Builder component that holds all of your ActionScript code. Because MXML is a well-formed XML, you need to tell the MXML parser to ignore your ActionScript code to avoid XML parsing errors by using the CDATA wrapper around the code, as shown in Listing 4.

Listing 4. The mx: Script object with ActionScript code


Within that element, import any AS3 classes that you need to create objects, listen for events, and handle events. We recommend that you import only those classes you need. Including any Flash Builderunnecessary libraries that may substantially increase the size of your SWF files.

Handling the map ready event

The onMapReady() event handler shown in Listing 5 starts by centering the map display at the given latitude and longitude and sets the map type to Normal. You can specify other map types, such as Hybrid, Physical, or Satellite, or allow users to specify the map type themselves.

Listing 5. The onMapReady() event handler initializes the Map component

private function onMapReady(event:MapEvent):void {
				map.setCenter(new LatLng(41.651505,-72.094455), 8, MapType.NORMAL_MAP_TYPE);
				dir = new Directions();
				dir.addEventListener(DirectionsEvent.DIRECTIONS_SUCCESS, onDirLoad);
				dir.addEventListener(DirectionsEvent.DIRECTIONS_FAILURE, onDirFail);
				map.addControl(new NavigationControl());
				map.addControl(new MapTypeControl());
				//map.viewMode = View.VIEWMODE_PERSPECTIVE;

The onMapReady() method creates a new Directions service and adds event listeners for the success and failure events that might occur when the service’s methods are called.

After creating the onMapReady() event handler, add it to the Maps component’s mapevent_mapready event:

Add a map marker

In many cases, you may want to show a location marker, also known as Map Marker. A Map Marker is one of the little red images that points to a specific location on the map. A marker has to be given a latitude and longitude (in the form of the LatLng object) and looks something like this:

	var latlng:LatLng = new LatLng(42.22,-83.75);	
	var marker:Marker= new Marker(latlng); map.addOverlay(marker);

Adding Map Markers increases the usability of your Google Maps application. Users will be able to click a Map Marker to get their destination instead of manually entering a destination.

For simplicity, we hard-coded Ann Arbor as a destination for the Map Marker when users click the Map Marker; however, you could easily display multiple Map Markers by giving users multiple destinations to choose from.

With a bit of creativity, you can really spice up your maps, because Map Markers are customizable, meaning that you can change the color and size, make the markers more interactive, and even implement your own icons and images as markers. It’s beyond the scope of this article, but we wanted to jump start your imagination.

When the Map is loaded, create a Map Marker using the code in Listing 6.

Listing 6. Create a Map Marker

private function createMarker ():void{
				var myMarker:Marker = new Marker (
					new LatLng(42.22, -83.75),
					new MarkerOptions({
						strokeStyle: new StrokeStyle({color: 0x6}),
						radius: 12,
						hasShadow: true
				myMarker.addEventListener(MapMouseEvent.CLICK, function(event:Event):void{

Now that you’ve handled the event on the Map component and created a Map Marker, you’re ready to add event handlers to the application’s buttons.

Add code to get directions

When users click Get Directions, the processDirections event handler shown in Listing 7 processes the click event.

Listing 7. The processDirections event handler

private function processDirections(event:Event):void {
				dir.load("from: " + from.text + " to: " + to.text);
				getTurnByTurnDirections.enabled = true;
				// Reset turnCounter to zero for new directions
				turnCounter = 0;
				step.htmlText = "Start at " + from.text;

This event handler calls the load() method on the Directory service that you created earlier. After calling the method, the processDirections event handler enables the button for getting turn-by-turn directions (getTurnByTurnDirections), resets the turn counter, and initializes the directions for the user.

If the load() method succeeds, the onDirLoad event handler set in the onMapReady event handler is executed. The onDirLoad() event handler is shown in Listing 8.

Listing 8. The onDirLoad() event handler

private function onDirLoad(event:DirectionsEvent):void {
				var dir:IDirections = event.directions;      
				var startMarker:Marker;
				var endMarker:Marker;
				startMarker = new Marker(dir.getRoute(0).startGeocode.point, 
					new MarkerOptions({fillStyle: {color:Color.GREEN}}));
				endMarker = new Marker(dir.getRoute(0).endGeocode.point, 
					new MarkerOptions({fillStyle: {color:Color.BLUE}}));

The onDirLoad() event handler receives the directions event, then creates the start marker and end marker. When those objects have been created, the handler adds them to the Map component for users to see and interact with.

The route is added to the map using the addOverlay() method of the map from the directions returned in the DirectionsEvent. Add the processDirections event handler to the getDirections button:

When the initial route is displayed on the map, users can click Get Next Step to get turn-by-turn directions.

Getting the next step

The processTurnByTurn event handler shown in Listing 9 gets the turn-by-turn directions from the Google Maps Direction service and displays them to the user.

Listing 9. The processTurnByTurn event handler

private function processTurnByTurn():void  {
				var stepText:String;
				var stepMarker:Marker;
				if (turnCounter <= dir.getRoute(0).numSteps) {
					stepText = dir.getRoute(0).getStep(turnCounter-1).descriptionHtml;
					stepMarker = new Marker(dir.getRoute(0).getStep(turnCounter-1).latLng, new MarkerOptions({label: turnCounter.toString()}));
					step.htmlText = "Step " + turnCounter + ": " + stepText;  
				} else {
					getTurnByTurnDirections.enabled = false;
					step.htmlText = "Arrive at " + to.text + " : " + dir.getRoute(0).summaryHtml;

The event handler starts by creating a variable (stepText) to hold your turn-by-turn text and a variable to display the marker for each turn. If the turn counter is less than or equal the number of steps, the handler sets the display text and creates a new step marker to add to the existing Map component. If all of the steps have been taken, the method disables the button for getting the turn-by-turn directions and simply displays the destination text.

Now, add the event handler to the click event on the getTurnByTurnDirections button:


Now that you’ve created the MXML file, added the Google Maps component and the ActionScript code to handle the events, you can share your new RIA with the world. It’s a relatively easy task to execute the application directly in Flash Builder.

Export the release build

To export your Flash Builder project and host your finished application on a Web page, select your project, and then click File > Export > Release Build. Verify the name of the project and application MXML file, and accept the defaults as listed in the Export Release Build window, as shown in Figure 4.


Figure 4. >Deploying the application

Click Finish to export your application.

Flash Builder compiles and exports your completed application to the bin-release directory of your Flash Builder project. It also compiles your application into one SWF file. This file is viewable with any device that has a fairly recent version of Adobe Flash Player.

In addition to the SWF file, Flash Builder copies an HTML file to the bin-release directory. You can view the HTML file in any Web browser, and it includes references to the SWF file. Other supporting files, such as swfobject.js and SWZ files, are also exported to the bin-release directory.

Copy the output

You can simply copy the MyFirstMap.html, MyFirstMap.swf, and other supporting files in the bin-release directory to your Web server and direct users to the MyFirstMap.html page. You can also embed the MyFirstMap.swf file on any existing Web page. For best results across all browsers, consider using the swfobject.embedSWF JavaScript function in the MyFirstMap.html file. This function is found in the swfobject.js file, which is copied into your bin-release folder.

Note: We’ve enabled view-source mode so that anyone who visits our site can right-click and see how we coded our application. Visitors can download the source files and play with the code in their own Flash Builder IDE.


Flash Builder allows you to build RIAs that include functionality to engage your users and to help keep them on your site longer. APIs like the Google Maps API allow you to easily add components to your application to use its services.

The example given in this article was using the Google Maps API within a Flash Builder environment. To learn more about adding functionality to your site, check out the “For More Information” section below.


To learn more about Flash Builder, see the Adobe Flash Builder site.

To learn more about the Google Maps API for Flash SDK, see the Google Maps API for Flash Developers Guide.

To obtain a key for the Google Maps API, see the Google Maps API Family site.


Get new stories first

Click to follow us on Twitter!



No comments for this page.

Submit a comment

Only registered members can comment. Click here to login or here to register