Flash CS3 API Quickstart Guide




Contents

  1. Introduction

  2. Advantage API 5.2.0 Libraries


  3. Mapping


  4. Geocoding, Routing and Searching




I. Introduction

Welcome to Advantage API 5.2.0 for Flash CS3!

The goal of this document is to familiarize developers with the basics of the Flash API and TileMap Toolkit.

Other available resources include the Flash API Reference, the XML reference Guide, the Flash API code samples contained in this guide, and the Advantage API Forums.

This document assumes the developer has a basic knowledge of Flash CS3, has a copy of Flash CS3, and has an understanding of ActionScript 3.

A trial version of Flash CS3 is available from Adobe's website.




II. Advantage API 5.2.0 Libraries


Obtaining the AAPI Flash CS3 Libraries

From the Technical Resource Center (TRC), click the ActionScript link within the Downloads section.

This will download a zip file containing the required Flash/ActionScript libraries.

Extract the libraries from the CS3 subdirectory, noting their extracted location.


Installing the AAPI Flash CS3 Libraries

Copy the extracted libraries to the User Interface directory within the Adobe Flash CS3 installation directory.

For a typical Windows installation of CS3, this would be the directory shown below.

C:\Program Files\Adobe\Adobe Flash CS3\en\Configuration\Components\User Interface

(Note: Within the Adobe Flash CS3 IDE, use the "Window >> Components" menu options to enable the Components panel.)




III. Mapping

Generating a Simple Map

This sample details how to create a simple map.

(Note: In an effort to keep the sample simple, no scaling functionality has been applied to this sample.)

  1. Open the Flash CS3 IDE.
  2. From the menu bar, select "File >> New >> Flash File (ActionScript 3.0)"
  3. From the Components toolbox, click and drag the MapquestTileMap component to the stage.
  4. Click the Parameters tab relating to the MapquestTileMap component, and enter the values shown below.
  5. From the menu bar, select "File >> Save", and save the file as SimpleMap.
  6. From the menu bar, select "File >> Export >> Export Movie...", and save the file as SimpleMap.
  7. Run the application by browsing to the exported movie and double-clicking the SimpleMap.swf file.


Adding Controls to a Map

This sample details how to add controls to a map to allow the map to be manipulated by users.

(Note: In an effort to keep the sample simple, no scaling functionality has been applied to this sample.)

There are four different map controls available in the MapQuest Flash CS3 API:

The Flash CS3 IDE should be opened displaying the SimpleMap.fla file to perform the steps below.

  1. Save the SimpleMap.fla file as ControlsMap.fla.
  2. Click the Parameters tab relating to the MapquestTileMap component, and enter the values shown below.
  3. From the Components toolbox, click and drag the LargeZoomControl component to the stage.
  4. Click the Parameters tab relating to the LargeZoomControl component, and enter the values shown below.
  5. From the Components toolbox, click and drag the ViewControl component to the stage.
  6. Click the Parameters tab relating to the ViewControl component, and enter the values shown below.
  7. From the menu bar, select "File >> Save", and save the file as ControlsMap.
  8. From the menu bar, select "File >> Export >> Export Movie...", and save the file as ControlsMap.
  9. Run the application by browsing to the exported movie and double-clicking the ControlsMap.swf file.


Centering a Map

This sample details how to center a map programatically.

The Flash CS3 IDE should be opened displaying the ControlsMap.fla file to perform the steps below.

  1. Save the ControlsMap.fla file as CenterMap.fla.
  2. Click the Parameters tab relating to the MapquestTileMap component, and enter the value shown below.
  3. From the Components toolbox, click and drag a button to the bottom center stage.
  4. Click the Parameters tab relating to the Button component, and enter the values shown below.
  5. From the File menu select New and then ActionScript File from the resulting dialog box. Click OK.
  6. Enter code below to import the required resources, assign and create the button event listener and handle resizing.


  7. package {

    import flash.display.Sprite;
    import flash.display.Stage;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import com.mapquest.*;
    import com.mapquest.tilemap.*;

    public class CenterMap extends Sprite {

    /**
    * Constructor
    */

    public function CenterMap():void {

    // Set Stage Properties
    this.stage.scaleMode = StageScaleMode.NO_SCALE;
    this.stage.align=StageAlign.TOP_LEFT;

    // Handle Resize event
    this.stage.addEventListener(Event.RESIZE, this.onStageResize);

    //create an even listener for the button click mouse event
    myButton.addEventListener(MouseEvent.CLICK, onButtonClick);

    // Set Initial size
    onStageResize(null);

    }

    /**
    * Handle Button Click
    */

    private function onButtonClick(event:MouseEvent):void {

    var newCenter:PointLL = new PointLL(40.0446, -76.4131);
    myMap.setCenter(newCenter);

    }

    /**
    * Handle Map Sizing
    */

    private function onStageResize(evt:Event):void {

    myMap.setSize(new Size(this.stage.stageWidth, this.stage.stageHeight - 50));
    myButton.x = (this.stage.stageWidth / 2) - (myButton.width/2);
    myButton.y = myMap.height + 10;

    }

    } // End Class

    } // End Package

  8. Save the file containing the code as CenterMap.as in the same folder as the .fla file.
  9. Click the tab containing the CenterMap.fla file.
  10. From the file menu select Publish Settings, click on the Flash tab and then the Settings... button
  11. Enter CenterMap in the document class field and click OK
  12. From the menu bar, select "File >> Export >> Export Movie..."
  13. Run the application by browsing to the exported movie and double-clicking the CenterMap.swf file.
  14. Click on the Set Center button to see the map recenter on the LatLng data specified in the code.


Adding Points of Interest(POIs) to a Map

This Sample will build on the previous sample.  In addtion to re-centering the map when the button is clicked, a POI for the city of New York will be added to the map.

The Flash CS3 IDE should be opened displaying the CenterMap.fla file to perform the steps below.

  1. Save the CenterMap.fla file as AddPOI.fla.
  2. Change the label on the button from Set Center to New York.
  3. Save the file containing the class code as AddPOI.as
  4. Click the tab containing the AddPOI.fla file.
  5. From the file menu select Publish Settings, click on the Flash tab and then the Settings... button
  6. Enter AddPOI in the document class field and click OK
  7. Add the import directive for the Poi class to the class code in the section with the other import statements.
  8. The code in the onButtonClick function should be replaced with the code below. This code will do the following:

  9. The actionscript code below represents the changes to the previous example.
    //import the required classes
    import com.mapquest.tilemap.pois.*;
    /**
    * Handle Button Click
    */

    private function onButtonClick(event:MouseEvent):void {

    // Create lat/lng point for NYC
    var nycLL:PointLL = new PointLL(40.720409,-73.994637);

    // Create Poi
    var myPoi:Poi = new Poi(nycLL);
    myPoi.setInfoTitle("New York, New York");
    myPoi.setInfoContent("The city that never sleeps");
    myPoi.setKey("A1");

    // Add Poi to Map.
    myMap.addPoi(myPoi);
    myMap.setCenter(nycLL);
    }


  10. In the AddPOI.as file, rename the class definition and the constructor from CenterMap to AddPOI.
  11. Click the AddPOI.fla tab.
  12. From the menu bar, select "File >> Export >> Export Movie..."
  13. Run the application by browsing to the exported movie and double-clicking the AddPOI.swf file.
  14. Click on the New York button to see the map recenter on the "Big Apple".

Using a Custom POI Icons

This Sample will build on the previous sample.  The POI created for New York will utilize a custom icon rather than the default icon.

The Flash CS3 IDE should be opened displaying the AddPOI.fla file to perform the steps below.

  1. Save the AddPOI.fla file as CustomIcon.fla.
  2. Change the label on the button from New York to Custom Icon.
  3. Save the file containing the class code as CustomIcon.as
  4. Click the CustomIcon.fla tab
  5. From the file menu select Publish Settings, click on the Flash tab and then the Settings... button
  6. Enter CustomIcon in the document class field and click OK
  7. Create a private variable, inside the class definition, to hold the NYC POI.
  8. The code below replaces the constructor and the onButtonClick code from the previous example, and does the following

  9. private var nycPoi:Poi;

    /**
    * Constructor
    */

    public function CustomIcon():void {

    // Set Stage Properties
    this.stage.scaleMode = StageScaleMode.NO_SCALE;
    this.stage.align=StageAlign.TOP_LEFT;

    // Handle Map Sizing
    this.stage.addEventListener(Event.RESIZE, this.onStageResize);

    // Create lat/lng point for NYC
    var nycLL:PointLL = new PointLL(40.720409,-73.994637);

    // Create Poi
    nycPoi= new Poi(nycLL);
    nycPoi.setInfoTitle("New York, New York");
    nycPoi.setInfoContent("The city that never sleeps, That's why it looks that way in the morning");
    nycPoi.setKey("A1");
    myMap.addPoi(nycPoi);
    myMap.setCenter(nycLL);

    // Handle Resize event
    this.stage.addEventListener(Event.RESIZE, this.onStageResize);

    // Hanlde Button Click
    myButton.addEventListener(MouseEvent.CLICK, onButtonClick);

    // Set Initial size
    onStageResize(null);
    }

    /**
    * Handle Button Click
    */

    private function onButtonClick(event:MouseEvent):void {

    var nycIcon:ImageMapIcon = new ImageMapIcon();
    nycIcon.setImageURL("http://www.yoursite.com/cs3/apple.jpg", 32, 32);
    nycPoi.setIcon(nycIcon);
    }

  10. From the menu bar, select "File >> Export >> Export Movie..."
  11. Run the application by browsing to the exported movie and double-clicking the CustomIcon.swf file.
  12. Click on the Custom Icon button to see the Icon change from the default Icon to the image you selected.



IV. Geocoding, Routing, and Searching

Geocoding

This sample utilizes the MapQuest Geocode server to retreive geocode data for an address.

  1. Open the Flash CS3 IDE.
  2. From the menu bar, select "File >> New >> Flash File (ActionScript 3.0)"
  3. From the Components toolbox, click and drag the Advantage API component to the stage.
  4. From the Components toolbox, click and drag a label to the stage, and set its parameters as shown below.
  5. From the Components toolbox, click and drag a TextInput to the stage, and set its parameters as shown below.
  6. Repeat steps 4-7 for state, zip and country.
  7. From the Components toolbox, click and drag a button to the stage.
  8. Click the Parameters tab relating to the Button component, and enter the values shown below.
  9. From the Components toolbox, click and drag a TextArea to the stage, and enter the values shown below.
  10. Save newly created flash file as Geocode.fla
  11. From the File menu select New and then ActionScript File from the resulting dialog box. Click OK.
  12. Enter code below into the window that is opened.

  13. package {

    //import the required classes
    import com.mapquest.*;
    import flash.display.Sprite;
    import flash.events.MouseEvent;

    public class Geocode extends Sprite {

    //create and set required variable to execute the geocode process
    private var serverName:String = "geocode.access.mapquest.com";
    private var serverPath:String = "mq";
    private var serverPort:int = 80;
    private var clientId:String = "[Your Client ID]";
    private var password:String = "[Your Password]";
    /**
    * Constructor
    */

    public function Geocode():void {

    // Add listener for button click
    myButton.addEventListener(MouseEvent.CLICK, onButtonClick);

    }

    /**
    * Handle Button Click
    */

    private function onButtonClick(event:MouseEvent):void {

    var address:Address = new Address();
    address.setCity(txtCity.text);
    address.setState(txtState.text);
    address.setPostalCode(txtZip.text);
    address.setCountry(txtCountry.text);

    // Setup server object for call.
    var exec:Exec = new Exec(serverName, serverPath, serverPort);
    exec.setClientId(clientId);
    exec.setPassword(password);

    // Add a listener to be called when geocode completes
    exec.addEventListener(Exec.TRANS_TYPE_GEOCODE, onGeocode);

    // Add a listener to the exec object. To handle the Geocode Error.
    exec.addEventListener(Exec.EVENT_DO_TRANSACTION_ERROR, onExecError);
    //call the geocode function of the exec object and give it the address object to be geocoded
    exec.geocode(address);

    }

    /**
    * Handle successful call to geocode service
    */

    private function onGeocode(evt:ExecResultEvent):void {

    //retreive the location collection from the event object.
    var lc:LocationCollection = LocationCollection(evt.resultData);

    //get the first geoaddress result out of the collection
    var geoAddr:GeoAddress = GeoAddress(lc.get(0));

    //build a nice string to show in the TextArea.
    var str:String = "Lat: "+geoAddr.getLatLng().lat+" Lng: "+geoAddr.getLatLng().lng+" Resultcode: "+geoAddr.getResultCode()+"\n";
    myTextArea.text="Geocode Results\n";
    myTextArea.text += str;

    }

    /**
    * Geocode Error - Handle errors.
    */

    private function onExecError(e:ExecFaultEvent):void {

    trace("Error retrieving data from the server. \n\nDid you set your Client Id and/or Password?", "Server Communication Error:");

    }

    } // End Class

    } // End Package

  14. Replace the instances of "Your Client ID" and "Your Password" with the your account information.
  15. Save the file containing the above code as Geocode.as in the same folder as the .fla file.
  16. Click the Geocode.fla tab.
  17. From the file menu select Publish Settings, click on the Flash tab and then the Settings... button
  18. Enter Geocode in the document class field and click OK
  19. From the menu bar, select "File >> Export >> Export Movie..."
  20. Run the application by browsing to the exported movie and double-clicking the Goecode.swf file.
  21. Enter an address and click the Geocode Address Button

 

Geocode and Map

This sample will build on the previous sample. This sample utilizes the MapQuest Geocode servers to retreive geocode data for an address and places a POI on a map.

  1. Save the Geocode.fla file as GeocodeAndMap.fla.
  2. Save the Geocode.as file GeocodeAndMap.as
  3. From the Components toolbox, click and drag a tileMap to the stage.
  4. Click the Parameters tab relating to the TileMap component, and enter the values shown below.
  5. Save newly created flash file as GeocodeAndMap.fla
  6. Enter code below GeocodeAndMap.as file, overwriting the exisitng code.

  7. package {

    //import the required classes
    import flash.display.Sprite;
    import flash.display.StageScaleMode;
    import flash.display.StageAlign;
    import flash.events.MouseEvent;
    import com.mapquest.*;
    import com.mapquest.tilemap.pois.*;

    public class GeocodeAndMap extends Sprite {

    //create and set required variable to execute the geocode process
    private var serverName:String = "geocode.access.mapquest.com";
    private var serverPath:String = "mq";
    private var serverPort:int = 80;
    private var clientId:String = "[Your Client ID]";
    private var password:String = "[Your Password]";

    /**
    * Constructor
    */

    public function GeocodeAndMap():void {

    // Set Stage Properties
    this.stage.scaleMode = StageScaleMode.NO_SCALE;
    this.stage.align=StageAlign.TOP_LEFT;

    // Add listener for button click
    myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
    }

    /**
    * Handle button click
    */

    private function onButtonClick(e:MouseEvent):void {

    var address:Address = new Address();
    address.setCity(txtCity.text);
    address.setState(txtState.text);
    address.setPostalCode(txtZip.text);
    address.setCountry(txtCountry.text);

    // Setup server object for call.
    var exec:Exec = new Exec(serverName, serverPath, serverPort);
    exec.setClientId(clientId);
    exec.setPassword(password);

    // Add a listener to be called when geocode completes
    exec.addEventListener(Exec.TRANS_TYPE_GEOCODE, onGeocode);

    // Add a listener to the exec object. To handle the Geocode Error.
    exec.addEventListener(Exec.EVENT_DO_TRANSACTION_ERROR, onExecError);

    //call the geocode function of the exec object and give it the address object to be geocoded
    exec.geocode(address);
    }

    /**
    * Handle successful call to geocode service
    */

    private function onGeocode(evt:ExecResultEvent):void {

    //retreive the location collection from the event object.
    var lc:LocationCollection = LocationCollection(evt.resultData);

    //get the first geoaddress result out of the collection
    var geoAddr:GeoAddress = GeoAddress(lc.get(0));

    //build a nice string to show in the TextArea.
    var str:String = "Lat: "+geoAddr.getLatLng().lat+" Lng: "+geoAddr.getLatLng().lng+" Resultcode: "+geoAddr.getResultCode()+"\n";

    myTextArea.text="Geocode Results\n";
    myTextArea.text += str;

    // Create a POI for the address.
    var poi:Poi = new Poi(geoAddr.getLatLng());
    poi.setInfoTitle(geoAddr.getStreet());
    poi.setInfoContent(geoAddr.getResultCode());

    // Place the POI on the map and recenter
    myMap.addPoi(poi);
    myMap.setCenter(poi.getLatLng(),7);
    }

    /**
    * Geocode Error - Handle errors.
    */

    private function onExecError(e:ExecFaultEvent):void {

    trace("Error retrieving data from the server. \n\nDid you set your Client Id and/or Password?", "Server Communication Error:");
    }

    } // End Class

    } // End Package

  8. Enter your Client ID and Password in the appropriate places in the GeocodeAndMap.as file.
  9. Click the GeocodeAndMap.fla tab.
  10. From the file menu select Publish Settings, click on the Flash tab and then the Settings... button
  11. Enter GeocodeAndMap in the document class field and click OK
  12. From the menu bar, select "File >> Export >> Export Movie..."
  13. Run the application by browsing to the exported movie and double-clicking the GeocodeAndMap.swf file.
  14. Enter an address and click the Geocode Address Button

 

Geocoding Multiple Addresses

This sample utilizes the MapQuest Geocode servers to retreive geocode data for two addresses.

  1. Open the Flash CS3 IDE.
  2. From the menu bar, select "File >> New >> Flash File (ActionScript 3.0)"
  3. From the Components toolbox, click and drag an Advantage API component to the stage.
  4. From the Components toolbox, click and drag a label to the stage, and enter its parameters as shown below.
  5. From the Components toolbox, click and drag a TextInput to the stage, and enter ts parameters as shown below.
  6. Repeat steps 4-7 for city, state, zip and country.
  7. Repeat steps 4-7 again for street, city, state, zip and country, replacing the 1 at the end of the instance name with a 2.
  8. From the Components toolbox, click and drag a button to the stage.
  9. Click the Parameters tab relating to the Button component, and enter the values shown below.
  10. From the Components toolbox, click and drag a TextArea to the stage, and give it an instance name of txtResults.
  11. Save newly created flash file as BatchGeocode.fla
  12. From the File menu select New and then ActionScript File from the resulting dialog box. Click OK.
  13. Enter code below into the window that is opened.

  14. package {

    //import the required classes
    import flash.display.Sprite;
    import flash.display.StageScaleMode;
    import flash.display.StageAlign;
    import flash.events.MouseEvent;
    import com.mapquest.*;

    public class BatchGeocode extends Sprite {
    //create and set required variable to execute the geocode process
    private var serverName:String = "geocode.access.mapquest.com";
    private var serverPath:String = "mq";
    private var serverPort:int = 80;
    private var clientId:String = "[Your Client ID]";
    private var password:String = "[Your Password]";

    /**
    * Constructor
    */

    public function BatchGeocode():void {

    // Set Stage Properties
    this.stage.scaleMode = StageScaleMode.NO_SCALE;
    this.stage.align=StageAlign.TOP_LEFT;

    // Add listener for button click
    myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
    }

    /**
    * Handle button click
    */

    public function onButtonClick(evt:MouseEvent):void {

    // Create an empty location collection to hold the addresses that
    var lc:LocationCollection = new LocationCollection();

    // Create an empty address object.
    var address1:Address = new Address();

    //populate the address object with the information from the form
    address1.setStreet(this.txtStreet1.text);
    address1.setCity(this.txtCity1.text);
    address1.setState(this.txtState1.text);
    address1.setPostalCode(this.txtZip1.text);
    address1.setCountry(this.txtCountry1.text);

    // Add the address to the location collection created above
    lc.add(address1);

    //populate the address object with the information from the form
    var address2:Address = new Address();
    address2.setStreet(this.txtStreet2.text);
    address2.setCity(this.txtCity2.text);
    address2.setState(this.txtState2.text);
    address2.setPostalCode(this.txtZip2.text);
    address2.setCountry(this.txtCountry2.text);

    // Add the address to the location collection created above
    lc.add(address2);

    // Setup server object for call.
    var exec:Exec = new Exec(serverName, serverPath, serverPort);
    exec.setClientId(clientId);
    exec.setPassword(password);

    // Add a listener to be called when batch geocode completes
    exec.addEventListener(Exec.TRANS_TYPE_BATCH_GEOCODE, onBatchGeocode);

    // Add a listener to the exec object. To handle the Geocode response - Error.
    exec.addEventListener(Exec.EVENT_DO_TRANSACTION_ERROR, onExecError);

    // call the batch geocode function of the exec object. Passing it the location collection
    exec.batchGeocode(lc);
    }

    /**
    * Handle successful call to batchGeocode service
    */

    private function onBatchGeocode(evt:ExecResultEvent):void {
    var str:String = "";

    // Get the locationCollectionCollection
    var lcc:LocationCollectionCollection = LocationCollectionCollection(ExecResultEvent(evt).resultData);

    // Loop through all the locationCollections in my collectionCollection
    for (var i:int=0; i < lcc.getSize(); i++){
    // Get the 1st for each location collection.
    var geoAddr:GeoAddress = LocationCollection(lcc.getAt(i)).getAt(0);

    // Build a nice string to display the data
    str += "Lat: "+geoAddr.getLatLng().lat+ " Lng: " +
    geoAddr.getLatLng().lng+" Resultcode: "+geoAddr.getResultCode() + "\n";
    }

    // update results.
    this.txtResults.text += str;
    }

    /**
    * BatchGeocode Error - Handle errors.
    */

    private function onExecError(e:ExecFaultEvent):void {
    trace("Error retrieving data from the server. \n\nDid you set your Client Id and/or Password?", "Server Communication Error:");
    }

    } // End Class

    } // End Package

  15. Save the file containing the above code as BatchGeocode.as in the same folder as the .fla file.
  16. Click the BatchGeocode.fla tab.
  17. From the file menu select Publish Settings, click on the Flash tab and then the Settings... button
  18. Enter BatchGeocode in the document class field and click OK
  19. From the menu bar, select "File >> Export >> Export Movie..."
  20. Run the application by browsing to the exported movie and double-clicking the BatchGoecode.swf file.
  21. Enter addresses and click the Geocode Addresses Button

 

Calculate Route

This sample will utilize the previous sample and the MapQuest Geocoding and Routing servers to calculate a route between two addresses.

  1. Save the BatchGeocode.fla file as DoRoute.fla.
  2. Save the BatchGeocode.as file as DoRoute.as.
  3. Click the Parameters tab relating to the Button component, and enter the values shown below.
  4. From the Components toolbox, click and drag a DataGrid to the stage, and give it an instance name of myDataGrid.
  5. Replace the code in the DoRoute.as file with the code shown below.

  6. package {

    import fl.controls.DataGrid;
    import flash.display.*;
    import flash.events.MouseEvent;
    import com.mapquest.*;

    public class DoRoute extends Sprite {

    // Server for geocoding.
    private var geoCodeServerName:String = "geocode.access.mapquest.com";
    private var geoCodeServerPath:String = "mq";
    private var geoCodeServerPort:int = 80;

    // Server for routing.
    private var routeServerName:String = "route.access.mapquest.com";
    private var routeServerPath:String = "mq";
    private var routeServerPort:int = 80;

    // Client Id and password
    private var clientId:String = "[Your Client ID]";
    private var password:String = "[Your Password]";

    // Exec server object
    private var exec:Exec;

    /**
    * Constructor
    */

    public function DoRoute():void {
    // Set Stage Properties
    this.stage.scaleMode = StageScaleMode.NO_SCALE;
    this.stage.align=StageAlign.TOP_LEFT;

    // Add Listener for button.
    myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
    }

    /**
    * Handle button click
    */

    public function onButtonClick(e:MouseEvent):void {

    // Create an empty location collection to hold the addresses.
    var lc:LocationCollection = new LocationCollection();

    // Create an empty address object.
    var address1:Address = new Address();

    //populate the address object with the information from the form
    address1.setStreet(this.txtStreet1.text);
    address1.setCity(this.txtCity1.text);
    address1.setState(this.txtState1.text);
    address1.setPostalCode(this.txtZip1.text);
    address1.setCountry(this.txtCountry1.text);

    // Add the address to the location collection created above
    lc.add(address1);

    //populate the address object with the information from the form
    var address2:Address = new Address();
    address2.setStreet(this.txtStreet2.text);
    address2.setCity(this.txtCity2.text);
    address2.setState(this.txtState2.text);
    address2.setPostalCode(this.txtZip2.text);
    address2.setCountry(this.txtCountry2.text);

    // Add the address to the location collection created above
    lc.add(address2);

    // Set up connection for geocode server
    exec = new Exec(geoCodeServerName, geoCodeServerPath, geoCodeServerPort);
    exec.setClientId(clientId);
    exec.setPassword(password);

    // Add a listener to be called when batch geocode completes
    exec.addEventListener(Exec.TRANS_TYPE_BATCH_GEOCODE, onBatchGeocode);

    // Add a listener to the exec object. To handle the Geocode response - Error.
    exec.addEventListener(Exec.EVENT_DO_TRANSACTION_ERROR, onBatchGeocodeError);

    // Geocode all addresses involved.
    exec.batchGeocode(lc);
    }

    /**
    * Handle successful response to BatchGeocode service call
    */

    private function onBatchGeocode(evt:ExecResultEvent):void {
    var lcc:LocationCollectionCollection = LocationCollectionCollection(evt.resultData);
    var lc:LocationCollection = new LocationCollection();

    // Extract the geocoded address from the collection of location collections
    for (var i:int=0; i < lcc.getSize(); i++) {
    lc.add(GeoAddress(LocationCollection(lcc.get(i)).get(0)));
    }

    /*
    Take the goecoded addresses and calculate the route.
    */

    // Set up connection for route server
    exec = new Exec(routeServerName, routeServerPath, routeServerPort);
    exec.setClientId(clientId);
    exec.setPassword(password);

    // Add Listeners for route calculation
    exec.addEventListener(Exec.TRANS_TYPE_DOROUTE, onDoRoute);
    exec.addEventListener(Exec.EVENT_DO_TRANSACTION_ERROR, onRouteCalcError);

    // Create an empty RouteOptions object;
    var routeOptions:RouteOptions = new RouteOptions();

    // Make the call
    exec.doRoute(lc, routeOptions, null);
    }

    /**
    * Handle successful response to DoRoute service call
    */

    private function onDoRoute(evt:ExecResultEvent):void {
    var rr:RouteResults = RouteResults(evt.resultData);
    var treks:TrekRouteCollection = rr.getTrekRoutes();
    var maneuvers:ManeuverCollection = TrekRoute(treks.get(0)).getManeuvers();

    // Populate grid with results
    myDataGrid.rowCount = maneuvers.getSize();
    myDataGrid.columns = ["Route Instructions", "Distance (miles)", "Time (mins)"];
    var oS:String=new String();
    for (var i:int = 0; i < maneuvers.getSize(); i++) {
    var maneuver:Maneuver = Maneuver(maneuvers.get(i));
    var d:String= (Math.round(maneuver.getDistance() * 10) / 10 ).toString();
    var t:String= (Math.round((maneuver.getTime()/60) * 10) / 10 ).toString();
    var ro:Object = { "Route Instructions":maneuver.getNarrative(),"Distance (miles)":d,"Time (mins)":t };
    myDataGrid.addItem(ro);
    }
    }

    /**
    * BatchGeocode Error - Handle errors.
    */

    private function onBatchGeocodeError(e:ExecFaultEvent):void {
    trace("Error retrieving data from the server. \n\nDid you set your Client Id and/or Password?", "Server Communication Error:");
    }

    /**
    * Route Calculation Error - Handle errors.
    */

    private function onRouteCalcError(e:ExecFaultEvent):void {
    trace("Error retrieving data from the server", "Error:");
    }

    } // End Class

    } // End Package

  7. Replace the instances of "Your ClientID" and "Your Password", in the DoRoute.as file, with the proper information from your account.
  8. Save the file containing the above code as DoRoute.as in the same folder as the .fla file.
  9. Click the DoRoute.fla tab.
  10. From the file menu select Publish Settings, click on the Flash tab and then the Settings... button
  11. Enter DoRoute in the document class field and click OK
  12. From the menu bar, select "File >> Export >> Export Movie..."
  13. Run the application by browsing to the exported movie and double-clicking the DoRoute.swf file.
  14. Enter addresses and click the Calculate Route Button

 

Display Route

This sample will utilize the previous sample and the MapQuest Geocoding, Routing and Mapping servers to calculate a route between two addresses and display it as an ovelay on a map.

  1. Save the DoRoute.fla file as OverlayRouteMap.fla.
  2. Select the DataGrid component in the OverlayRouteMap.fla file and delete it.
  3. Drag a Tilemap component onto the stage.
  4. Click the Parameters tab relating to the TileMap component, and enter the values shown below.
  5. Save the DoRoute.as file as OverlayRouteMap.as.
  6. Replace the code in the OverlayRouteMap.as file with the code below.

  7. package {

    //import the required classes
    import flash.display.Stage;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import fl.controls.DataGrid;
    import flash.display.*;
    import flash.events.MouseEvent;
    import com.mapquest.*;
    import com.mapquest.tilemap.overlays.*;

    public class OverlayRouteMap extends Sprite {
    // Server for geocoding.
    private var geoCodeServerName:String = "geocode.access.mapquest.com";
    private var geoCodeServerPath:String = "mq";
    private var geoCodeServerPort:int = 80;

    // Server for Routing
    private var routeServerName:String = "route.access.mapquest.com";
    private var routeServerPath:String = "mq";
    private var routeServerPort:int = 80;

    // Client Id and password
    private var clientId:String = "[Your Client ID]";
    private var password:String = "[Your Password]";

    // Exec server object
    private var exec:Exec;

    /**
    * Constructor
    */

    public function OverlayRouteMap():void {
    // Set Stage Properties
    this.stage.scaleMode = StageScaleMode.NO_SCALE;
    this.stage.align=StageAlign.TOP_LEFT;

    // Add Listener for button.
    myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
    }

    /**
    * Handle button click
    */

    public function onButtonClick(e:MouseEvent):void {
    // Create an empty location collection to hold the addresses that
    var lc:LocationCollection = new LocationCollection();

    // Create an empty address object.
    var address1:Address = new Address();

    //populate the address object with the information from the form
    address1.setStreet(this.txtStreet1.text);
    address1.setCity(this.txtCity1.text);
    address1.setState(this.txtState1.text);
    address1.setPostalCode(this.txtZip1.text);
    address1.setCountry(this.txtCountry1.text);

    // Add the address to the location collection created above
    lc.add(address1);

    //populate the address object with the information from the form
    var address2:Address = new Address();
    address2.setStreet(this.txtStreet2.text);
    address2.setCity(this.txtCity2.text);
    address2.setState(this.txtState2.text);
    address2.setPostalCode(this.txtZip2.text);
    address2.setCountry(this.txtCountry2.text);

    // Add the address to the location collection created above
    lc.add(address2);

    // Set up connection for geocode server
    exec = new Exec(geoCodeServerName, geoCodeServerPath, geoCodeServerPort);
    exec.setClientId(clientId);
    exec.setPassword(password);

    // Add a listener to be called when batch geocode completes
    exec.addEventListener(Exec.TRANS_TYPE_BATCH_GEOCODE, onBatchGeocode);

    // Add a listener to the exec object. To handle the Geocode response - Error.
    exec.addEventListener(Exec.EVENT_DO_TRANSACTION_ERROR, onBatchGeocodeError);

    // Geocode all addresses involved.
    exec.batchGeocode(lc);
    }

    /**
    * Handle successful response to BatchGeocode service call
    */

    private function onBatchGeocode(evt:ExecResultEvent):void {
    //Get the location collection collection from the event.
    var lcc:LocationCollectionCollection = LocationCollectionCollection(evt.resultData);

    // Create a LocationCollection for geocoded addresses.
    var lc:LocationCollection = new LocationCollection();

    // Get the geocoded addresses from the location collections
    for (var i:int=0; i < lcc.getSize(); i++) {
    lc.add(GeoAddress(LocationCollection(lcc.get(i)).get(0)));
    }

    // Create an exec object this time pointing the routing server.
    var exec:Exec = new Exec(routeServerName, routeServerPath, routeServerPort);
    exec.setClientId(clientId);
    exec.setPassword(password);

    // Create an empty route options object
    var routeOptions:RouteOptions = new RouteOptions();

    // Set the maxShapePoints property to 10000. Just to be safe.
    routeOptions.setMaxShapePointsPerManeuver(10000);

    // Add listeners to receive the results of thie call.
    exec.addEventListener(Exec.TRANS_TYPE_DOROUTE, onDoRoute);
    exec.addEventListener(Exec.EVENT_DO_TRANSACTION_ERROR, onRouteCalcError);

    // Make the call
    exec.doRoute(lc, routeOptions, null);
    }

    /**
    * Handle successful response to DoRoute service call
    */

    private function onDoRoute(evt:ExecResultEvent):void {
    // Extract the RouteResults object from the event data.
    var rr:RouteResults = RouteResults(evt.resultData);

    // Get the shape points from the routeResults object
    var shapes:IPointLLCollection = rr.getShapePoints();

    // Get rid of previous overlays
    myMap.removeAllOverlays();

    // If a route has been calculated then create an overlay and place it on the map
    if (shapes.getSize() != 0 ) {
    // Create a line overlay and set it's display properties
    var lo:LineOverlay = new LineOverlay();
    lo.setBorderWidth(10);
    lo.setColor(0x0000ff);
    lo.setColorAlpha(.4);
    lo.setShapePoints(shapes);

    // Add the line overlay to the map
    myMap.addOverlay(lo);

    // set zoom to the center of the route.
    myMap.zoomToRect(new RectLL(shapes.getPointLL(0), rr.getShapePoints().getPointLL(shapes.getSize()-1)));
    }
    }

    /**
    * BatchGeocode Error - Handle errors.
    */

    private function onBatchGeocodeError(e:ExecFaultEvent):void {
    trace("Error retrieving data from the server. \n\nDid you set your Client Id and/or Password?", "Server Communication Error:");
    }

    /**
    * Handle error getting route
    */

    private function onRouteCalcError(e:ExecFaultEvent):void {
    trace("Error retrieving data from the server", "Error:");
    }

    } // End Class

    } // End Package

  8. Replace the Client ID and Password fields in the code above with the appropriate values from your account.
  9. Click the tab containing the OverlayRouteMap.fla file.
  10. From the file menu select Publish Settings, click on the Flash tab and then the Settings... button
  11. Enter OverlayRouteMap in the document class field and click OK
  12. From the menu bar, select "File >> Export >> Export Movie..."
  13. Run the application by browsing to the exported movie and double-clicking the OverlayRouteMap.swf file.
  14. Enter addresses and click the Calculate Route Button

 

Displaying Search Results on a Map

This sample will utilize the Geocoding sample (from earlier in this guide), and the MapQuest Geocoding, Spatial Searching, and Mapping servers to display search results on a map.

  1. Open the Geocode.as file and save it as SearchAndMap.as.
  2. Open the Geocode.fla file and save it as SearchAndMap.fla.
  3. Select the text area on the stage and delete it.
  4. From the Components toolbox, click and drag a label to the stage, and assign the parameters shown below.
  5. From the Components toolbox, click and drag a TextInput to the stage, and assign the parameters shown below.
  6. From the Components toolbox, click and drag a label to the stage, and assign the parameters shown below.
  7. From the Components toolbox, click and drag a ComboBox to the stage, and assign the parameters shown below.
  8. From the Components toolbox, click and drag a label to the stage, and assign the parameters shown below.
  9. From the Components toolbox, click and drag a TextInput to the stage, and assign the parameters shown below.
  10. Click the "Geocode Address" button on the stage, and change its label to the value shown below.
  11. From the Components toolbox, click and drag a tileMap to the stage.
  12. Click the Parameters tab relating to the TileMap component, and enter the values shown below.
  13. Replace the code in the SearchAndMap.as file with the code shown below.

  14. package {

    import flash.display.Stage;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import com.mapquest.*;
    import com.mapquest.tilemap.controls.LargeZoomControl;
    import com.mapquest.tilemap.pois.*;
    import fl.data.DataProvider;
    import flash.display.*;
    import flash.events.MouseEvent;

    public class SearchAndMap extends Sprite {
    // Server for geocoding.
    private var geocodeServerName:String = "geocode.access.mapquest.com";
    private var geocodeServerPort:int = 80;
    private var geocodeServerPath:String = "mq";

    // Server for search calculation.
    private var searchServerName:String = "spatial.access.mapquest.com";
    private var searchServerPort:int = 80;
    private var searchServerPath:String = "mq";

    // Client Id and password
    private var clientId:String = "[Your Client ID]";
    private var password:String = "[Your Password]";

    // Geocoded address
    private var geocodedAddress:GeoAddress;

    /**
    * Constructor
    */

    public function SearchAndMap():void {
    // Set Stage Properties
    this.stage.scaleMode = StageScaleMode.NO_SCALE;
    this.stage.align=StageAlign.TOP_LEFT;

    // Populate combo box
    var distanceUnits:DataProvider = new DataProvider()
    distanceUnits.addItem( {label:"Miles", data:Constants.DISTANCEUNITS_MILES} );
    distanceUnits.addItem( {label:"Kilometers", data:Constants.DISTANCEUNITS_KILOMETERS} );
    distanceUnitsCombo.dataProvider = distanceUnits;

    // Add listener for button click
    myButton.addEventListener(MouseEvent.CLICK, onSearchClick);

    // Add Zoom control to map
    myMap.addControl( new LargeZoomControl());
    }

    /**
    * Call Search service when SearchButton is clicked.
    */

    private function onSearchClick(e:MouseEvent):void {
    // Geocode address.
    var address:Address = new Address();

    // populate the address object with the information from the form
    //address.setStreet(this.txtStreet.text);
    address.setCity(this.txtCity.text);
    address.setState(this.txtState.text);
    address.setPostalCode(this.txtZip.text);
    address.setCountry(this.txtCountry.text);

    // Create an exec object for the geocode call
    var exec:Exec = new Exec(geocodeServerName, geocodeServerPath, geocodeServerPort);
    exec.setClientId(clientId);
    exec.setPassword(password);

    // Add Listeners for Geocode call
    exec.addEventListener(Exec.TRANS_TYPE_GEOCODE, onGeocodeAddress);
    exec.addEventListener(Exec.EVENT_DO_TRANSACTION_ERROR, onGeocodeError);

    //call the geocode function of the exec object - give it the address object to be geocoded
    exec.geocode(address);
    }

    /**
    * Handle successful response to Geocode service call
    */

    private function onGeocodeAddress(evt:ExecResultEvent):void {
    //Get the 1st geoaddress result out of the collection
    var lc:LocationCollection = LocationCollection(evt.resultData);
    geocodedAddress = GeoAddress(lc.get(0));

    // Create an exec object for the Search Call
    var exec:Exec = new Exec(searchServerName, searchServerPath, searchServerPort);
    exec.setClientId(clientId);
    exec.setPassword(password);

    // Add listener for the search call.
    exec.addEventListener(Exec.TRANS_TYPE_SEARCH, onSearch);
    exec.addEventListener(Exec.EVENT_DO_TRANSACTION_ERROR, onSearchError);

    // Create objects required for search parameters
    var distanceUnits:DistanceUnits = new DistanceUnits(distanceUnitsCombo.selectedItem["data"]);
    var searchCriteria:RadiusSearchCriteria = new RadiusSearchCriteria();

    // Set the center of the search to the address entered.
    searchCriteria.setCenter(geocodedAddress.getLatLng());

    // Set Maximum matches
    searchCriteria.setMaxMatches(int(Number(txtMaxResults.text)));

    // Set the distance units value
    searchCriteria.setRadius(Number(txtRadius.text), distanceUnits);

    // Create a query object.
    var dbLayerQueryCollection:DBLayerQueryCollection = new DBLayerQueryCollection();
    var dbLayerQuery:DBLayerQuery = new DBLayerQuery();
    dbLayerQuery.setDBLayerName("MQA.test");
    dbLayerQueryCollection.add(dbLayerQuery);

    // call the search function of the exec object
    exec.search(searchCriteria, "", dbLayerQueryCollection);
    }

    /**
    * Handle successful response from the Search service call.
    */

    private function onSearch(evt:ExecResultEvent):void {
    // Clear All Pois
    myMap.removeAllPois();

    // Get the feature collection from the event.
    var fc:FeatureCollection = FeatureCollection(evt.resultData);

    // Get each feature (which is a poi) from the collection and add it to the map.
    for ( var i:int = 0; i < fc.getSize(); i++ ) {
    var pointFeature:PointFeature = PointFeature(fc.get(i));

    // Create a POI object and set it's location.
    var poi:Poi = new Poi(pointFeature.getCenterLatLng());

    // Set rollover and popup text.
    poi.setInfoTitle(pointFeature.getName());
    poi.setInfoContent(pointFeature.getCenterLatLng().lat + ' by ' +
    pointFeature.getCenterLatLng().lng + '\n Distance: ' +
    pointFeature.getDistance());
    poi.setKey(pointFeature.getKey());

    // Add the Poi to the map.
    myMap.addPoi(poi);
    }

    //Add the search origin
    poi = new Poi(geocodedAddress.getLatLng());
    poi.setInfoTitle(geocodedAddress.getStreet() + ' ' + geocodedAddress.getCity());
    poi.setInfoContent(geocodedAddress.getResultCode());
    poi.setKey('Origin');
    myMap.addPoi(poi);

    //Best-Fit the map to the results
    myMap.bestFit();
    }

    /**
    * Geocode Error - Handle error from geocode call.
    */

    private function onGeocodeError(e:ExecFaultEvent):void {
    trace("Error retrieving data from the server. \n\nDid you set your Client Id and/or Password?", "Server Communication Error:");
    }

    /**
    * Search Error - Handle error from search call.
    */

    private function onSearchError(e:ExecFaultEvent):void {
    trace("Error performing search. \n\nCheck server names.");
    }

    } // End Class

    } // End Package

  15. Replace the Client ID and Password in the above code block with eh proper information for your account.
  16. Click the tab containing the SearchAndMap.fla file.
  17. From the file menu select Publish Settings, click on the Flash tab and then the Settings... button
  18. Enter SearchAndMap in the document class field and click OK
  19. From the menu bar, select "File >> Export >> Export Movie..."
  20. Run the application by browsing to the exported movie and double-clicking the SearchAndMap.swf file.
  21. Enter addresses and click the Calculate Route Button