Yahoo! Astra 1.2 has new layout containers for Flash! (and more)

by Josh Tynjala

Grab the open source goodness known as Astra 1.2 from the Yahoo! Flash Developer Center and read all about the new 1.2 release on the Yahoo! Flash Blog. This release includes updates to the Flash components, the removal of the Flex Maps hack from the Web APIs library (use the new Yahoo! Maps AS3 API instead), and the addition of the new Astra Utilities library.

Looking over the release notes, I realize that I made loads of contributions to this release. In particular, here are some highlights:

  • Charts now support legends! This is a much needed feature that just required a bit of time to get right.

  • Some cool new additions to LineCharts. I’ll be writing a blog post highlighting some of these new features soon.

  • Layout containers should be a big help to many projects. I’ve seen time and again Flex developers doing an AS3 project and complaining that there are no layout controls available in Flash CS3. Now you’ve got HBoxPane, VBoxPane, FlowPane, TilePane, and BorderPane at your disposal.

  • A lightweight Animation class. Yeah, I know, why do we need another tween library? We probably don’t, but when I wrote it, nothing else quite fit my needs. This actually got released in 1.1 as part of the charts, but now that we’ve got a library for generic utilities, I can give it a proper moment in the spotlight.

  • The layout utility provides the core framework used by the Flash CS3 layout containers. The purpose of this library is to allow component developers to build layout containers for any component set a bit more easily. Please read the documentation on YDN if you want to learn more. I explain the layout utility in much more detail over there.

Again, grab all the new downloads from the Yahoo! Flash Developer Center. All of our releases are available under the terms of the new BSD license, so enjoy! If you have any questions, comments, bug reports, or feature requests, please post them to the ydn-flash list.

Adobe needs to improve accessibility in Flash Player

by Josh Tynjala

For the last couple of weeks, I’ve been focused entirely on understanding the accessibility capabilities of Flash Player. My goals were two-fold. First, I needed to learn as much as possible about the documented and undocumented APIs available to ActionScript (The “undocumented” link purposefully leads to a page that doesn’t exist). Second, I wanted to use my findings to create a list of feature requests so that Adobe can improve accessibility support in future versions of Flash Player.

The following list compiles, in no particular order, what I felt were the more important missing features related to Flash Player’s accessibility. After each description, I link to the relevant feature request in Adobe’s public bug database. Please vote!

  • Flash Player isn’t accessible on a Mac

    For a cross-platform runtime, it’s a little troubling to see that Flash Player on a Mac can’t communicate with a assistive technology. Mac OS X 10.4 and 10.5 both include a built-in screen reader, called VoiceOver. With two versions supported by the base Mac operating system (it’s not an addon), I sincerely hope support for VoiceOver is a priority for the upcoming Flash Player 10.

    Feature Request: Support Accessibility API on Mac OS X

  • The AccessibilityProperties class doesn’t support roles

    Adobe recommends that we use the documented class, AccessibilityProperties. This class provides a simple API for many properties used by screen readers. One property it doesn’t expose is the role of the accessible object. Everything seen by a screen reader in Flash Player is a “graphic”. I’d love to be able to specify that an object is a button or a list.

    WAI-ARIA roles are recommended for UI controls created in HTML. I think this would be a great standard for Adobe to use as a basis for Flash Player’s accessibility.

    Feature Request: Support for roles in AccessibilityProperties

  • AccessibilityProperties doesn’t expose the display list hierarchy

    This one’s a little more abstract, but the hierarchy of accessible objects on the display list isn’t made available to accessibility clients when you use AccessibilityProperties. If I make a TabBar control, I cannot specify that individual tabs are children of the TabBar.

    I can’t declare the ultimate importance of this feature because I’m not an experienced screen reader user, but I definitely noticed the difference while testing with Microsoft’s Accessibility Explorer. When viewing native Windows applications, it displays a nice tree of objects that one can navigate. In a Flash Player application, I only saw a flat list of objects. At the very least, if this hierarchy isn’t important for screen reader users, it helps a developer to organize a very complex application for debugging purposes.

    Feature Request: Support for Object Hierarchy in AccessibilityProperties

  • Some accessibility APIs in Flash Player are undocumented

    As I stated previously, Flash Player has undocumented accessibility APIs. The Flex components and the Flash CS3 components both uses the undocumented class flash.accessibility.AccessibilityImplementation. It appears this class is based on the IAccessible interface from Microsoft’s Active Accessibility (MSAA).

    Unfortunately, Adobe’s implementation for ActionScript is incomplete because it doesn’t provide all the same functionality available to developers using MSAA. Additionally, this API is obviously platform-specific, so future Mac support will likely need to be handled very differently.

    I believe that Adobe needs to do one of two things.

    1. AccessibilityImplementation should be fully documented. If Adobe wants the developer community to be able to build complete components of the same quality as the Flex framework components, we should have access to the same APIs.

    2. Alternatively, if Adobe believes that we shouldn’t be using the AccessibilityImplementation class (the reasons I stated above are good reasons why we shouldn’t use it), they should not use this API themselves. It looks unprofessional. If that’s the case, substitute a better API that will allow cross-platform development and more complex controls. This may be possible with some simple additions to the existing AccessibilityProperties class.

    Feature Request: Accessibility implementations use undocumented APIs

For more information about the limitations of Flash Player’s Accessibility features, see Niqui Merret’s blog post from last year, Accessibility in Flash bug and issue list. For information related to web accessibility and laws in various jurisdictions around the world, see Policies Relating to Web Accessibility. In time, accessibility laws will become stronger, and it’s important that Flash Player provides better support early so that developers can prepare.

Modern Flex Developer – A Video for 30onair

by Josh Tynjala

Not long ago, Adobe’s Ted Patrick introduced 30onair, a community video project promoting Adobe technologies. What a great idea, I thought, but I didn’t have any good ideas right away. Thankfully, Phillip Kerman made enough WHY videos to keep us entertained for years.

Finally, I decided to show my love of Flex with a little song. Without further ado, here’s Modern Flex Developer, a parody of Gilbert and Sullivan’s Major General’s Song.

You don’t seem to have Adobe Flash Player 9 installed. It is required to view this content!

Enjoy!

Learning ActionScript 3.0 offers the best intro to Flash development

by Josh Tynjala

Very few Flash or Flex development books get me excited. They’re all generally pretty decent, but only the rare ones1 make me want to read cover to cover. A good programming book is one that I want to share with others before I’m finished reading it. Among those great gems, I’ve recently added Learning ActionScript 3.0 by Rich Shupe and Zevan Rosser. It certainly lives up to its title.

Learning ActionScript 3.0 differs greatly when compared to other books published by O’Reilly. The most obvious difference when you see this one on the shelf will be that there’s no iconic animal drawing on the front cover. When you pick it up, and start looking through its pages, you’ll soon discover an even more surprising difference. Every page in Learning ActionScript 3.0 is printed in full color. All the code is formatted to match Flash CS3′s ActionScript editor. All the screenshots are, you guessed it, fully colorized. Unlike many other developers, we of the Flash community tend to work on projects that are highly visual. Screenshots in previous Flash and Flex books I’ve read have been greyscale and sometimes very difficult to see. Learning ActionScript 3.0 sets a new standard. The books I read in the future will lose points immediately for crappy black and white screenshots.

The visual treatment isn’t all that stands out. The authors have experience teaching “thousands of students at universities, training facilities, and conferences”. In the preface, they explain that they’ve been told time and again that no ActionScript book for beginners is truly all that good for the intended audience. They set out to try to fix that problem. In my opinion, they’ve done an excellent job crafting a book that slowly eases someone into programming ActionScript without being too overwhelming. They wait six chapters before introducing Object-Oriented Programming, and I think it works very well. The first three chapters offer the bare minimum of programming concepts and then the reader is taken into sections about how to use the Display List and the Timeline. Only then, after the reader has built a couple things, and hopefully gained some confidence, do the authors begin to introduce the complete concepts behind objects and classes. It’s a very gentle introduction with enough hands-on learning that it doesn’t get boring.

In later chapters, the authors touch a bit on text, sound, video, animation, drawing, and loading external assets like images and XML. With each topic separated into its own chapter, I get the feeling that this book will be an excellent resource for someone who might want to skip certain bits of functionality and reference it later as needed, or for a beginner that needs a refresher every once in a while. I noticed on several occasions, as I was reading, that these sections cover many of the most common questions I see in online Flash forums.

The book ends with a chapter on “Programming Design and Resources”. This chapter introduces various software development models, such as waterfall, spiral, and several agile methods. I like that this section was included because most Flash books don’t really mention larger project-scale processes that developers might want to consider following. It’s refreshing and forward thinking. After that, the reader gets a very short introduction to design patterns. Though I was impressed that they were included, I felt this section could have been bigger or omitted. With such a slow introduction to OOP earlier in the book, the sudden appearance of what many consider a very advanced topic felt out of place. Still, I think it will probably help inspire some especially-talented new developers to discover how to move to the next level, so perhaps it fits. Finally, the chapter ends with several large lists of online resources for Flash developers, including many popular blogs (sadly, not mine. haha), open source libraries, books, forums, conferences, and more. For someone new to Flash development, this section alone offers hundreds of ways to go beyond what’s in the book.

While targeted more at beginners, Learning ActionScript 3.0 serves as an excellent reference to some of the most common tasks ActionScript developers encounter daily. The transition from the very basics of Flash programming to more advanced topics is gentle, but engaging. The full color pages throughout this book separate it from everything else on the shelf, and O’Reilly couldn’t have chosen a better topic than Flash to enhance with this wonderful addition. I’m not the only person excited about this book either; Lee Brimelow, Platform Evangelist at Adobe, called it “the best ActionScript book ever written.”

1For reference, the last Flash book that got me excited was Object-Oriented ActionScript for Flash 8, which I read back in 2006 (there’s an updated version, Object Oriented ActionScript 3, if you’re interested).

Bugs and Feature Requests for JSFL

by Josh Tynjala

JSFL makes me bang my head on the desk sometimes. Don’t get me wrong, JSFL is useful. I’ve been using it for some time now to partially automate builds for Flash CS3 FLA-based components. I can create component shims, live preview SWFs, and many things of that nature which normally take a long time to do manually. Unfortunately, I can’t get everything working perfectly for a fully automated build. Here are a few problems with JSFL that have been making me extra angry:

  • library.updateItem("itemName") Crashes Flash CS3

    This works like the Update… option that’s available when you right-click on something in the library. Basically, it lets you update your symbols from a source FLA. This is useful for component examples that need an updated component symbol from the main FLA. Apparently, updateItem() worked well in Flash 8, but calling it brings the whole application down in Flash CS3. A topic about the crash on the official Flash forums includes a response from someone at Adobe that says that this bug has been fixed and will be included in the “next release”. Will this be an update to Flash CS3, or are we talking CS4?

  • Copy an Item from one FLA’s library into another FLA requires confirmation

    As a workaround to the updateItem() bug, one can add a symbol from the source FLA’s library to the stage of the destination FLA. This will replace the out-of-date symbol in the destination library, but it displays a confirmation dialog that you have to interact with manually.

    Flash CS3 LIbrary Conflict Dialog

    Several other JSFL functions have flags to let you bypass dialogs like this (such as the bPromptToSave parameter used by fl.closeAll()), but document.addItem() does not.

  • Component Live Previews cannot be set or updated with JSFL

    FLA-based components need a live preview SWF embedded in the FLA to have the component appear properly on stage when the user drags it there. As I mentioned, I can easily create that SWF with JSFL, but making my component use (or later update) that SWF is another story.

    To manually update the live preview SWF, you have to right click on the component, go into Component Definition…, click the Set.. button in the live preview section, click the Update button, click OK in one window, and then click OK in the next. There is no API to set or update it with JSFL, and all that clicking leads to long builds.

Hopefully, some of these things can be cleared up in Flash CS4 (or maybe a CS3 hotfix for that crash bug, please?). In theory, it will be possible to modify and create files using the upcoming XML/ZIP FLA file format called XFL completely outside the Flash authoring environment. It doesn’t help me now, but I rest just a little bit easier knowing that I’ll have an easy job creating builds in the future when XFL becomes available and I may no longer need most of my JSFL scripts. Adobe, want to make things just a tiny bit easier? I’d love for Flash CS4 to include a native command-line compiler to build FLA files. I already run Flash from the command line now, but I’d rather not have the whole IDE open when I don’t need any visual tools.

ActionScript Game Programming University: Fun and Educational

by Josh Tynjala

Games inspired me to become a developer. I remember having fun playing a myriad of games on consoles and my computer and thinking, “someday, I could make cool stuff like this too!” Fastforward to today, and I’m building chart and treemap visualizations, but that’s a different story…. Still a kid at heart, I was excited to take a look at Gary Rosenzweig’s ActionScript 3.0 Game Programming University. Though I took my time reading it, I found the each chapter very interesting as they each laid out very simple source code that I think even a new developer wouldn’t have trouble following.

The back of the book entices the potential reader with promises of sixteen complete games. In fact, the author’s attention to detail shines through as he lays out games from start to finish. Considering all the Flash and ActionScript books I’ve read over the years, I think I’d recommend this one just for the fact that Mr. Rosenzweig encourages proper cleanup of objects clearly and often. Ultimately, the sixteen games are very simple, and anyone hoping to have something finished by the end of the chapter can only be called naive. The fact is, a real game someone would want to release online needs a lot of content, and that’s certainly outside the scope of this book. Don’t take that as a negative, but a warning in case you think game development will be as easy as it feels while reading this book.

General programming tasks pepper the pages of each chapter without feeling dry and boring. Learning to load XML seems to happen naturally when a game needs some external data. A little E4X gets thrown in for good measure. Again, I noticed over and over, the author encourages good practices by placing common tasks (such as moving objects using physics) or pointing out that he coded something one way to account for features that could be added later (playing sounds in a single function because you might want to add volume changing and mute functionality).

The order of example games works pretty well overall. The first couple of chapters with “complete game” examples feature matching games that are a bit boring, but the interestingness quickly progresses into a shooting game, an Arkarnoid clone, an Asteroids clone, and several others. It ends up being a good mix between graphical games and more traditional quiz and word games. The final two chapters feature a 2D side-scrolling platformer and two top-view driving games.

Like I said, part of me still wants to feel cool by making a fun game that people truly enjoy. Gary Rosenzweig’s approach to teaching game development encouraged that feeling, and if I were still younger and had hours to kill on the computer, I know I’d love to play around with this book and build little games to proudly show my parents. Part of me predicts I’ll eventually sit down one lazy weekend and come up with something to proudly show my girlfriend, but she’ll probably just roll her eyes. Anyway, if you’re keen to try a little game development, whatever your age, I definitely recommend ActionScript 3.0 Game Programming University. With very clear explanations, anyone should be able to explore its examples without much effort, and like me, more experienced developers can have fun too.

360Flex Item Renderers Session Slides and Code

by Josh Tynjala

As promised, I’m making my slides and the code samples from my 360Flex Atlanta session available for download. The session was officially titled Building Components That Use Item Renderers and it covers the use of custom item renderers for existing components (like List, Tree, DataGrid) and the creation of new components that can display item renderers.

Screenshot of 360Flex Atlanta Item Renderers Slides

The following examples of MXML List item renderers were shown during the session. These examples display their source code next to the components.

Font List Item Renderer Example

Color List Item Renderer Example

To access the source code for the CheckBoxList ActionScript item renderer, head over to my blog post, Open Source Flex Components: AdvancedList and CheckBoxList. The source code for the TabBar component for Flash CS3 is available in the Yahoo! Astra Library for Flash CS3. It’s not a Flex component, but it is a good example of recycling renderers for reuse.

You can download the source code for the TreeMap component at its Google Code project. The current stable release is available on the Downloads page. For the latest “unstable” revision (which is what I showed during the session) you can go to the Source page and follow the instructions to access the source code with your favorite Subversion client.

To all who attended such an early session after a night of partying, I appreciate it. Also, if you stopped me in the halls between sessions to say you liked it, thanks a lot. I’m excited for the next 360Flex. I heard rumors that Tom and John want to head back to the Bay Area, or at least the west coast, next time.

Download Slides (PDF file)

Live From 360Flex, Day One

by Josh Tynjala

As I begin, it’s ten minutes to 8:00am. We have a half hour until the first keynote of 360Flex Atlanta starts. Attendees are streaming into a line to get their badges and the first schwag of the conference. Adobe provided AIR 1.0 t-shirts for everyone, and they’re pretty damn sweet. Doug McCune and I stole ours from Tom and John’s room at midnight last night. For my fellow attendees, I assure you that there’s more cool stuff on the way.

In case you didn’t hear it from the MXNA zombies, Flex 3.0 and AIR 1.0 have officially gone live on Adobe’s website today, February 25, 2008. Rich Tretola was telling me last night that his first post about the then-codenamed Apollo appeared on his blog in late 2006. Has it been that long? I guess it has. At MAX 2006, Flex 2 posters were hot off the presses and that version of the framework was only about six months old. Mike Chambers was chilling at a little booth in the back corner of the conference passing out red Apollo t-shirts and showing people very early builds of this new and exciting technology on his laptop.

Matt Chotin is up at the podium preparing for the keynote and chatting with Ben Forta. Up past the projector screen, you can see OMNI Hotel’s glass elevator coming down with more attendees. The keynote will be in an open area of the hotel. If I had one of the rooms with balconies on my right, I’d be relaxing up there next to one of the matching plants that each room seems to have. It would be a unique view of the whole scene that I wouldn’t be able to pass up.

I see Deepa sitting in the first row to support Matt. Should I Stay, Or Should I Go? just played for a few seconds on the speakers in front. The seats are filling up, and I’ve overheard a few folks talking around me. Not everyone realizes that AIR 1 and Flex 3 are available right now. Some people are talking about Flash on the iPhone. That subject will never go away until it becomes a reality, I think.

Matt’s laptop is finally on screen after much ado around the projector. He’s getting some websites ready to show us. The hotel’s wireless is getting pounded by geeks like me, and I’m impressed that it’s staying pretty strong. We’re about to begin.

The Keynote Begins

Matt is “wowing [us] with his awesome PowerPoint skills”.

What’s available today? AIR 1.0, Flex 3 SDK, Flex Builder 3 Standard and Pro, Blaze DS, Adobe’s Open Source websites. The Flex SDK is available in two editions. The Adobe Flex SDK is the official release supported by Adobe that includes the Flex framework and compilers. The open source Flex SDK will be considered separate with different licensing and packaging for its intended audience. More on that in a bit.

Flex Builder Professional includes charts, AdvancedDataGrid, and OLAP, along with the profiler and automated testing support. Originally, in Flex 2, this was only supported by QTP, but Matt says that several more testing frameworks (I heard Borland, IBM, and one or two others) are supported now or will be supported in the near future.

Matt says he doesn’t want to focus much on Flex 3 today. It’s been out in beta form for a long time, and we all know the details. He gives us a quick overview of the available tools, pricing, and upgrade options. Next, he mentions the iLog Elixir components with maps, charts, and more. Adobe is the official distributor of the components, and they’re available for $799.

Matt’s going to demo several AIR applications. The first is AOL’s Top 100 videos. It’s a pretty sweet looking app with a big grid of video thumbnails. The poor wireless can’t handle watching one of the videos right now, but thankfully, I can keep blogging. Ted Patrick showed it to folks at Yahoo! a month or so ago, and it’s pretty simple and cool. Now, Matt is showing a NASDAQ app with cool charts. I only caught a quick look at it. The Parleys.com application has cool transitions between views similar to Adobe Media Player. It displays video presentations and interviews from user conferences. There’s a slide view similar to Adobe Connect, and there are some awesome controls for switching between video, slides, and navigating through a recorded talk.

Now we’re looking at the Google Analytics Reporting Suite application. Google is helping the developer build the app. They were impressed with the guy’s ability to scrape the Google Analytics site and build a powerful application based on that data. I’ve heard people say that they prefer this app to the actual Google Analytics site. That’s very cool. The Allurent Desktop Connection is an e-commerce app. It has some cool features like being able to pick a color and seeing all the products in the catalog that are available in that color. You can either use a simple color picker or grab a color straight from an image. The Digimix application is a cool sequencer built on AIR. Reminds me of my old days playing with Sonic Foundry ACID and other audio apps.

Adobe Rocks the Backend

Ben Forta isn’t going to talk about ColdFusion. We’re going to look at LCDS, BlazeDS, and Flex-supported backend technologies. He’s talking about how Flash Player natively supports things like regular web services, but he’s focusing on Flash remoting for a moment. Before, using Flash remoting was pretty hard in many situations. It was easy in CF because it was supported out of the box. Now, with BlazeDS available as an open source project, Flash remoting will be far easier for developers that use other backend technologies.

What’s the difference between LCDS and BlazeDS? Both have Flash Remoting and Messaging. LCDS also has data management features like data synchronization and conflict resolution that Ben explained was a pretty useful way to ensure that multiple database transactions don’t conflict.

We’re about to see a preview version of LCDS that will go into public beta next month on Adobe Labs. LiveCycle is a J2EE app that supports many platforms. Many components for LCDS are available pre-built. I see email components, encryption components, LDAP, PDF, database queries, but there’s a huge tree of available categories. There’s an interesting visual builder for these components, and we’re taking a look at LiveCycle Workspace, the default Flex app for users to view LiveCycle data. Full source code is available for this app, and developers can build their own views of the same data.

What’s Open Source and What’s Next?

The Flex SDK source code, including compilers and the debugger, are available under the MPL. The bug database is open, of course. Daily builds of Flex can be downloaded, and the roadmap is available for the world to view. The open source SDK is available as a download with only the MPL code, if desired. This version can be used with a separate add-ons package that contains everything from the SDK that doesn’t fall under the MPL (like the debugger Flash Player). Lots of flexibilty here for the open source purists. BlazeDS reference implementations are available for Java and CF, and Adobe is working with the community to provide other implementation for technologies like PHP, ASP.NET, etc.

How will the community integration work for Flex 3? To start, Adobe engineers will be handling most of the work, but Adobe plans to let the community start to patch the framework through bug reports, and eventually, some non-Adobe folks will get commit rights to the code repository.

According to Matt, Flex 4 was recently codenamed “Gumbo”. What do they want to do in this version? Improve collaboration between designer and developer through Thermo. Accelerated development from concept to reality quickly. Improving workflow. “Horizontal platform improvements” that benefit everyone (faster compiler, for example). Finally, they want to broaden the scope of Flex to expand the range of apps that can be built with it.

We get a quick look at Flash Player 10, codenamed Astro. New AS3 text components built on a new text engine (named Vellum). Hydra, a custom pixel shader language. Simple 3D effects. They won’t replace Papervision, but they will certainly help make Papervision better. Mainly, we’re hearing the same stuff that Adobe announced at MAX. However, this is the first announcement I’ve seen publicly about the implementation of a new Vector type in ActionScript. We’ll have typed Arrays. Matt says you know you’re at a developer conference when that’s the feature that got applause over the others. You may remember the Vector class from my overview of ECMAScript 4 a couple months ago.

The keynote ends with a hilarious video put together by Matt and the Flex team. Lot’s of self-deprecating humor and friendly jabs at fellow Flex teammates. Matt shows that he’s everyone’s friend with pictures of him sporting a thumbs up and a cheesy smile with frightened Adobeans. Doug McCune’s infamous Panel border bug gets featured too. Head over to Matt’s blog to view the Flex: Behind the Scenes video.

That ends the 360Flex day one keynote. If you’ll excuse me, I need to eat something and think about taking a nap. The Adobe party is tonight, and I want to be well-rested. Plus, I have my session Building Components That Use Item Renderers at 8:30am tomorrow. Seriously, with the timezone shift added onto my complete lack of sleep, that’s just plain mean. I’ll get my revenge, Tom Ortega. You just wait.

Talking about item renderers at 360Flex Atlanta

by Josh Tynjala

I see that Jesse and Ben just pimped their own sessions for 360Flex, so I might as well jump on the bandwagon. My session is titled Building Components that use Item Renderers. It’ll be divided into two parts. The first part will involve several examples in MXML and ActionScript demonstrating how to build item renderers. Part two will feature some tips about how you can build completely custom components that use item renderers.

Abstract

Item renderers provide a powerful way for developers to completely change the way a component displays each item from a data provider. After looking at how item renderers can be used with existing components, you’ll gain an understanding of all the classes and interfaces an item renderer system needs.

From there, Josh exposes the dirty details of how to build a component that supports drop-in renderers, what properties and methods should be exposed to the developer, and how to implement renderer caching to maximize performance. Highlights include peeks into how the Flex framework uses item renderers, how to use custom item renderers with existing Flex components, and how to build a component from scratch to use item renderers.

The session takes place Tuesday morning, February 26th, at 8:30am. I’ll forgive you if that’s too early to be fully awake, but I hope you’ll stop by with coffee and a muffin to see some code. You’re registered to go to 360Flex, aren’t you? Of course you are. Don’t be the guy who misses the best Flex event of the year!

How to use the Yahoo! AS3 Maps API in Flash CS3

by Josh Tynjala

Important: As of version 0.9.3, the Yahoo! Maps API for ActionScript 3 includes a component that may be used with Flash CS3. It’s a simple MXP installer like many other Flash CS3 components. The following tutorial is obsolete.

The official release of the ActionScript 3 API for Yahoo! Maps appeared on the Yahoo! Developer Network yesterday to much fanfare. Believe me, I’m excited as you are! We on the Yahoo! Flash Platform team have been working hard to ensure Maps got into the hands of AS3 developers. You may have noticed that this first version specifically targets Flex Builder and the free Flex SDK. I assure you, Flash CS3 support is definitely on the way, but due to technical reasons and time constraints, it’s not available just yet. That said, there’s nothing wrong with a little hacking if you’re too excited to wait until we have an official component.

We’d love to let you use the same SWC file with Flex and Flash. Unfortunately, the compiler in Flash CS3 treats SWC files a little strangely. Basically, the compiler sees the classes available in your SWC file, and it will compile your code that uses those definitions, but the classes themselves aren’t included in your output SWF. When you try to view the output SWF, you’ll see one or more VerifyErrors because the classes cannot be found. Since we cannot compile directly from the SWC, another interesting possibility is to load the classes at runtime to instantiate them.

If you didn’t know, SWC files are actually special ZIP files. If you open YahooMap.swc in your favorite archive manager, you’ll discover two files. First, you’ll see catalog.xml, which specifies the available classes and some other information that may be used by compilers. Additionally, there’s a file named library.swf, and that’s the one we’re most interested in using. This SWF file contains the compiled ActionScript code for the Yahoo! Maps AS3 API. Extract that file from the SWC to your filesystem (preferrably right next to the FLA file you’ll be using).

Yahoo! Maps SWC Extraction

What we’re going to do next is load the library.swf into our Flash application. Using the ApplicationDomain class, we’ll access the classes from the SWF to instantiate a YahooMap instance in our main SWF. It’s a little cumbersome if you need many of the available classes, but it doesn’t take too much code to set up the basics.

I’m just going to put this code on the timeline for simplicity’s sake, but you may set up a class, if you prefer. First, we have the variable that will store the com.yahoo.maps.api.YahooMap instance. I typed it as Object because we don’t have a compile-time reference to the required class and Object is most flexible being dynamic. Additionally, we have our Yahoo! API Key, sometimes called an application ID, placed in a constant because it won’t change. Finally, we have variables to store the references to classes we will be retrieving from library.swf:

var map:Object;
const APP_ID:String = "Put your own Application ID here";

// classes we will be loading
var YahooMap:Class;
var YahooMapEvent:Class;
var LatLon:Class;

Let’s load library.swf using a standard flash.display.Loader.

var mapsLoader:Loader = new Loader();
mapsLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, mapsLoaderCompleteHandler);
mapsLoader.load(new URLRequest("library.swf"));

When library.swf has finished loading, the mapsLoaderCompleteHandler() event handler function will be called, and we will retrieve the required classes. Use the getDefinition() function from ApplicationDomain to load the classes and place them in the variables we set up a moment ago.

function mapsLoaderCompleteHandler(event:Event):void
{
	// of course, don't forget to remove your listeners!
	event.target.removeEventListener(Event.COMPLETE, mapsLoaderCompleteHandler);

	// save each of the classes we plan to use
	var appDomain:ApplicationDomain = event.target.applicationDomain;
	YahooMap = appDomain.getDefinition("com.yahoo.maps.api.YahooMap") as Class;
	YahooMapEvent = appDomain.getDefinition("com.yahoo.maps.api.YahooMapEvent") as Class;
	LatLon = appDomain.getDefinition("com.yahoo.maps.api.core.location.LatLon") as Class;

	// create the YahooMap instance
	this.map = new YahooMap(APP_ID, stage.stageWidth, stage.stageHeight);

	// we can call functions normally
	this.map.addPanControl();
	this.map.addZoomWidget();
	this.map.addTypeWidget();

	// using the loaded YahooMapEvent class
	this.map.addEventListener(YahooMapEvent.MAP_INITIALIZE, mapInitializeHandler);

	// cast as DisplayObject because yahooMap is typed as Object
	this.addChild(DisplayObject(this.map));
}

The mapInitializeHandler() function is called when the YahooMap is ready for interaction. We’ll set the zoom level and center on a specific latitude and longitude. As you can see, we use the LatLon class that we retrieved earlier.

// unfortunately we cannot use the YahooMapEvent type as the
// parameter because it isn't a compile-time constant.
function mapInitializeHandler(event:Event):void
{
	// once again, we can use the YahooMapEvent class here
	this.map.removeEventListener(YahooMapEvent.MAP_INITIALIZE, mapInitializeHandler);

	// sets the zoom level to a high-level city view.
	this.map.zoomLevel = 5;

	// here we use the loaded LatLon class
	this.map.centerLatLon = new LatLon(37.779160,-122.420049);
}

You’ll notice that the code itself isn’t much different than in the examples. By placing the loaded classes in a wide enough scope, we’ve made them accessible to all our functions here. For a more advanced application with extended functionality, you might consider placing the classes in a static variable somewhere so that they can be accessed globally.

To make things easy, so you don’t have to copy all my code, I’ve made my project files available (along with library.swf extracted from the SWC) in a zip. Download the YahooMaps in Flash CS3 project files. This hack will probably be short-lived, but I thought I’d share it anyway. As I mentioned before, a fully-supported Flash CS3 component can be expected in an upcoming release. Until then, happy hacking! :)

Pages: Prev 1 2 3 4 5 6 7 8 9 10 ...18 19 20 Next