
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.
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.
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.)
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.)
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.
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.
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
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.
//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);
}
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.
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);
}
This sample utilizes the MapQuest Geocode server to retreive geocode data for an address.
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
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.
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
This sample utilizes the MapQuest Geocode servers to retreive geocode data for two addresses.
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
This sample will utilize the previous sample and the MapQuest Geocoding and Routing servers to calculate a route between two addresses.
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
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.
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
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.
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