Google Maps API for Flash (Deprecated)

Google Maps API for Flash Services

Services Overview

The Google Maps API for Flash will be regularly extended, adding new functionality and features that are often released on maps.google.com first. This section covers Google Maps API for Flash features which communicate with other Google services. As such, these communications are usually asynchronous and require special handling.

Geocoding

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.

The Google Maps API for Flash provides a client geocoder for geocoding addresses dynamically from user input. If instead, you wish to geocode static, known addresses, see the Geocoding Service documentation.

The Geocoding Object

Geocoding within the Google Maps API for Flash requires an asynchronous request to Google's servers. As a result, you cannot geocode an address through a simple function call. Instead, geocoding requires the following steps:

  1. Creation of a ClientGeocoder object
  2. Registration of event listeners on that object for events of type GeocodingEvent
  3. Initiation of a geocode request via the ClientGeocoder.geocode()

The request will then be sent to Google's geocoding service. Receipt of a response will then generate an event on the ClientGeocoder, and the geocoding response can be utilized.

Geocoding Events and Responses

The Google Maps API for Flash provides a GeocodingEvent for holding the response data associated with a geocoding request. This object enumerates two events:

  • GEOCODING_SUCCESS
  • GEOCODING_FAILURE

You should set up event listeners for both cases. For example:

var geocoder:ClientGeocoder = new ClientGeocoder();
geocoder.addEventListener(GeocodingEvent.GEOCODING_SUCCESS, handleGeocodingSuccess);
geocoder.addEventListener(GeocodingEvent.GEOCODING_FAILURE, handleGeocodingFailure);

In each case, the event returns information related to the geocoding request in the following properties of the GeocodingEvent itself:

  • request stores the original geocoding request as a text string.
  • requestType stores the type of geocoding request (currently "geocoding" is the only request type).
  • response.name stores the original geocoding request as a text string.
  • response.placemarks.address stores the resolved address.
  • response.placemarks.addressDetails stores address details conforming to xAL, or eXtensible Address Language, an international standard for address formatting.
  • response.placemarks.point stores the LatLng of the geocoded address.
  • status contains the status of the geocoding request and generally holds additional information for why a geocoding attempt has failed, for example.

(Note that the GeocodingResponse.placemarks property returns an array of KML Placemarks.)

Once you have set up proper handlers for the GeocodingEvent events, you can initiate a geocode request with the ClientGeocoder.geocode() method, which takes a string address as its sole argument.

In the following example, we instantiate a ClientGeocoder, add event listeners to the GeocodingEvent events, and handle successful geocodes by moving the map to the address, adding a marker, and adding an event listener to the marker that displays the address if the marker is clicked.

private function doGeocode(event:GeocodingEvent):void {
  var geocoder:ClientGeocoder = new ClientGeocoder();
  geocoder.addEventListener(GeocodingEvent.GEOCODING_SUCCESS,
      function(event:GeocodingEvent):void {
        var placemarks:Array = event.response.placemarks;
        if (placemarks.length > 0) {
          map.setCenter(placemarks[0].point);
          var marker:Marker = new Marker(placemarks[0].point);
          map.addOverlay(marker);
          marker.addEventListener(MapEvent.CLICK,
              function(event:MapEvent):void {
                marker.openInfoWindow(new InfoWindowOptions({
                  title: "Geocoded Result",
                  content: placemarks[0[]].address
                }));
              });
        }
      });
  geocoder.addEventListener(GeocodingEvent.GEOCODING_FAILURE,
        function(event:GeocodingEvent):void {
          trace("Geocoding failed");
        });
  geocoder.geocode(address.text);
}

View example (GeocodingSimple.html)

View Source (GeocodingSimple.mxml)

Driving Directions

You can add driving directions using the Google Maps API for Flash by using the Directions object. The Directions object requests results using either query strings (e.g. "New York, NY to Chicago, IL") or provided textual lat/lons (e.g. "40.712882, -73.967257 to 41.943181,-87.770677"). You may request directions between two or more points by specifying waypoints. For example, "New York, NY to Chicago, IL to San Francisco, CA" will result in directions being returned for both segments.

Initiating Directions Requests

Driving directions are requested using the asynchronous Directions.load() method. This method takes a query string and a set of optional DirectionsOptions parameters. Note that the directions object is not populated with return information immediately, as this information needs to be requested from Google's servers. For this reason, the Directions object defines the following two DirectionsEvent events which you can intercept to determine this state: DIRECTIONS_SUCCESS and DIRECTIONS_FAILURE.

Travel Modes

By default, directions are assumed to be driving directions though you may request other modes of travel by passing a constant within the DirectionsOptions object when calling the Directions.load() method. The following travel modes are supported:

  • DirectionsOptions.TRAVEL_MODE_DRIVING indicates standard driving directions using the road network
  • DirectionsOptions.TRAVEL_MODE_WALKING requests walking directions via pedestrian paths & sidewalks (where available.)

Note: Walking directions may sometimes not include clear pedestrian paths; as a result, requesting walking directions will initially display a warning message box the first time such directions are retrieved.

Handling Returned Directions

Once directions are successfully returned, the Directions object will store an encoded polyline representing the directions on the map, and a series of textual directions within textual and HTML-formatted fields. The encoded polyline can be accessed via the Directions.encodedPolyline property (and provided to other services such as the Elevation service). To display the directions on the map use Directions.createPolyline().


private function onMapReady(event:Event):void {
 
  // Create a directions object
  var dir:Directions = new Directions();
  dir.addEventListener(DirectionsEvent.DIRECTIONS_SUCCESS, onDirLoad);
  dir.addEventListener(DirectionsEvent.DIRECTIONS_FAILURE, onDirFail);
  dir.load("77 Massachusetts Avenue, Cambridge, MA to 4 Yawkey Way, Boston, MA 02215 (Fenway Park)");
}

private function onDirFail(event:DirectionsEvent):void {
  // Process failure, perhaps by showing an alert
}

private function onDirLoad(event:DirectionsEvent):void {
  var dir:Directions = event.directions;
                
  map.clearOverlays();
  map.addOverlay(dir.createPolyline());
}

View example (DirectionsSimple.html)

View Source (DirectionsSimple.mxml)

Routes and Steps

Textual and HTML-formatted directions are returned within a series of one or more Route objects, each consisting of a segment specified in the original query. Each route in turn consists of one or more Step objects, which contain the turn-by-turn directions. You can retrieve the routes using the Directions.getRoute(i:Number) method, where the passed number refers to the segment of the returned directions. Steps within a route can be retrieved using the Route.getStep(i:Number) method.

Route objects store the number of steps (of type Step) for that route, the starting and ending geocode for that route, and other computed information such as distance, duration, and exact lat/lon of the endpoint (which may be different than the ending geocode if the geocode does not lie on a road segment). Each Step object as well contains the description for that text (e.g. "Merge onto US-101 S via the ramp to San Jose") plus computed information including the distance, duration, and exact lat/lon.

You may use the textual information returned by the Directions object to display turn-by-turn textual descriptions within any DisplayObject. In the following example, we display turn-by-turn directions within an <mx:Text> object. The sample code below shows how to extract route and step information from a Directions object.

private var map:Map;
private var dir:Directions;
private var turnCounter:uint = 0;

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);
}

private function onDirFail(event:DirectionsEvent):void {
  Alert.show("Status: " + event.directions.status);
  step.htmlText = "";
}

private function onDirLoad(event:DirectionsEvent):void {
  var dir:Directions = event.directions;       
  var startMarker:Marker;
  var endMarker:Marker;
        
  map.clearOverlays();
  map.addOverlay(dir.createPolyline());
  map.setZoom(map.getBoundsZoomLevel(dir.bounds));
  map.setCenter(dir.bounds.getCenter());
  
  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}}));
  map.addOverlay(startMarker);
  map.addOverlay(endMarker);
}

private function processTurnByTurn():void  {
  
  var stepText:String;
  var stepMarker:Marker;
  turnCounter++;
  
  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()}));
    map.addOverlay(stepMarker);
    step.htmlText = "Step " + turnCounter + ": " + stepText;  
  } else {
    getTurnByTurnDirections.enabled = false;
    step.htmlText = "Arrive at " + to.text + " : " + dir.getRoute(0).summaryHtml;
  }  
}

View example (DirectionsAdvanced.html)

View ActionScript code (DirectionsAdvanced.mxml)

For full documentation of the various objects, methods and events in the Directions API package, consult the API Reference.

Elevation

The Elevation service provides elevation data for locations on the surface of the earth, including depth locations on the ocean floor (which return negative values). In those cases where Google does not possess exact elevation measurements at the precise location you request, the service will interpolate and return an averaged value using the four nearest locations.

The Elevation object provides you with a simple interface to query locations on the earth for elevation data. Additionally, you may request sampled elevation data along paths, allowing you to calculate the equidistant elevation changes along routes. The Elevation object communicates with the Google Maps API Elevation Service which receives elevation requests and returns elevation data.

Note that these requests are rate-limited to discourage abuse of the service. If instead you wish to calculate elevations for static, known locations, see the Elevation API documentation.

With the Elevation service, you can develop hiking applications, mobile positioning applications, or low resolution surveying applications.

Elevation Requests

Accessing the Elevation service is asynchronous, since the Google Maps API for Flash needs to make a call to an external server. The Elevation class provides several methods for requesting elevation for locations or along a path, but none of these methods return a result. Instead, the Maps API for Flash provides events which you can monitor upon completion of the service request:

  • ElevationEvent.ELEVATION_FAILURE indicates that the Elevation service could not process the request. Evaluate the event's status property for an indication of the failure's cause.
  • ElevationEvent.ELEVATION_SUCCESS indicates that the Elevation service successfully processed the request. The returned elevations are located within the event's elevations array.

The following code illustrates how to set up these event listeners:

private var elevator:Elevation;

elevator.addEventListener(ElevationEvent.ELEVATION_SUCCESS, showElevation);
elevator.addEventListener(ElevationEvent.ELEVATION_FAILURE, onElevationFail);

private function onElevationFail(event:ElevationEvent):void {
  // Process failure, perhaps by showing an alert
}

private function showElevation(event:ElevationEvent):void {
  // Process elevation data
}

You may request elevation data in two ways:

  • Requests for separate, discrete locations using the loadElevationForLocations() method, which is passed a list of one or more LatLng objects.
  • Requests for elevation on a series of connected points along a path using the loadElevationAlongPath() method, which is passed an ordered set of path vertices as a series of LatLng objects. When requesting elevations along paths, you must also pass a parameter indicating how many samples you wish to take along that path.

Both methods dispatch a request to the Elevation service and return void. Before invoking either of these methods, you must set up an event listener for ElevationEvents.

Note: The Maps API for Flash also provides two convenience methods similar to the above methods (loadElevationForEncodedLocations() and loadElevationAlongEncodedPath()) if you have a set of locations within an encoded polyline, such as those returned from a Directions request. (See Handling Returned Directions for information on accessing this encoded polyline.)

Location Elevation Requests

To request elevation data for a single location, or a set of discrete locations, call loadElevationForLocations(), passing this method an array of LatLngs.

You may pass any number of multiple coordinates within an array, as long as you don't exceed the service quotas. Note that when passing multiple coordinates, the accuracy of any returned data may be of lower resolution than when requesting data for a single coordinate.

Sampled Path Elevation Requests

You may also request elevation data along a path using loadElevationAlongPath(), passing a set of two or more ordered LatLng objects that define a path and a number specifying the number of sample points along that path for which to return elevation data.

As with positional requests, the path parameter specifies a set of latitude and longitude values. Unlike a positional request, however, the path specifies an ordered set of vertices. Rather than return elevation data at the vertices, path requests are sampled along the length of the path, where each sample is equidistant from each other (inclusive of the endpoints).

Elevation Responses

For each valid request, the Elevation service will return an ElevationResponse object within the ElevationEvent's locations property. Additionally, the event will contain an ElevationStatus object within the event's status property.

Elevation Statuses

Each elevation event returns an ElevationStatus code within its event properties. This status code is of type ServiceStatusand generally contains one of the following values:

  • GEO_SUCCESS indicating the service request was successful
  • GEO_BAD_REQUEST indicating the service request was malformed
  • GEO_TOO_MANY_QUERIES indicating that the requestor has exceeded quota
  • GEO_REQUEST_DENIED indicating the service did not complete the request, likely because of an invalid parameter
  • GEO_UNKNOWN_ERROR indicating an unknown error

You should check the event's status code when listening for ElevationEvent.ELEVATION_FAILURE.

Elevation Results

Upon success, the locations argument of the ElevationEvent will contain an array of ElevationResponse objects. These objects contain the following elements:

  • A location element (containing a LatLng object) of the position for which elevation data is being computed. Note that for path requests, the set of location elements will contain the sampled points along the path.
  • An elevation element indicating the elevation of the location in meters.

The following code translates a click on a map into an elevation request using the Location Elevation Request:

import com.google.maps.MapMouseEvent;
import com.google.maps.LatLng;
import com.google.maps.MapEvent;
import com.google.maps.Map;
import com.google.maps.MapType;
import com.google.maps.InfoWindowOptions;
import com.google.maps.services.*;

private var elevator:Elevation;
private var denali:LatLng = new LatLng(63.333333, -150.5);

private function onMapReady(event:MapEvent):void {

  map.setCenter(denali, 8, MapType.PHYSICAL_MAP_TYPE);

  elevator = new Elevation();

  map.addEventListener(MapMouseEvent.CLICK, getElevation);

  elevator.addEventListener(ElevationEvent.ELEVATION_SUCCESS, showElevation);
  elevator.addEventListener(ElevationEvent.ELEVATION_FAILURE, onElevationFail); 
}

private function getElevation(event:MapMouseEvent):void {
  var locationArray:Array = new Array();
  locationArray[0] = event.latLng;

  elevator.loadElevationForLocations(locationArray);
}

private function onElevationFail(event:ElevationEvent):void {
  // Process failure, perhaps by showing an alert
}

private function showElevation(event:ElevationEvent):void {
  var elevationArray:Array = event.elevations;

  map.openInfoWindow(
    elevationArray[0].location,
    new InfoWindowOptions({
        content: "Elevation: " + elevationArray[0].elevation + " meters"}));
}

View example (ElevationSimple.html)

View Source (ElevationSimple.mxml)

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.