English | Site Directory

Google Maps API for Flash

Google Maps for Enterprise

Includes enterprise licensing and support

Google Maps API for Flash Tutorial

Writing the "Hello World" of the Maps API for Flash

The easiest way to start learning about the Google Maps API for Flash is to see a simple example. In this tutorial, we'll create a simple Flash SWF file containing a map using ActionScript code, include that SWF file in an HTML page, and display it.

ActionScript Fundamentals

Maps within the Google Maps API for Flash are created and manipulated using ActionScript 3.0 code. This tutorial will not attempt to teach ActionScript. Online tutorials are available at the following locations:

The following ActionScript code displays a map centered on New York City:

package com.google.maps.examples {

import flash.events.Event;
import com.google.maps.Map;
import com.google.maps.MapEvent;
import com.google.maps.MapType;
import com.google.maps.LatLng;

public class HelloWorld extends Map {

  public function HelloWorld() {
    super();
    addEventListener(MapEvent.MAP_READY, onMapReady);
  }

  private function onMapReady(event:MapEvent):void {
    setCenter(new LatLng(40.736072,-73.992062), 14, MapType.NORMAL_MAP_TYPE);
  }
}

}

Note that this example defines a com.google.maps.examples namespace. As a result, this code (HelloWorld.as) should reside in a com/google/maps/examples directory structure within your source development tree.

This example is located at gmaps-samples-flash.googlecode.com/svn/trunk/examples/HelloWorld.html. (ActionScript source is located here.) Note that you'd need to build your own SWF file, with your own key, in order for this example to appear on your website.

Even in this simple example, there are five things to note:

  1. We declare a package for our Application code.
  2. We import a number of packages from the Google Maps API for Flash library.
  3. We write an ActionScript class to create a Map object.
  4. We create an event listener to indicate when the map loads.
  5. We center the map on a location once that event fires.

These steps are explained below.

Declaring Packages

package com.google.maps.examples {

ActionScript packages contain groups of related code and implicitly define a namespace that uniquely identifies that code. The package name acts as a prefix to any classes contained in the package (so the HelloWorld class above within package com.google.maps.examples defines the com.google.maps.examples.HelloWorld class).

Package declarations aren't strictly necessary within your Google Maps Flash code, and they don't technically need to use the top-level domain naming convention, though both are good ideas and the examples here will use these conventions.

Importing ActionScript Libraries

import flash.events.Event;
import com.google.maps.MapEvent;
import com.google.maps.Map;
import com.google.maps.MapType;
import com.google.maps.types.LatLng;

ActionScript libraries are imported with the import declaration. In the sample code above, we import one library related to standard Flash event handling, and several Google Maps Flash libraries. Note that the flash.events.Event library and the com.google.maps.MapEvent are both "event" libraries, and both are needed for Google Maps Flash applications.

You should ensure that you import libraries for types that you use within your sample code. We recommend that you import only those classes you need. In most of the example code within this documentation, we structure our code so that the Map will not link to Flex UI libraries. Doing so provides a basic lightweight map. For more complicated applications involving Flex user interface components, a Map object needs to be embedded into the Flex UI. Note that including any Flex libraries may substantially increase the size of your SWF files, even if you only need one particular Flex component (such as a button).

Setting Up Your Map Object

The fundamental object used within the Google Maps API for Flash is the Map object. Your Google Maps Flash application should define a class which extends the Map interface class. You must define a constructor within this class definition. ActionScript (like most programming languages) defines a constructor through a function with the same name as the defined class. You should call the superclass before you do any additional configuration through the super() method.

The following code defines a HelloWorld class which extends the base Map class. It also defines a constructor HelloWorld(), which calls its superclass (therefore calling the Map() constructor) and then attaches an event listener to the created object. (See Setting Up Event Listeners below for more information on event listeners.)

public class HelloWorld extends Map {

  public function HelloWorld() {
    super();
    addEventListener(MapEvent.MAP_READY, onMapReady);
  }

Setting Up Event Listeners

ActionScript, like JavaScript, is an event-driven programming language. Interactions with users within Flash objects are handled by registering event listeners on objects for specific events.

In the code snippet in the previous section, the constructor for the HelloWorld class added an event listener to the Map object for the MapEvent.MAP_READY event. When the map receives that event, it calls the onMapReady function, which is shown below.

  private function onMapReady(event:MapEvent):void {
    setCenter(new LatLng(40.736072,-73.992062), 14, MapType.NORMAL_MAP_TYPE);
  }

This onMapReady() function passes an event parameter of type MapEvent (which is ignored in this case) and then calls setCenter() using the given parameters (which define a location, a zoom level, and the type of map to show).

In general, it is good to "initialize" your map in such a manner by intercepting and handling the MapEvent.MAP_READY event. Most of the examples within this documentation only show code snippets within the onMapReady() event handler, omitting the requisite class declarations and constructor implementations for teh sake of clarity. Events are discussed in more detail within the Map Events section of the Google Maps Flash documentation.

Specifying the UI Container

Google Maps Flash applications require not only ActionScript code but also at least some minimal user interface framework to display the map and any associated UI elements on a web page. Within the Flex framework, these UI components are specified within an MXML declaration. An MXML declaration consists of a configuration file with the .mxml suffix. This MXML file commonly resides in the root of your ActionScript development directory.

In order to display your Flash map on a webpage, you will at least need a minimal MXML declaration. This declaration will specify the UI container, the class to instantiate, and the namespace for your application code. A sample MXML declaration named helloworld.mxml appears below:

<?xml version="1.0" encoding="utf-8"?>
<examples:HelloWorld xmlns:examples="com.google.maps.examples.*" key="ABCDEF" width="800" height="600"/>

This MXML declaration specifies only one UI component: an object of class "HelloWorld" attached to the examples namespace, which is defined as "com.google.maps.examples.*" The MXML declaration also specifies width and height parameters. More importantly, the MXML declaration acts as a convenient location to place your unique API key.

This helloworld.mxml file should be placed in the root of the ActionScript development directory; doing so implicitly defines the location for your ActionScript code within your com/google/maps/examples development directory.

Note that MXML declarations can be quite complex, and the layout of UI components within an MXML declaration is beyond the scope of this documentation To add a map to the Flex UI framework, you will need to add the Map object to an instance of UIComponent. For more information, see the provided examples and consult the Flex SDK documentation.

Compiling Your SWF File

We now have a HelloWorld.as ActionScript file and a helloworld.mxml MXML declaration within our source's com/google/maps/examples directory. We are ready to compile our code into a SWF (Shockwave Flash) file. We do so using the Flex SDK's mxmlc compiler.

The mxmlc compiler requires a target *.mxml file. As well, to use the Google Maps API for Flash, we use the compiler's -library-path parameter to add the location of the Google Maps API for Flash Library (maps_flash_1_1.swc) provided to you. A sample invocation appears below:

# Execute this command from the ROOT of your development directory, not from within 
# the leaf of the namespace (e.g. not in com/google/maps/examples)
#
hostname$:~/src/helloworld$ path_to_flex_sdk/bin/mxmlc helloworld.mxml -library-path+=maps_flash_1_1.swc
Loading configuration file /home/src/flex_sdk/frameworks/flex-config.xml
/home/src/helloworld/helloworld.swf (22223 bytes)

If you have trouble compiling:

  • Ensure you can execute the mxmlc compiler (you may want to change your path to add the Flex SDK's bin directory.
  • Ensure your MXML and ActionScript files are set up within the proper directory structure to reflect your declared namespace.
  • Ensure you add the library-path parameter using the "plus equals" operator (+=).

Once you have a helloworld.swf file, you can then place that file within a web page.

Hosting Your SWF File in a Web Page

Google Maps Flash SWF files, if they are compiled with the API key included, can simply be displayed as standalone files. This is useful for testing, but is not practical for proper page layout. As a result, you will likely want to set up an HTML page to contain the SWF file. To ensure your SWF file executes within both Internet Explorer and other browsers, you should add the SWF within both object and embed tags.

A simple HTML page that contains our helloworld.swf file appears below. For the map to display on a web page, we must reserve a spot for it. We do so in this example by creating a named div element and adding the object element to it.

  <div id="map_canvas" name="map_canvas">
    <object
      classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
      codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"
      width="800px"
      height="600px">
      <param name="movie" value="helloworld.swf">
      <param name="quality" value="high">
      <param name="flashVars" value="key=ABCDEF">
      <embed
        width="800px"
        height="600px"
        src="helloworld.swf"
        quality="high"
        flashVars="key=ABCDEFG"
        pluginspage="http://www.macromedia.com/go/getflashplayer"
        type="application/x-shockwave-flash">
      </embed>
    </object>
  </div>

Note that we add the API key parameter within a flashVars parameter. This registration method is an alternative to compiling your key into the SWF file within the MXML declaration. If values are specified here, they override values contained within the SWF file or MXML declaration.

The resulting HTML page is shown below.

 

View ActionScript code (HelloWorld.as)

Congratulations! You've written your first Google Maps Flash application!

Integrating Your Application within a Flex UI

The previous "Hello World" example (and most of the examples in this documentation set) declares a simple MXML file, which implicitly defines the only UI element within each sample application: the resulting Map itself. In practice, if you are a Flex developer, you will want to leverage and make use of the UI components available within the Flex toolkit. Doing so involves creating more complex MXML files which define UI components and arrange them using Flex's mx "namespace." (Note: this mx prefix isn't quite a true namespace, but a best practice for naming and utilizing Adobe's Flex UI components.)

The Google Maps API for Flash implementation does not allow the direct declaration of a Map object as a Flex UI component; instead, you will need to declare a map container object and add the map to that container dynamically upon initialization of the application. There are advantages and disadvantages to this approach. Simple MXML application that don't use Flex UI components are able to consolidate code within a custom namespace. However, if you use the Flex UI framework, you will be able to build more robust UI elements, produce complex layouts, and make use of utility objects (such as the Alert object) that are useful for debugging purposes.

To integrate a Map object into an MXML Flex application, you will need to perform the following steps:

  1. Declare a standard <mx:Application> parent element, adding Flex UI components and arranging them within a layout of your choosing.
  2. Reserve a spot for the map to display by creating a <mx:UIComponent> object and assigning it a unique id. This UI component will hold the map container. Note that you may wish to define custom width and height parameters for this object to display properly within the UI layout you have defined.
  3. Declare an initialize handler within the <mx:UIComponent> to handle the intialization event.
  4. Declare a resize handler within the <mx:UIComponent> to set the size of the map within the container element.
  5. Declare an <mx:Script> tag and place your code within this tag:
    • Declare a private Map variable, and always refer to the map using that variable, as this will no longer refer to the Map object.
    • Define the handler for the initialize event. This method should construct a new Map, add an event listener for the MAP_READY event, and add the Map as a child of the <mx:UIComponent> object.
    • Define the handler for the resize event. This method should set the size of the map within its container element.
    • Define the handler for the MapEvent.MAP_READY event and perform .

The following MXML file incorporates these changes, rewriting our "HelloWorld" as a Flex application and incorporating the Map as the child of an <mx:UIComponent> container:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="100%" height="100%">
  <mx:Panel title="Google Maps API for Flash - Simple Map" width="100%" height="100%">
    <mx:UIComponent id="mapContainer" 
        initialize="startMap(event);" 
        resize="resizeMap(event)" 
        width="100%" height="100%"/>
  </mx:Panel>
  <mx:Script>
    <![CDATA[
import flash.events.Event;
import com.google.maps.MapEvent;
import com.google.maps.Map;
import com.google.maps.MapType;
import com.google.maps.LatLng;

  private var map:Map;

  public function startMap(event:Event):void {
    map = new Map();
    map.addEventListener(MapEvent.MAP_READY, onMapReady);
    mapContainer.addChild(map);
  }
      
  public function resizeMap(event:Event):void {
    map.setSize(new Point(mapContainer.width, mapContainer.height));
  }
  
  private function onMapReady(event:MapEvent):void {
    map.setCenter(new LatLng(40.736072,-73.992062), 14, MapType.NORMAL_MAP_TYPE);
  }
    ]]>
  </mx:Script>
</mx:Application>

View example (MapSimple.html)

View MXML code (MapMarkers.mxml)

Note: to simplify the documentation, we generally define "simple" MXML files as illustrated in the previous "HelloWorld" application. Note that if you are repurposing any sample code supplied in this documentation and wish to incorporate it into a Flex UI framework, you will need to remove any existing package declarations and follow the steps illustrated above.

Latitudes and Longitudes

Now that we have a map, we need a way to refer to locations on the map. The LatLng object provides such a mechanism within the Google Maps API for Flash. You construct a LatLng object, passing its parameters in the order { latitude, longitude } as is customary in cartography:

var myGeographicCoordinates:LatLng = new LatLng(myLatitude, myLongitude);

Note: the process of turning an address into a geographic point is known as geocoding and is discussed in detail in the Google Maps API for Flash Services section.

Just as it is useful to easily refer to a geographic point, it is also useful to define the geographic bounds of an object. For example, a map displays a current "window" of the entire world within what is known as a viewport. This viewport can be defined by the rectangular points at its corners. The LatLngBounds object provides this functionality, defining a rectangular region using two LatLng objects representing the southwest and northeast corners of the bounding box, respectively.

LatLng objects have many uses within this API. The com.google.maps.overlays.Marker object takes a LatLng in its constructor, for example, and places a marker overlay on the map at the given geographic location.

The following example uses getLatLngBounds() to return the current viewport, and then randomly places 10 markers on the map within those bounds:

private function onMapReady(event:MapEvent):void {
  setCenter(new LatLng(37.4419, -122.1419), 13, MapType.NORMAL_MAP_TYPE);

  // Add 10 markers to the map at random locations
  var bounds:LatLngBounds = getLatLngBounds();
  var southWest:LatLng = bounds.getSouthWest();
  var northEast:LatLng = bounds.getNorthEast();
  var lngSpan:Number = northEast.lng() - southWest.lng();
  var latSpan:Number = northEast.lat() - southWest.lat();
  for (var i:int = 0; i < 10; i++) {
	var newLat:Number = southWest.lat() + (latSpan * Math.random());
	var newLng:Number = southWest.lng() + (lngSpan * Math.random());
    var latlng:LatLng = new LatLng(newLat, newLng);
    addOverlay(new Marker(latlng));
  }
}

View example (MapMarkers.html)

View ActionScript code (MapMarkers.as)

Note: more information on Marker objects is within the Overlays section.

Map Attributes

By default, maps show up within the Google Maps API for Flash using standard "painted" tiles. However, the Flash API also supports other maps types. The following map types are standard:

  • NORMAL_MAP_TYPE- the default view
  • SATELLITE_MAP_TYPE - showing Google Earth satellite images
  • HYBRID_MAP_TYPE - showing a mixture of normal and satellite views
  • PHYSICAL_MAP_TYPE - showing a physical relief map of the surface of the Earth
  • DEFAULT_MAP_TYPES - an array of these four types, useful for iterative processing
  • You can set the map type using the Map object's setMapType() method. For example, the following code sets the map to use the satellite view from Google Earth:

    // This code resides within your Map subclass
    
    private function onMapReady(event:MapEvent):void {
      setCenter(new LatLng(37.4419, -122.1419), 13);
      var bounds:LatLngBounds = getLatLngBounds();
      setMapType(SATELLITE_MAP_TYPE);
    }
    

    A map also contains a number of attributes that are useful to ascertain. For example, to find the dimensions of the current viewport, use the Map interface's getLatLngBounds() method to return a LatLngBounds value.

    Each map also contains a zoom level, which defines the resolution of the current view. Zoom levels between 0 (the lowest zoom level, in which the entire world can be seen on one map) to 19 (the highest zoom level, down to individual buildings) are possible within the normal maps view. Zoom levels vary depending on where in the world you're looking, as data in some parts of the globe is more defined than in others. Zoom levels up to 20 are possible within satellite view.

    You can retrieve the current zoom level in use by the map by using the Map interface's getZoom() method.

    Map Interactions

    Now that you have an implementation of the Map interface, you can interact with it. The basic map object looks and behaves a lot like the map you interact with on the Google Maps website and comes with a lot of built-in behavior. The Map interface also provides a number of configuration methods to alter the behavior of the map object itself.

    By default, map objects tend to react to user activity as they do on http://maps.google.com. You can alter this behavior with a number of utility methods, however. For example, the Map.disableDragging() method disables the ability to click and drag the map to a new location.

    You can also interact with the map programmatically. The Map interface provides a number of methods that alter the map state directly. For example, the setCenter(), panTo(), and zoomIn() methods operate on the map programatically, rather than through user interaction.

    The following example displays a map, waits two seconds, and then pans to a new center point. The panTo method centers the map at a given point. If the specified point is in the visible part of the map, then the map pans smoothly to the point; if not, the map jumps to the point.

    // Note: this example uses the best practice of using a Timer object
    private function onMapReady(event:MapEvent):void {
      setCenter(new LatLng(37.4419, -122.1419), 13, MapType.NORMAL_MAP_TYPE);		
      myTimer = new Timer(1000, 1);
      myTimer.addEventListener("timer", timedFunction);
      myTimer.start();
    }
    
    private function timedFunction(eventArgs:TimerEvent):void {
      panTo(new LatLng(37.4569, -122.1569));
    }
    

    View example (MapAnimate.html)

    View ActionScript code (MapAnimate.as)

    Info Windows

    Each map within the Google Maps API for Flash may show a single "info window" of type InfoWindow, which displays text or HTML. The info window looks a little like a comic-book word balloon; it has a content area and a tapered stem, where the tip of the stem is at a specified point on the map. You can see the info window in action by clicking a marker in Google Maps.

    The InfoWindow object has no constructor. An info window is automatically created and attached to the map when you create the map. You can't show more than one info window at a time for a given map, but you can move the info window and change its contents as needed.

    The Map object provides an openInfoWindow() method, which takes a LatLng and InfoWindowOptions used to populate the InfoWindow with content. The openInfoWindow() object appends a DisplayObject to the info window container, and the info window window tip is anchored to the given latitude and longitude.

    The following example code displays an info window anchored to the center of the map with a simple "Hello, world" message.

    private function onMapReady(event:MapEvent):void {
      setCenter(new LatLng(37.4419, -122.1419), 13, MapType.NORMAL_MAP_TYPE);
      openInfoWindow(getCenter(), new InfoWindowOptions({title: "Hello", content: "World"}));
    }
    

    View example (MapInfoWindow.html)

    View ActionScript code (MapInfoWindow.as)

    For full documentation on info windows, consult the Google Maps API for Flash Reference