Notes about the sample code in this article:
- The examples in the article are full copy-and-paste code excerpts. While I encourage you to add your own elements, I wanted to provide you with as much of a head start as possible.
- To implement all the code examples, you can simply add them into a basic MXML file. Certain elements will be written in <mx:Script> tags like event handling and other elements will be called from Flex 2 components via click events etc.
The Basics: Architecture and Setup
Let's start at the very beginning (a very good place to start).
Overview of the architecture
- Look at the examples folder in the AS3 Library distribution you downloaded and installed (if you haven't yet, refer to the link in the "What You Need" section above.) In examples/traffic and examples/pipes, you will notice a swf file named as2map.swf. This file contains the AS2 Yahoo! Maps component. You shouldn't have to touch this file; however, if you need to, the source file is in the source/as2 directory, named as2map.fla. If you make any changes, make sure you update the compile path, so that the updated swf overwrites the swf file with the same name in your applications root directory.
- Inside the source folder, there are two subdirectories, as2 and as3. Both of these ActionScript-versioned directories contain separate classes, but share the same namespace. Again, in most cases you won't have to make any changes, though we encourage you to expand any of the classes with whatever functionality you deem necessary for your application.
- Some of the code lives on the first frame of the as2map.fla. Normally, I don't like having any code on the timeline (other than using an #include directive), in this case I had no choice. In order to access features and events inside the compiled as2 component I had to use the full class path (i.e. com.yahoo.maps.api.flash.YahooMap.EVENT_ZOOM_START), and since these paths don't exist in my class structure, the compiler produced errors.
- Both the AS2 and AS3 class paths have some similarities. You will notice com.yahoo.webapis.maps.utils.ExternalInterfaceBuffer exists in both class paths. This is the file that both AVM's communicate through. Since the AS2 and AS3 portions of this application are running in separate AVM's, you need not worry about collisions.
- Lastly, the example MXML files we will create will end up in the root of the source/as3/ folder.
Let's setup the application:
Make sure that you've followed the instructions on how to set up the Yahoo! AS3 Libraries.
Next, we need to add in the Yahoo! namespace to the mx:Application tag so that the tag looks like this:
- <mx:Application
- xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:yahoo="com.yahoo.webapis.maps.*"
- layout="absolute">
Next, we'll need to set a few constants that are needed to enable seamless communication between the two AVM's. The first constant that I called SWFDOMID is a String and has to have the same value as the object/embed id/name attribute used within the HTML file that houses this application. This constant is used to send method calls and events through the Flash Player's ExternalInterface. The ExternalInterface uses Javascript as its method of communication, and the Javascript needs to know what to target in the DOM of the current page. If this is a little confusing, don't worry, you won't have to deal with this. There is unfortunately no other way to access the object/embed id/name directly with ActionScript. If you were so inclined, you could use Javascript to pass in the object/embed id/name with flashvars; however, for the purpose of this example, we'll just define it as a constant.
The second constant that's needed for this project is a unique integer identifier, named UNIQUEID. This id is appended to all communication between the AVM's, to ensure there is never a collision if multiple instances of the same application are running on a machine. This is even more important if you are using the LocalConnection method, but can come in handy if two SWFs on the same page have the same object/embed id/name.
The third constant that needs to be set is your Yahoo! API Key. Let's name this one YAHOOAPIKEY. This key is needed to access any publicly available data through the Yahoo! API. If you don't have one, go here, it only takes a minute.
The last constant, named MAPSWF, will contain the filename (and path, if necessary) of the as2maps.swf file.
Now, let's set these. All of these variables will be constants, so we can bind them to the YahooMapsService. By default, the HTML page that Flex Builder generates uses the project name as the default object/embed id/name, so let's use that in our example, as we don't want to edit any HTML in this tutorial. To generate the second constant (UNIQUEID), I use the getTimer() method to produce a unique integer based on the number of milliseconds elapsed since the app started running. This is ActionScript 3, so don't forget to import mx.utils.getTimer. There exists a very small probability that that two getTimers() return the exact same millisecond value (they would have to run in very close succession), which in turn will cause communication collisions. It's not a risky gamble, but feel free to spice up the UNIQUEID generation as you see fit. Now your MXML should look something like this:
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application
- xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:yahoo="com.yahoo.webapis.maps.*"
- layout="absolute">
- <mx:Script>
- <![CDATA[
- import flash.utils.getTimer;
- private const SWFDOMID:String = "YahooAS3Maps";
- private const UNIQUEID:int = getTimer();
- private const YAHOOAPIKEY:String = "InsertYourAPIKeyHere";
- private const MAPSWF:String = "as2map.swf";
- ]]>
- </mx:Script>
- </mx:Application>
Now all that is left to set up this project is to actually load the map into our application. This is done with one simple line of MXML. Just add a yahoo:YahooMapService tag into your application, like so:
In most cases, you will want to be notified when the map is loaded and, more importantly, when it's not loaded. This can all be done using events. Now, these, and all events we will use in this project, are no ordinary events. These are events that are broadcast from the AS2 map component and passed through the Yahoo! AS3 Maps Communication Kit. Don't be afraid, you will use them as you would a regular event. That's the beauty of this Communication Kit: the work is done for you, and you can concentrate on creating the best possible Yahoo! Maps application.
Let's start by specifying a creationComplete method that gets triggered when the application has initialized. To do this we just add a creationComplete attribute to the mx:Application tag, like so:
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application
- xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:yahoo="com.yahoo.webapis.maps.*"
- layout="absolute">
- <mx:Script>
- <![CDATA[
- import flash.utils.getTimer;
- private const SWFDOMID:String = "YahooAS3Maps";
- private const UNIQUEID:int = getTimer();
- private const YAHOOAPIKEY:String = "InsertYourAPIKeyHere";
- private const MAPSWF:String = "as2map.swf";
- ]]>
- </mx:Script>
- <yahoo:YahooMapService id="swfLoader" UUID="{UNIQUEID}"
- swfDomId="{SWFDOMID}" apiId="{YAHOOAPIKEY}" mapURL = "{MAPSWF}"
- horizontalCenter="0" verticalCenter="0" width="600" height="400" />
- </mx:Application>
At this point, you can go ahead and test your project. You should see a Yahoo! map loaded into a Flex 2 application. Not impressed? All right, then it's time for fun stuff:
Loading Events: Let me know when the map is loaded
In most cases, you will want to be notified when the map is loaded and, more importantly, when it's not loaded. This can all be done using events. Now, these, and all events we will use in this project, are no ordinary events. These are events that are broadcast from the AS2 map component and passed through the Yahoo! AS3 Maps Communication Kit. Don't be afraid, you will use them as you would a regular event. That's the beauty of this Communication Kit: the work is done for you, and you can concentrate on creating the best possible Yahoo! Maps application.
Let's start by specifying a creationComplete method that gets triggered when the application has initialized. To do this we just add a creationComplete attribute to the mx:Application tag, like so:
- public function tokenLoaded(evtObject:Object) : void {
- <mx:Application
- xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:yahoo="com.yahoo.webapis.maps.*"
- layout="absolute" creationComplete="init();" >
Next, let's add the init method that gets called when the application is initialized. Inside that method, we will listen for two events, onMapLoad and onMapError. Lastly, let's set up the methods that get called when these methods get triggered. Don't forget to import the Alert control, you will notice that it's being used in the error handler. Your mx:Script content should now look like this:
- <mx:Script>
- <![CDATA[
- import flash.utils.getTimer;
- import mx.controls.Alert;
- private const SWFDOMID:String = "YahooAS3Maps";
- private const UNIQUEID:int = getTimer();
- private const YAHOOAPIKEY:String = "InsertYourAPIKeyHere";
- private const MAPSWF:String = "as2map.swf";
- private function init():void {
- myAS2Map.addEventListener('onMapLoad', onMapLoaded);
- myAS2Map.addEventListener('onMapError', onMapError);
- }
- private function onMapLoaded(ev:Object):void {
- }
- private function onMapError(errorCode:String, httpStatus:String):void {
- Alert.show(errorCode + '/n' + httpStatus, 'Load Error');
- }
- ]]>
- </mx:Script>
Now that we have an event telling us when the map is loaded, let's do something with it.
Calling Map Methods: How do I call Yahoo! Map methods?
Setting up panning:
So now that our map is loaded, and we have an event telling us that it is loaded, it's time to add some functionality to it. The map is pretty boring if you can't drag it around to see more of it. To turn on panning, we will instantiate the PanTools class and call the setPanTool method. Since we can't access any map classes until the map is loaded, let's instantiate the PanTools in our onMapLoaded method:
- private function onMapLoaded(ev:Object):void {
- var panTools:PanTool = new PanTool(myAS2Map);
- panTools.setPanTool(true);
- }
That's it (honestly, you aren't being punked)! Go ahead, test it. You can now drag to all corners of the Earth (Christopher Columbus would have a field day with this.)
What about all those other tools that are available on Yahoo! Maps:
Ah, you mean the Widgets. Fortunately, they are just as easy to setup. Let's add two of the most popular tools available in the Yahoo! Maps component. The NavigatorControl, and the SatelliteControl. The SatelliteControl allows you to toggle between three different views: Map view, Hybrid view, and everyone's favorite Satellite view. The NavigatorControl loads a slider tool that is used for zooming in and out. The NavigatorControl also includes a small interactive navigator widget that can be opened and closed at any time. These tools can be turned on or off by calling methods in the Widgets class. Just like above, let's instantiate the Widgets class in our onMapLoaded method:
- private function onMapLoaded(ev:Object):void {
- var panTools:PanTool = new PanTool(myAS2Map);
- panTools.setPanTool(true);
- var widgets:Widgets = new Widgets(myAS2Map);
- widgets.showNavigatorWidget(true);
- widgets.showSatelliteControlWidget(true);
- }
See, it really is as easy as it seems.
How about those cool overlays, can I still add those?
With such a cool, interactive feature as a Yahoo! map on your Flex site, your customers are going to be flocking to your location. To make it even easier for your customers, why not display all of the traffic problems in your area? Using overlays, this too can be done with just a few lines of code. Since we don't want our beautiful map defaced with all sorts of traffic and construction icons all the time let's give the user the ability to turn on the traffic overlay. To do this, we will add a Button component to our Flex application and launch the traffic overlay using the click event of the button. Would you believe me if I said this can be done with one line of code? Just add this one line of MXML to your application and your local traffic report is always one click away.
- <mx:Button id="trafficButton" label="Traffic Report"
- click="new Overlays(myAS2Map).showTrafficOverlay();"/>
Using inline code, you can instantiate the Overlays class and call the showTrafficOverlay() method, all in one line. Now that I proved it can be done in one line, you'll probably want to add a few more lines of code to make this more functional. A few lines of code will be used to position interface elements properly, and a few more lines will add some logic to the trafficButton. In its default state, you probably want the button to say "Show Traffic Report", and once it's clicked, you'll want it to switch to "Remove Traffic Report", and change its function accordingly. This really doesn't have anything to do with the Yahoo! AS3 Maps Communication Kit itself, but let's take a look at how to do this anyway.
First, let's position things a bit better, so the button doesn't sit on top of the map. To do this, I simply put my YahooMap and Button in a VBox container. I also moved the horizontalCenter and verticalCenter attributes from my YahooMap tag to the VBox container. Setting it up this way ensures that the button will always appear below the map, and both will always appear centered in the browser. Before I show you the code for that, let's think about that button logic. There are a couple ways it could be done. You could create another Flex state, and in that state change the label and inline click event code to remove the traffic overlay. That would be too simple, so let's do it all with ActionScript instead, this will really impress your friends and family (because, really, so far this application has been far too easy to build !)
Instead of having the traffic overlay code inline, we are giong to call a method called toggleTrafficView(). This method will keep the state of the traffic overlay and change the button text and click event to reflect the current state. Here is the code for our entire MXML file (don't forget to check out the new VBox container):
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application
- xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:yahoo="com.yahoo.webapis.maps.*"
- layout="absolute" creationComplete="init();" >
- <mx:Script>
- <![CDATA[
- import flash.utils.getTimer;
- import mx.controls.Alert;
- import com.yahoo.webapis.maps.methodgroups.*;
- private const SWFDOMID:String = "YahooAS3Maps";
- private const UNIQUEID:int = getTimer();
- private const YAHOOAPIKEY:String = "InsertYourAPIKeyHere";
- private const MAPSWF:String = "as2map.swf";
- private function init():void {
- myAS2Map.addEventListener('onMapLoad', onMapLoaded);
- myAS2Map.addEventListener('onMapError', onMapError);
- }
- private function onMapLoaded(ev:Object):void {
- var panTools:PanTool = new PanTool(myAS2Map);
- panTools.setPanTool(true);
- var widgets:Widgets = new Widgets(myAS2Map);
- widgets.showNavigatorWidget();
- widgets.showSatelliteControlWidget();
- }
- private function onMapError(errorCode:String, httpStatus:String):void {
- Alert.show(errorCode + '/n' + httpStatus, 'Load Error');
- }
- private function toggleTrafficView():void {
- var trafficVisible:Boolean = trafficButton.label == 'Show Traffic Report' ? false : true;
- if (trafficVisible) {
- trafficButton.label = 'Show Traffic Report';
- new Overlays(myAS2Map).showTrafficOverlay(false);
- } else {
- trafficButton.label = 'Hide Traffic Report';
- new Overlays(myAS2Map).showTrafficOverlay(true);
- }
- }
- ]]>
- </mx:Script>
- <mx:VBox horizontalAlign="center" horizontalCenter="0" verticalCenter="0">
- <yahoo:YahooMapService id="myAS2Map" UUID="{UNIQUEID}"
- swfDomId="{SWFDOMID}" apiId="{YAHOOAPIKEY}" mapURL="{MAPSWF}" width="600" height="400" />
- <mx:Button id="trafficButton" label="Show Traffic Report" click="toggleTrafficView();"/>
- </mx:VBox>
- </mx:Application>
And voila, "I was stuck in traffic" is no longer an acceptible excuse.
Yahoo Maps and Yahoo Pipes Mash-up
GeoRSS, can I still plot points using an RSS feed?
I am glad you asked, because the answer is - absolutely. For this example, I am going to use data from another Yahoo! property: Pipes. Yahoo! Pipes is an interactive feed aggregator and manipulator. Using Pipes, you can create feeds that are more powerful, useful and relevant and the best part is all of their data is Flash-friendly, with a wide-open crossdomain policy, so Flash developers can have fun too!In this example, I'll use a pipe (the name for a feed built in Yahoo! Pipes) I found on pipes.yahoo.com. The pipe matches schools found in Yahoo! Search with their location found in Yahoo! Local and generates a geoRSS feed. You can also limit the number of schools per type that are returned. This pipe requires two parameters, a zip code, and a maximum number of schools per type. In our example, we will use one numeric search field, a numeric stepper, and a button. Clicking the button will dynamically create the pipes URL and the returned data will be loaded onto our map which will be positioned based on the zip code. Ok, ok, enough chit-chat, let's see the code:
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application
- xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:yahoo="com.yahoo.webapis.maps.*"
- creationComplete="init()" layout="absolute" >
- <mx:Script>
- <![CDATA[
- import flash.utils.getTimer;
- import mx.controls.Alert;
- import flash.utils.setTimeout;
- import com.yahoo.webapis.maps.methodgroups.*;
- private const SWFDOMID:String = "howtoMapsAS3ExGeorssPipes";
- private const UNIQUEID:int = getTimer();
- private const YAHOOAPIKEY:String = "InsertYourAPIKeyHere";
- private const MAPSWF:String = "as2map.swf";
- private var overlays:Overlays;
- private var mapController:MapController;
- private function init():void {
- myAS2Map.addEventListener('onMapLoad', onMapLoaded);
- myAS2Map.addEventListener('onMapError', onMapError);
- }
- private function onMapLoaded(ev:Object):void {
- var panTools:PanTool = new PanTool(myAS2Map);
- panTools.setPanTool(true);
- var widgets:Widgets = new Widgets(myAS2Map);
- widgets.showNavigatorWidget();
- widgets.showSatelliteControlWidget();
- overlays = new Overlays(myAS2Map);
- mapController = new MapController(myAS2Map);
- }
- private function onMapError(errorCode:String, httpStatus:String):void {
- Alert.show(errorCode + '/n' + httpStatus, 'Load Error');
- }
- public function getHouse():void {
- var pipeURL:String = "http://pipes.yahoo.com/pipes/hPD_lmy_2xGykI16dbq02Q/run?
- numberinput1="+prox.value.toString()+"&locationinput1="
- +locationQuery.text+"&_render=rss";
- overlays.removeGeoRssOverlay();
- overlays.showGeoRssOverlay(pipeURL);
- mapController.setCenterByAddressAndZoom(locationQuery.text, 6);
- }
- ]]>
- </mx:Script>
- <mx:HBox horizontalCenter="0" verticalCenter="0" width="884">
- <mx:Panel x="195" y="210" width="251" height="254" layout="absolute"
- title="School by zip locator">
- <mx:Label text="Max number of results" x="10" y="109"/>
- <mx:Label text="per school type" x="50" y="122"/>
- <mx:Text x="10" y="12" text="Show me all the schools located in
- the entered zip code region. Enter the max number of school types you
- want to see per region (i.e. 5 means you will see a max of 5
- elementary schools, 5 high schools, etc." width="211"/>
- <mx:Label text="Zip Code: " x="86" y="148"/>
- <mx:TextInput x="149" y="146" width="69" id="locationQuery"
- text="95120" maxChars="5" restrict="0-9"/>
- <mx:NumericStepper x="149" y="114" width="69" id="prox"
- value="2" minimum="1" maximum="10" stepSize="1" enabled="true"/>
- <mx:Button id="findhouse" x="73" y="176" label="Show me the schools!"
- click="this.getHouse()" />
- </mx:Panel>
- <mx:Panel x="464" y="210" width="617" height="440" layout="absolute" id="mapPanel"
- title="Results brought to you by the good people at Yahoo! Maps and Yahoo! Pipes"
- verticalScrollPolicy="off" horizontalScrollPolicy="off">
- <yahoo:YahooMapService id="myAS2Map" UUID="{UNIQUEID}" swfDomId="{SWFDOMID}"
- apiId="{YAHOOAPIKEY}" mapURL="{MAPSWF}" width="600" height="400" />
- </mx:Panel>
- </mx:HBox>
- </mx:Application>
Well that's it for now. I hope it's enough to get you started and inspired. I plan to write another tutorial in the coming weeks showcasing some of the other functionality available in the extensive Yahoo Maps! API. For now feel free to download the Yahoo! AS3 Maps Communication Kit as it contains all of the examples in this article and other examples that use methods that weren't part of this write-up. Lastly, make sure you come back to the Yahoo! Flash Developer Center often, as we are constantly adding and updating our content.
Summary
Check out the finished products to see how easy it was to integrate Yahoo! Maps into an application.
- Traffic Overlay example
- Yahoo Pipes / Yahoo Maps School locator
- Example showcasing most of the methods available in the API (the source for this is available in the downloadable package below)
- There are other examples in the Yahoo! AS3 Maps Communication Kit download package
Where to go from here
I hope these code examples give you a great start in developing your own AS3 Yahoo! Maps applications. Make sure to submit your apps and mashups to gallery.yahoo.com/flash and be sure to check back here often for more coverage and examples of the Yahoo! AS3 Maps Communication Kit.