Yahoo!® Maps Mashups Charles Freedman
Yahoo!® Maps Mashups
Yahoo!® Maps Mashups Charles Freedman
Yahoo!® Maps Mashups Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-0-470-09778-6 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 Library of Congress Cataloging-in-Publication Data: Freedman, Charles, 1977– Yahoo! Maps mashups / Charles Freedman. p. cm. Includes index. ISBN-13: 978-0-470-09778-6 (paper/website) ISBN-10: 0-470-09778-7 (paper/website) 1. Geographic information systems. 2. Yahoo! Maps. 3. Application program interfaces (Computer software) I. Title. G70.212.F74 2007 910.285'4678—dc22 2006038751 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Yahoo! is a registered trademark of Yahoo!, Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
To Jamie, my wife. With your unconditional love and support you inspire me to live my dreams. To my parents and grandparents. You showed me the world from all angles before I ever looked at a map.
About the Author Charles Freedman is a Senior Flash Developer for Yahoo! with a communications degree in film and television from Boston University. His development approach combines an education in multimedia with expertise and passion for building engaging and intuitive applications and content. In recent years, Charles has produced some of the most highly visible Flash platform work, leading development for Yahoo! Maps and deploying modules for the home pages of eBay, eBay China and Fidelity. Born in Boston, Charles relocated with his wife Jamie to sunny Santa Clara, California, to join Yahoo! in 2005. Still a season ticket holder, he plans many trips back East to see his beloved Red Sox win another World Series.
Credits Executive Editor
Vice President and Executive Group Publisher
Chris Webb
Richard Swadley
Senior Development Editor
Vice President and Executive Publisher
Kevin Kent
Joseph B. Wikert
Development Editor
Graphics and Production Specialists
Howard A. Jones
Carrie A. Foster Heather Ryan Alicia B. South
Technical Editor Mirek Grymuza
Quality Control Technician Production Editor
Brian H. Walls
Katharine Dvorak
Project Coordinator Copy Editor
Patrick Redmond
S. B. Kleinman
Proofreading and Indexing Editorial Manager
Techbooks
Mary Beth Wakefield
Anniversary Logo Design Production Manager Tim Tate
Richard Pacifico
Acknowledgments I have benefited from the support and encouragement of many people during the long and rewarding journey of writing this book. First let me thank the folks who make the APIs covered in the book worth writing about, the Yahoo! Maps Team. A special thanks to the product and engineering managers and developers, and particularly to Aaron King and Zach Graves. Their personal dedication to the quality and performance of the Flash APIs is represented in the spirit of this book. While more than half of this book covers Flash, a technology I am proud to consider myself a champion of, an important part covers the incredibly versatile Ajax API. Mirek Grymuza has crafted this API and technology into the widely adopted, well-engineered and admirable solution that it is. In addition to lending his valuable services as technical editor for the Ajax chapters of this book, Mirek’s influence on my appreciation and understanding of Ajax will remain long after these pages are written. Many thanks to friends and family for your patience and understanding while I took on this huge endeavor. Especially my brother Nathaniel who made sure I didn’t miss my entire first California summer. (More about that in Chapter 22.) Thanks to Rob Abbott for never letting me forget the importance of what I was writing. Also, thanks to Clint Modien for bringing the opportunity for writing the book to my attention in the first place. Thank you to the editors at Wiley for helping me along with your guidance and direction. A most endearing thank you to my wife, Jamie, who didn’t think twice when insisting that I take on this project. She knew how important this was to me. Her encouragement from the beginning allowed me to dive into this book and never look back.
Contents Acknowledgments Introduction
Chapter 1: Your Map, Your World What Is a Map API? The Four Types of Map APIs Understanding Map Technology
Common Map Features and API Tools Map and Satellite Imagery Zooming Panning Geo-coding Markers and Custom Markers Overlays Navigation
Summary
Chapter 2: Developing with Yahoo! Maps What Is a Mashup? XML REST RSS and GeoRSS Feeds
Prime Mashup Sources Flickr Upcoming.org HotJobs Weather Traffic Local Search
xi xxi
1 1 2 2
3 3 4 5 6 6 7 7
8
9 9 10 10 11
12 12 13 13 14 14 15
Yahoo! Developer Support
15
Developer Network Message Group Maps Application Gallery
15 15 16
Summary
16
Contents Chapter 3: The Ajax API
17
What the Ajax API Is Ajax in Greater Depth
17 18
Applications You Know That Use Ajax Fundamentals of JavaScript Fundamentals of CSS and DHTML
Benefits of the Ajax API Summary
Chapter 4: Get Started with the Ajax API Get an Application ID Software Requirements Integrating the Ajax API Including the API Classes Setting Initial Map Parameters
Summary
Chapter 5: Ajax API Basics Basic API Methods The YEvent Class Map Zoom Methods and Events Map Type Methods and Events Map Positioning Methods and Events
Summary
Chapter 6: Ajax API Advanced Features Working with Markers Marker Methods and Classes
18 19 23
24 25
27 27 28 29 29 31
34
35 35 36 36 40 41
46
47 47 48
Working with Tools
52
Control Methods
52
Working with Overlays Overlay Methods and Classes
Summary
Chapter 7: The Ajax Mashup Time to Mash Up The Big Idea Planning an Approach
xiv
55 55
61
63 63 63 64
Contents The Flickr API How Flickr Photos Are Geo-Tagged API Authentication API Methods Understanding JSON
Build the Mashup Code the Mashup
Enhancing the Mashup Summary
64 64 65 66 67
68 69
73 74
Chapter 8: The JS-Flash API
75
What Is the JS-Flash API?
75
Fundamentals of JavaScript Fundamentals of CSS and DHTML
Benefits of the JS-Flash API Summary
Chapter 9: Get Started with the JS-Flash API Get an Application ID Software Requirements Transitioning Between APIs Integrating the JS-Flash API Including the API Classes Setting Initial Map Parameters
Summary
Chapter 10: JS-Flash API Basics Basic API Methods Map Zoom Methods and Events Map Type Methods and Events Map Positioning Methods and Events
Summary
Chapter 11: JS-Flash API Advanced Features Working with Markers Marker Methods and Classes
Working with Tools Tool Methods and Classes
76 79
80 81
83 83 84 85 85 85 88
90
93 93 93 97 101
107
109 109 110
115 115
xv
Contents Working with Widgets Working with Overlays Overlay Methods and Classes
Summary
Chapter 12: The JS-Flash Mashup Time to Mash Up The Big Idea Planning and Approach
The Yahoo! Travel API How Travel Content Contains Location API Authentication API Methods Understanding JSON
Build the Mashup Code the Mashup
Enhancing the Mashup Summary
119 120 121
125
127 127 127 128
128 128 129 130 131
133 133
139 140
Chapter 13: The AS-Flash API
141
What Is the AS-Flash API? Flash in Greater Depth
141 142
The Flash IDE
Fundamentals of ActionScript 2 Variable Types Classes Methods Components Events
Benefits of the AS-Flash API Summary
Chapter 14: Get Started with the AS-Flash API Get an Application ID Software Requirements Downloading and Installing Components Adding the Map API Adding to the Stage Initialization Adding with ActionScript
Summary
xvi
142
145 147 148 148 149 150
150 151
153 153 154 154 155 156 159 161
164
Contents Chapter 15: AS-Flash API Basics Basic API Methods Map Set Methods Map Get Methods Component Methods
Summary
Chapter 16: AS-Flash API Advanced Features API Classes in Depth Advanced Map Objects and Methods Working with Events
Working with Widgets
165 165 165 173 180
181
183 183 184 184
189
Widget Methods Widget Classes
189 189
Working with Tools
195
Tool Methods Tool Classes
Working with Markers Marker Methods Marker Classes
Working with Overlays Overlay Methods Overlay Classes
Summary
Chapter 17: The AS-Flash Mashup Time to Mash Up The Big Idea Planning and Approach
Setting the Stage The Layout
Coding the Mashup Exploring the HotJobs Web Service Architecting the Mashup Loading the XML Parsing the XML Handling User Interaction Displaying the Data on the Map
Enhancing the Mashup Summary
195 196
201 201 202
211 212 212
222
223 223 224 224
225 225
228 229 231 231 234 237 239
241 242
xvii
Contents Chapter 18: Yahoo! Maps and Flex 2 Finding Out About Flex The History of Flex How Yahoo! Maps Works in Flex Getting Flex 2 Flex Builder 2: The Flex Authoring Tool
Fundamentals of MXML Coding with MXML and ActionScript
Benefits of Using Flex 2 and the AS-Flash API Summary
Chapter 19: Get Started with Yahoo! Maps and Flex 2 Get an Application ID Software Requirements Download and Install the AS-Flash API Create the Flash Client of the Application Adding the AS-Flash API to the Stage Adding ActionScript to the Flash Client Side
Create the MapConnector Class Coding the MapConnector Class in ActionScript
Create the Flex Client of the Application Writing the MXML
Summary
Chapter 20: Basic Methods: Flex 2 Using the AS-Flash API Basic API Methods Map Set Methods Map Get Methods
Summary
Chapter 21: Advanced Features: Flex 2 Using the AS-Flash API Advanced AS-Flash API Classes Reviewing Objects and Methods Reviewing Events
Working with Widgets Widget Methods Widget Classes
xviii
243 243 244 245 246 247
249 250
252 253
255 255 256 257 258 258 260
262 262
264 264
266
269 269 270 279
285
287 287 288 288
289 289 289
Contents Working with Tools
290
Tool Methods setActiveTool(tool) removeTool(tool) Tool Classes
290 290 290 291
Working with Markers
291
Marker Methods Marker Classes
Working with Overlays Overlay Methods Overlay Classes
Summary
Chapter 22: The Flex 2 Mashup Time to Mash Up The Big Idea Planning and Approach
The Flex Client Architect the MXML The Data The Layout Coding the Controls Handling User Interaction Completing the MXML
The Local Connection Coding the MapConnector Class
Making the Video Converting Media to Flash Video
The Flash Client Architect the ActionScript Importing the Classes Create the Local Connection Add the Event Listeners Field Map Instance Events Field Local Connection Events Completing the ActionScript
Finalize the Mashup Enhancing the Mashup Summary
291 292
298 298 299
304
305 305 305 306
307 307 307 308 309 309 310
312 312
314 314
316 316 316 316 317 317 318 318
320 321 322
xix
Contents Appendix A: API Method Comparison Chart Basic Set Methods and Classes Basic Get Methods Tools and Widgets Markers and Overlays
Appendix B: API Example and Mashup Index
xx
323 323 325 325 326
329
Ajax API Examples JavaScript Flash API Examples ActionScript Flash API Examples AS-Flash/Flex 2 API Examples
329 330 331 332
Index
335
Introduction Yahoo!® Maps Mashups provides you with all the information about map technology, the tools and features of maps, and the basic methods and advanced techniques of APIs you need as a developer to build amazing map mashups. In addition, and because of the wide array of Yahoo!’s offerings, the book details the technology each API features. The ultimate goal is for you to be able to download, install and develop mashups with one or all of the Yahoo Maps APIs.
Who This Book Is For The book will benefit readers at all levels of development experience. Those interested in Yahoo! Maps APIs and building map mashups will have at their fingertips all they need to build amazing map applications. This book covers a wide array of technologies at different levels. Many readers will find it useful and enjoyable, including: ❑
The developer new and completely open to the maps APIs and the technologies they feature
❑
Web developers looking to broaden their understanding of Web 2.0 and rich Internet application (RIA) technologies
❑
Intermediate or experienced JavaScript and Ajax or Flash and Flex 2 developers who are looking to expand their skill set into mashup development
❑
Fans of Yahoo! Maps mashups who want documentation and cut-and-paste mashup examples in their laps
While further reading is not required, you may benefit from books such as Beginning ActionScript 2.0 (Wiley Publishing, ISBN 978-0-7645-7768-0) and Professional Ajax (Wiley Publishing, ISBN 978-0-471-77778-6).
What This Book Covers Yahoo! Maps Mashups details the documentation, approach, methodology, architecture and design of the Yahoo! Maps APIs. The Yahoo! Maps APIs are some of the most powerful APIs available. With tremendous support for Ajax and Flash technologies, Yahoo! Maps’ API offerings let developers push map technology to its limits and beyond. With an unparalleled capacity for customization and integration of external data, the APIs let developers build unique mashups easily. Yahoo! Maps Mashups explores each API flavor, guiding the developer through the simple, yet comprehensive sets of API calls. With three APIs to cover, any developer certainly has a choice of technologies. This book guides you through the capabilities of each technology through its respective API. As each
Introduction API is introduced, the benefits of that API, its architecture, and the technology used to implement it are reviewed. Each API distinctively features its own Web 2.0 or rich Internet application technology. The book uses each API’s uniqueness to explore its basic and advanced set of API methods, classes, and events. With each API comes an analysis of the technology that drives it. The principal technologies that make up the book, Ajax and Flash, are often very segregated and seldom does a developer cross the line between the two. The book makes little comparison between the technologies, rather pointing out the benefits each one gives the developer through the efficiency and feature capability of the API it drives.
How This Book Is Structured With the goal of helping the developer build his or her own map mashup with the Yahoo! Maps API of their choice, Chapter 1: “Your Map, Your World” defines an API and how it differs from a regular application. It highlights common features and tools offered by existing map applications, pointing out that Yahoo! has made many of these features available to the developers for implementation in their own mashups. Chapter 2: “Developing with Yahoo! Maps” introduces you to the concept of a mashup. It covers some of the many data sources that can be loaded into the map API, including exciting brands such as Flickr and Upcoming.org. It also explores mashing up with data from HotJobs and Yahoo! Local. Also in the chapter is coverage of Yahoo’s support through its developer network and message groups; these will give confidence to the soon-to-be map API developer. Chapter 3: “The Ajax API” begins a comfortable and comprehensive pattern, launching an examination of each of the three Yahoo! Maps APIs and implementations. Starting with the Ajax API, Chapter 3 defines the Ajax technology, DHTML and JavaScript. It also discusses the benefits of the Ajax API. Chapter 4: “Get Started with the Ajax API” covers the steps you need to execute to get started with the Ajax API, including the free and simple process of getting an application ID, software requirements and key steps to prepare code for API integration. Chapter 5: “Ajax API Basics” immerses you in the API, covering the basic calls and fundamentals of the API, including changing the map view type, setting the zoom level and setting the address. This chapter features rich, cut-and-paste-able code samples intended to get the user running with simple API examples. Exploring the more advanced techniques of the API, Chapter 6: “Ajax API Advanced Features” features descriptions and code samples of API methods like adding custom markers and custom objects and panning and zooming programmatically. Once you’ve gone through the basic and advanced aspects of the API, Chapter 7: “The Ajax Mashup” features a project for the Ajax API. The mashup combines data from the Flickr JSON API with the Ajax Map API. With the comprehensive code of the application, you will have all you need to deploy your first map mashup.
xxii
Introduction The rest of the book follows a similar pattern to the review of the Ajax API. The chapters cover the benefits and core technologies of each API. Since the implementation of the Ajax API and JavaScript-Flash API are similar, Chapter 8: “The JS-Flash API” points out how to easily adapt from Ajax to the JavaScriptFlash API. This provides a further transition between the single Ajax API flavor and the Flash APIs. Both Flash APIs and the ActionScript-Flash API/Flex 2 implementation parts begin with an introduction chapter (Chapter 8: “The JS-Flash API,” Chapter 13: “The AS-Flash API” and Chapter 18: “Yahoo! Maps and Flex 2”) followed by a chapter (Chapters 9, 14 and 19) on getting started. The “basics” chapters (Chapters 10, 15 and 20) for each Flash API, along with the advanced chapters (Chapters 11, 16 and 21) once again immerse you in that API. Each discussion of each API concludes with a chapter (Chapter 12: “The JS-Flash Mashup,” Chapter 17: “The AS-Flash Mashup” and Chapter 22: “The Flex 2 Mashup”) featuring a comprehensive project. Each mashup is designed to push the limits of the API it is built with, giving you all the tools you need to recreate such an application and put yourself, as a developer, well on your way to building your own amazing mashups.
What You Need to Use This Book To install and run much of the examples and software mentioned in this book you will need the following: ❑
Windows XP or Mac OS X
❑
Internet Explorer 6.0 or higher (Windows), Mozilla 1.5 or higher (all platforms), or Safari 1.2 or higher (Mac OS)
❑
The JS-Flash API and AS-Flash APIs require Flash Player 7 or higher and will play on future releases. The Flex 2 solution requires Flash Player 9 and will play on future releases
❑
Various code-authoring tools, detailed throughout the book. Trial download instructions are covered as needed
Conventions To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.
Try It Out The Try It Out is an exercise you should work through, following the text in the book.
1. 2. 3.
They usually consist of a set of steps. Each step has a number. Follow the steps with your copy of the database.
xxiii
Introduction How It Works After each Try It Out, the code you’ve used will be explained in detail.
Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.
Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this. As for styles in the text: ❑
We highlight new terms and important words when we introduce them
❑
We show keyboard strokes like this: Ctrl + A
❑
We show file names, URLs and code within the text like so: maps.getZoomLevel().
❑
We present code in two different ways:
In code examples we highlight new and important code with a gray background. The gray highlighting is not used for code that’s less important in the present context, or that has been shown before.
Source Code As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the “Download Code” link on the book’s detail page to obtain all the source code for the book. Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-0-470-09778-6. Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this and all other Wrox books.
Errata We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration and at the same time you will be helping us provide even higher quality information.
xxiv
Introduction To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the “Book Errata” link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml. If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport .shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.
p2p.wrox.com For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts and your fellow readers are present on these forums. At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:
1. 2. 3.
Go to p2p.wrox.com and click the Register link.
4.
You will receive an e-mail with information describing how to verify your account and complete the joining process.
Read the terms of use and click Agree. Complete the required information to join as well as any optional information you wish to provide and click Submit.
You can read messages in the forums without joining P2P, but in order to post your own messages you must join. Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.
mashupexper ts.com A special companion site is being maintained by the author and the development community at www.mashupexperts.com. Examples, mashups and source code throughout the book can be found
xxv
Introduction here. As new versions of the APIs covered in this book are released, mashupexperts.com will post timely examples, mashups and posts to assist you with your usage and enjoyment of this book. Appendix B, “API Example and Mashup Index” provides an inventory of example files that can be found at www.mashupexperts.com. The site is set up to field support questions and answers, once again supported by the author and development community.
xxvi
1 Your Map, Your World “When I have the map, I will be free, and the world will be different, because I have understanding.” — Time Bandits, 1981 This chapter discusses ❑
What map APIs are
❑
What map applications can do
❑
The core principles of map technology, including map projection and scaling
❑
Why Yahoo! offers three types of map APIs
What Is a Map API? As an avid web user, you probably use map applications all the time, even daily. Map applications, like the Yahoo! Maps beta, enable millions of users to find locations by address, get driving directions and search for businesses based on location. These useful applications have become some of the most popular and dependable sets of functionality on the web. As a web developer, you have probably worked with APIs. API stands for application programming interface. It is an interface for programming an application, a collection of functions to program against. An API, like the Yahoo! Maps API, is designed to expose key functionality as functions that, when simply added to your application, enable you to access and control the features of the application. In the coming chapters you will see that many API calls, like setCenterByAddress(), setZoomLevel() and setMapViewType(), are named after their respective functionalities. A map API enables you to develop with much of the useful and dynamic functionality of map applications. When it is combined with your existing application, your users will benefit from unparalleled, very useful features.
Chapter 1
The Four Types of Map APIs Yahoo! released version 3 of its Maps in November 2005, and with it a new wave of map APIs. Your development world is truly about to expand as you learn about each API. There is an Ajax API and two Flash-based APIs, and each type or flavor of API features its own set of characteristics. The technology behind each API flavor leads to some unique benefits, and as a result, both the basic and advanced functionalities vary while offering many of the same core features. The most distinct thing about each API is the way it is implemented. The Ajax API is known for its universal adoption and browser compatibility. This API was very skillfully built and has benefited from tremendous support. Ajax is spreading madly across the web and has been key in what has become known as the Web 2.0 revolution. Its ability to send and receive data without the browser being refreshed has changed the way map applications are used on the web. The three Flash APIs, while implemented very differently, are all built on a similar code base. There is a JavaScript implementation, which implements almost identically to the Ajax API. When Flash is used as an optimal rendering engine, method calls to this API are made through JavaScript and then channeled into the Flash client. The AS-Flash API requires you to develop with the Adobe (formerly Macromedia) Flash IDE. However, with this requirement comes the ability to control the appearance of the map in a way that no other API can offer. The Flash IDE enables you to work with the API instance on Flash’s stage, as well as with the programmatic instantiation of the API through ActionScript 2.0. Flex is a framework on top of Flash that allows extremely easy control of user interface (UI) elements with a language called Mxml. While Flex still requires some heavy use of ActionScript, it provides an environment that allows much more rapid deployment. A big strength of Flex is its ability to bind common control elements with dynamic data sources. With the Flex API, you can build what are considered more enterprise-level applications. With either the AS-Flash or Flex APIs, you will find it very easy to integrate other UI elements alongside the map, or blend them within it. This creates a seamless and rich user experience, ensuring that your application will be well received by your users. While each API has its own benefits, the Flash-based APIs offer some very special functionality. As you will see in the introduction to map features and tools in Chapter 2, “Developing with Yahoo! Maps,” Flash offers several ways to create your map application.
Understanding Map Technology To build a map application with Yahoo!’s APIs really requires very little, if any, understanding of map technology. The more details you understand, however, the better you’ll be able to make your map application. The first concept to grasp is that of map projection. Most people know the world is round, just like globes in elementary school classrooms. Yet online maps, as well as those we print for driving directions, are flat. Getting from the spherical presentation of Earth to a flat one online is called projection. If you were to merely peel off the detail of a globe and put it flat on paper, each piece would connect only at the equator. In other words, you could lay each piece of the globe side by side, but you would see gaps grow between the pieces up and down from the middle.
2
Your Map, Your World A projection model called Mercator, named after the sixteenth-century Flemish cartographer, solves this problem. This concept of map projection maintains consistent width between pieces of a globe. However, to fill in the gaps above and below the equator, Mercator stretches the north and south scale of the map. As you move farther away from the equator in either direction, the depiction of Earth on the map is gradually stretched. This provides a rectangular representation of a map, one that fills the window of a browser and the screen on your monitor. See Figure 1-1.
Figure 1-1
Another concept in mapping technology is scaling. Scaling simply enables you to relate the distance on a map to actual distance on the ground. Take a look at any map. You will probably see a pair of lines, usually on the bottom-left corner, showing the distances that represent miles and kilometers on the map. In dynamic web-based maps, the scale changes as you zoom in and out of the map.
Common Map Features and API Tools Because many of the features in Yahoo! Maps are offered in the APIs, your users will likely be familiar with what they come across in your applications. Before building your application and implementing the map APIs, it is important to get an overview of the tools that make map applications work. These are many of the fundamentals you will build on in creating your map applications with Yahoo! Maps APIs.
Map and Satellite Imagery At the core of the map application is the map itself. In most map applications, including Yahoo! Maps, map images are displayed with a combination of tiles. These tiles represent portions of the map cut up into fixed sizes and served to the application. When these tiles are combined, they form the viewable map area. To keep the application running efficiently, only those tiles in view, as well as some additional rows and columns of tiles, are downloaded as a buffer.
3
Chapter 1 The Yahoo! Maps API offers three different view types and, with these, three different sets of image tiles. The default view, map, presents the standard map tiles. These tiles combine two elements. First is the labels layer, displaying street, landmark and area names. Landmark labels include parks, lakes, shopping malls, learning institutions and railroad tracks, to name a few. The second element is a layer of color-coded areas. An array of simple colors is used to indicate with exceptional accuracy the size and location of bodies of water, roads, commercial zones and recreational areas such as ballparks and marinas. Both elements are generated from data and keep the map tiles fairly small in file size. The satellite view, perhaps the most fascinating element of web-based map applications, represents the layer made up of aerial images. These images, mostly taken from a satellite in space, give us a unique perspective on our world. The ideal satellite image will be taken with no clouds and with as little angle as possible. (In some major cities, like New York or Chicago, angles that cause shadows are inevitable due to the height of some buildings.) Satellite images are larger in file size than map images, as they feature high-resolution photography. Like the maps layer, satellite images are cut up into smaller pieces. This allows the map application to download the tiles progressively as opposed to downloading one big image. The hybrid view is a combination of both the map and satellite layers. This provides a very effective feature. Street names and labels are displayed on top of satellite images, providing more detailed information and removing some of the obscurity satellite tiles have by themselves. While the satellite tiles in the hybrid view are the same, the map tiles are slightly different. The second element is removed, as described earlier, leaving just the label elements. This creates a transparent effect in the map layer, letting the satellite imagery show through with the street, landmark and area names on top. In the map application, a set of buttons enables the user to toggle between map-view types. Working with the API, you can set the map-view type as a default parameter, allowing your users to see either the map, hybrid or satellite layers by default. There are several ways to introduce controls that allow toggling between layers as well. In addition to creating your own buttons with calls like getMapViewTypes(), you can also add a satelliteControlWidget that mimics the buttons in the Yahoo! Maps beta.
Zooming Maps have zoom capability to allow the user to display different magnitudes of the same layer. With the satellite images, photographic layers are compiled at several different distances. The map’s layers are rendered at these respective distances as well. The action of moving between these layers, moving your view of the map closer and farther away, is called zooming. Past HTML- and JavaScript-based map applications included zooming. However, when zoom levels were changed, the application needed to completely refresh, loading the new layer. Yahoo! Maps APIs allow zooming that does not require the browser to refresh. The Flash APIs also feature a much more dazzling effect. As the user zooms from one distance to the next, the layers actually fade into one another, creating a very attractive transition effect. There are 16 zoom levels offered in the APIs. Zoom levels are changed by the user clicking on the zoombar, a user interface element that usually features plus and minus buttons. The plus button zooms in and the minus button zooms out. In the Flash APIs, a slide mechanism is placed between the buttons of the zoombar. When the slider is selected and moved up or down, like to the scrollbar on the side of a web browser, the map will respond by zooming in and out accordingly.
4
Your Map, Your World The zoom level can be set by default when the API loads. By calling methods like setZoomLevel(), you can programmatically modify the zoom level of the API instance. Methods like setCenterByAddressAndZoom() enable you to move the map to a new destination as well as to prompt a zoom level change. In the Flash APIs, changing zoom levels by calling the API methods will induce the transition effects. See Figure 1-2.
Figure 1-2
Panning A key functionality of web-based map applications is the ability to pan. Commonly referred to as “making the map draggable,” panning is the action of moving the view of the map in any direction. You may be surprised to know that this feature is overall fairly new to map applications. In fact, several map applications still do not have panning abilities. Traditionally, maps without panning require you to click on the direction in which you want to move the map. Once you choose the direction, the application must refresh to collect new tiles. Yahoo! Maps and the API feature a very well implemented ability to pan, and you can do it in several ways. In film and television, panning is the technique of moving a camera to create a sweeping shot. The effect is called panoramic. Panning applied to maps creates a transition so the map within the API moves without the component container moving around on the screen. In the API, this is achieved by the masking capabilities of Flash. The best way to pan is to click the map with your mouse and drag it around. Effectively, what you are doing is moving the map view layer, with all its tiles. Because the map view layer downloads tiles as it needs them, panning far enough in any direction will likely prompt the application to download and display additional tiles. A buffer exists to be displayed so the application has tiles to show as you pan beyond the initial downloaded layer.
5
Chapter 1 A less discoverable, but very effective, way to pan over the map is with your arrow keys. Using your keyboard, the map will pan in the direction of the arrow key you press. Those users who like to use shortcut keys will find this feature very suitable. Like an airplane’s throttle, each key actually moves the map in the opposite direction. Pressing the up-arrow and right-arrow keys simultaneously will move the map diagonally. When working with the API, you add panning functionality as a tool with addTool(). One of the advantages to using the Flash APIs, as we will explore, is the support of a hand icon instead of a mouse cursor. This adds better discoverability to the panning feature, as users know what areas they can drag.
Geo-coding A map’s ability to plot an address is called geo-coding. By means of sophisticated backend technology capable of correlating countries, states, cities, ZIP codes, streets and street addresses, an address is turned into latitude and longitude. You may remember latitude and longitude (referred to in maps development as lat/lon) from elementary school. Lat/lon are the axes of a map. Since most developers don’t know lat/lon coordinates by heart, the map APIs offer built-in geo-coding. This means you can pass an address in the API’s initial parameters, then that address will be converted by the server to lat/lon, and the API instance will display and load to that location. You can call a method like setCenterByAddress() to perform a similar function and change the address during runtime. If you do know what your initial lat/lon is, you can set that for when the API loads. By using methods like setCenterByLatLon(), you can change the location the map centers on. A method called getCenter()returns a LatLon object representing the center point of the map. In the event that an address returns an error, the sophisticated API will likely return a SuggestedAddress or an array of them. This can be displayed to your users and help them narrow down address selection.
Markers and Custom Markers Markers are locations plotted on a map at specific locations, indicated with icons, images and media. They are placed at lat/lon coordinates derived from the server based on an entered lat/lon or address. Acting as indicators, markers can represent several aspects of data being shown on maps. Yahoo! Maps APIs offer several ways to display markers, using methods like addMarkerByAddress and addMarkerByLatLon. More impressive are the variety of marker types you can add. A CustomPOIMarker (POI meaning point of interest) can be added and features out-of-the-box interactivity when the user rolls over it. When the user engages this type of marker, a dynamic title will be shown. These markers can be defined with custom colors as well. CustomImageMarkers let you define a marker with a JPEG or SWF file. However, with the Flash API you have an even better option. Using CustomSWFMarker not only lets you define a marker with a custom SWF, but also lets you call methods on that SWF with callCustomMethod. Basically, you can create
your own Flash movie and serialize it as your marker. This feature will be explored much more in later examples found in Chapter 16, “AS-Flash API Advanced Features.” For now, look at Figure 1-3.
6
Your Map, Your World
Figure 1-3
Overlays Adding an overlay to the map creates another layer that stays in sync with the map as it pans and zooms. An overlay can contain various elements, all displaying on a transparent layer above the map. When you add a set of markers to an overlay instead of to the map, you can control them collectively, using hide() and show(). Packaged with the Flash API are two very powerful overlays, LocalSearchOverlay and TrafficOverlay. LocalSearchOverlay adds the ability to search Yahoo!’s powerful local database. Your users will be entering local search criteria and a method search(). Based on those criteria as well as the center lat/lon of the map, the API will take data returned from the server and add a set of markers representing several local findings. The markers within the overlay will display the business name and, when engaged by the user, will also display address, contact and rating information for that establishment. The TrafficOverlay data add some very useful information technology to the API. When activated, this overlay displays special markers, based on the map’s location, featuring traffic incidents such as accidents and closed roads. The possibilities of the overlay are limitless. As you will learn, the results from many data sources can be neatly and effectively contained within an overlay. Like markers, the API offers much customizability with classes like CustomSWFOverlay.
Navigation An API element found only with the Flash APIs is the NavigatorWidget. This widget represents a unique set of user interfaces that provides users with an intuitive means of moving the map around. The NavigatorWidget consists of two elements, a zoombar and a miniature version of the map, called mini-map.
7
Chapter 1 The zoombar handles much like the one we discussed in the earlier section “Zooming.” There are two buttons, a plus button and a minus button, which handle zooming in and out respectively when pressed. The slider in the middle is draggable and changes the zoom level of the map as it is pressed and dragged. Adding to the panning ability of the map is the mini-map element of the NavigatorWidget. Featured here is a smaller version of the map, displaying a bird’s-eye view of the main viewable area. Just like the main map, the mini-map also consists of layers, but it is restricted for usability reasons to displayed map tiles. Hovering within the mini-map is a distinct gray rectangle. When clicked and dragged within the boundaries of the mini-map, this square prompts the main map to pan along with it. Another feature that usually goes unnoticed is that this gray square actually maintains the ratio of the main map should the browser window be resized. See Figure 1-4.
Figure 1-4
Summar y In this chapter, you learned the following:
8
❑
What a map API is and the basics of its application
❑
The three flavors of Yahoo! Maps APIs and their respective technologies that will be covered in this book
❑
Projection and scaling map technologies
❑
Several of the common features of map applications and the map APIs
❑
How map tools and interfaces work in the map APIs
2 Developing with Yahoo! Maps In the last chapter, you learned what map applications and their APIs can do. As stand-alone applications, they are more than engaging. Now we’ll explore how applying various technologies and a wealth of online data to map APIs will form a mashup. This chapter discusses ❑
What a map mashup is
❑
Keys and fundamentals of mashup technology
❑
A sampling of free online data sources primed for map mashups
❑
How Yahoo! supports you in development with the map APIs
What Is a Mashup? Think of a mashup as a web cocktail, a mixture of two or more sources of content that creates a new web application. To understand mashups and the spirit of them, you must first understand Web 2.0. Over the past five years, web developers have begun to use dynamic technologies and concepts like Ajax, Flash, PHP and content syndication in order to build more collaborative and rapid-publishing applications. The fruit of this innovation is the wealth of blogs, free APIs, comment-driven sites and wikis you enjoy on the web today. Many of the Internet giants, the Yahoo!s and eBays of the web, have realized that to give data away is to promote the depth of their own sites. Web developers are enjoying unprecedented access to the very data and programming interfaces that were once kept locked up by such successful web pioneers. Access to this content is granted almost completely free, with little monitoring, so that you can combine it with your own web application.
Chapter 2 This practice of combining data has become so much an art form that developers have begun mixing data from one site with data from another’s. In the case of Yahoo!, which has so many properties, data can be combined between two entities like Sports and Local or Flickr and Travel. The essence of mashups is the act of combining these data to offer your users and the web your own new application.
XML Extensible Markup Language (XML) is a file that can describe data as well as contain them. Think of XML as a database, but in a file format. XML is human-readable, meaning you can read it when you open it in Notepad or a coding IDE. As a file format, XML is very cleanly syntaxed and the patterns within it are very easy to follow. XML has become the most highly recommended way to share data between web sites, software applications and operating systems. The code that follows is an example of an XML file, used to store album information in an MP3 player desktop application: Abbey Road The Beatles 17 The Fall On The Surface < Total_Tracks >12
Wrapped in the Albums node, information about each individual album is listed within its own Album node. The code you will use to read or parse this XML will look up a specific album’s data by stepping through each set of nodes.
REST Many APIs used to develop mashups use REST (Representational State Transfer), an architecture built on a GET and RESPONSE model. Using a URL with appended queries, web applications can talk with each other and exchange data. When a request is sent it prompts the service to return data. Those data come in the form of XML. Your application will likely need to get data from another source. You will start with the web service’s URL, the hostname of the REST service you will call for data. After you append the query corresponding to the data you want, that string will be coded somewhere in your application and tied into a user interaction. The XML returned will ultimately generate markers on your map application. The code that follows is an example of a REST query and a response in the Yahoo! Local Search API: http://api.local.yahoo.com/LocalSearchService/V3/localSearch?appid=WroxYahooMaps&qu ery=pizza&zip=60609&results=1
10
Developing with Yahoo! Maps This query requests locations in the ZIP code of 60609 that have the keyword pizza. The results parameter forces the response to be limited to one. Pizza Nova 558 W 43rd St Chicago IL (773) 548-5100 41.816437 -87.640051
The XML returned provides detailed data, including the latitude and longitude of the location, wrapped in the ResultSet node. REST-based APIs will be explored in more detail later in this chapter.
RSS and GeoRSS Feeds RSS stands for Really Simple Syndication and is a form of XML. Having become one of the most popular data formats online, RSS is used to replicate content found on web sites, weblogs (blogs) and podcasts. News sources like CNN, MSN and Yahoo! News offer RSS feeds so that the headlines and stories they report can be displayed almost verbatim across the web. In addition, shopping sites such as Amazon, eBay and Yahoo! offer free RSS feeds that relay product information such as pricing and availability. RSS feeds consist of four common attributes: title, link, description and pubdate (the date the feed was published). On occasion, there maybe be other attributes or objects mixed in, such as images that accompany the text. The code that follows is an example of an RSS feed from Yahoo! Sports listing headlines about the Red Sox. The title, link and description nodes represent standard data found in most RSS feed results: Interleague Capsules (AP) http://sports.yahoo.com/mlb/news?slug=ap-interleaguecapsules David Ortiz hit his seventh career walkoff homer... Sat, 24 Jun 2006 14:34:09 PDT
Users can take these feeds, usually called by a URL, and load them in RSS aggregators. One such aggregator is My Yahoo! Here, within a space customized to your personal preferences, you can define your own content based on thousands of RSS feeds. An aggregator takes in the feed and displays it for you.
11
Chapter 2 RSS feeds work particularly well with map APIs when the feeds include geographically encoded objects, as GeoRSS does. In addition to the standard attributes, geographically encoded objects add a georss: point tag to the feed. Featuring a latitude/longitude coordinate, this tag will add a location to the entry in the RSS feed: 42.346524,-71.097381
In this book I’ll cover the ability of each flavor of the Yahoo! Maps API to aggregate GeoRSS feeds.
Prime Mashup Sources Now that you have a solid understanding of mashups and the types of APIs and data out there, it’s time to introduce you to some of the great sources available to you. These are the ingredients in your web cocktail, and combining them with each other and ultimately with Yahoo! Maps makes for some fun and effective mashups.
Flickr Flickr has become one of the most popular and exciting web services around. Considered one of the best photo sites, Flickr enables its users to share and manage their photos from almost any source (see Figure 2-1). These sources include a user’s desktop, his or her mobile phone or device and, of course, the web. A huge objective of Flickr’s is to expose photos through as many outlets as possible. Photos in Flickr’s repository are viewable in e-mail messages, blogs, widgets, plug-ins and RSS feeds, as well as on the website www.flickr.com.
Figure 2-1
The success of Flickr is largely due to the tagging feature supported in the application. When a user uploads a photo, rather than just titling the photo, that user can add keywords called tags to it. These tags allow Flickr’s search engine to identify both photos and sets of photos by association. When another user browses photos on Flickr, a search for an existing tag will pull up all the photos tagged accordingly.
12
Developing with Yahoo! Maps What makes Flickr such a great source for mashups is its very comprehensive API. The API consists of a great catalog of methods with which to search for and get much of the attributes associated with a photo. These attributes range from a tag on the photo to the date it was taken, who uploaded it and what set it may belong to. Flickr works great with maps because so many photos are uploaded with tags referencing geo-spatial information. That is, many photos have tags that let you know where they were taken. Mashups with Flickr often show a series of photos as a marker. With the Flash API, you can build a sophisticated customSWFMarker that lets users browse through sets of photos within a sleek interface. That marker is plotted at the very place a photo was taken, at the place that it is associated with.
Upcoming.org One of the web’s premiere event calendar applications is Upcoming.org. Upcoming is free and enables anyone to enter information about any event for public consumption. Users can log an event happening anywhere in the world, from Lithuania to Luxembourg. When someone adds a new event, such attributes as event category, start date and time, end date and time, event name, description and event URL are collected. The site offers a list of venues to which you can assign your event. If your venue isn’t listed, you can add it through a very simple interface. There is a unique social aspect to Upcoming. When adding an event, you can specify if it’s personal or private or even self-promotional. Once the event is added, your friends and other users on Upcoming can find that event and register themselves as attending. Other users can even comment on the event. Upcoming’s value as a mashup source lies in the venue information collected when an event is logged. The venue information, whether previously existing or newly entered, includes a precise location. Like Flickr’s API, Upcoming’s gets you access to events and their locations. These events can easily be depicted as markers or markers within overlays. Data can be retrieved in such a way as to allow the event title or venue to be displayed by default. When a user engages with the marker, additional information on the event or venue, such as address and event time, can be displayed.
HotJobs HotJobs is another location-based web site that is very friendly with map APIs. The service lets employers post job openings for a fee and invites job seekers to search those postings for free. It is a very simple model, one that has been very successful for several sites like it. Users search job openings by keyword, location (city, state or ZIP) or category. You can expand the search to include surrounding cities as well. A useful addition to HotJobs is the search agent. This feature lets you save a search you make, register your e-mail and receive notifications as jobs that meet that set of criteria are posted. Additional resources like career tools and topics on résumés, interviewing, networking and salary calculations round out a very helpful resource. A good mashup scenario involving HotJobs is not hard to imagine. People move often and need to find new jobs. Pulling in HotJobs data through its API and displaying those data in the Yahoo! Maps API helps users gauge the distance between potential jobs and where they may rent or buy a home.
13
Chapter 2
Weather On the news, you will never hear weather mentioned without a reference to the area it is affecting. Weather is news based on location, and that makes it a perfect ingredient to be mashed up with Yahoo! Maps. The weather API offered by Yahoo! gives you up-to-date weather information on an area, using a ZIP code or location ID. XML returned by the weather API is in RSS format and features attributes such as wind (wind chill, direction and speed), atmosphere (humidity, visibility and pressure), and astronomy (sunrise and sunset). Most useful is the forecast attribute, which lays out what the weather is in that area and what it will be later. Forecasts feature a code that adheres to the weather API’s code index, enabling you to look up a code to see what the weather condition is. Combine that information with the latitude/longitude value and the magical CustomSWFMarker in the Flash APIs and you can creatively convey actual weather masses right on the map.
Traffic Yahoo! offers a REST API and RSS feed for traffic, and both play very nicely with the map APIs. The Traffic API is used to mark any traffic problems based on the location you query. In your map’s mashup, you can tie the location, as it is dynamically prompted based on user interaction, and pass it into the Traffic API. The XML returned can be represented with markers (see Figure 2-2) or as a set of markers within an overlay.
Figure 2-2
The TrafficOverlay class mentioned previously will be explored with the Flash APIs a little later in this book. A benefit to using this built-in overlay is that it leverages a wide set of preloaded custom markers designed to reflect various traffic alerts.
14
Developing with Yahoo! Maps
Local Search As I demonstrated in the REST example, local search is a very powerful example of data perfect for the map APIs. After being successfully queried, local search data returns XML featuring some very comprehensive location-based data. The information available includes business name, contact information, address and the categories related to the business. Also included is the rating for the business, an attribute representing the collective rating given to the business by Yahoo! users. The LocalSearchOverlay class mentioned previously will be featured in some of the mashup examples that use the Flash APIs. Included in this class are special markers that display local business information and feature a five-star rating interface.
Yahoo! Developer Suppor t Yahoo! has a tremendous reputation for offering developers trustworthy and well-supported APIs. The map APIs are no different. Yahoo! offers a wide range of very helpful code references, documentation, examples and source code. Particularly useful with maps are the “Getting Started” examples available. Like the exercises in this book, these examples are cut-and-paste, ready to be inserted and launched.
Developer Network Yahoo! Developer Network (YDN) is responsible for spreading the word about all Yahoo! APIs and development platforms. This group also works to distribute and govern the APIs. All APIs listed and supported by YDN receive the same high-quality support, no matter how old or new the API is. The support offered by YDN, documentation and all, is very consistent from one Yahoo! API to the next. This is a big advantage to developers, making it easy to explore the wide offering of APIs. You may not have noticed, but each of the APIs in the previous section is a Yahoo! property and all are supported under the same roof of YDN. Yahoo Developer Network can be accessed at http://developer.yahoo.com.
Message Group The Yahoo! Maps message group is a welcome support line for all developers using the map APIs. Messages posted here are read by other API developers like you as well as Yahoo! developers actually working on the APIs. Messages posted consist of questions and answers regarding best practices, requests for source code and assistance and suggested alternatives to ways of implementing the API. The message group is also used by API developers to post bugs, learn of upcoming releases and share their latest mashups with others. Several support groups use Yahoo! Groups. The yws-maps group is a popular place to discuss maps and map mashups. Here, developers and members of the maps team exchange ideas for working with maps. This group can be found at http://tech.groups.yahoo.com/group/yws-maps/.
15
Chapter 2
Maps Application Gallery Part of the fun in developing a mashup is being able to share it with others. But what if your mashup is so good, you desire to see it on a greater stage? The Yahoo! Maps API Application Gallery features the very best, most innovative mashups made by users and the development community. Featuring mashups made with all the API flavors, the gallery also acts as a launchpad and point of inspiration for other developers looking for ideas. Since many of the postings push the envelope of the map APIs and stretch them to the limit, browsing through the elite postings can give you a good sense of just what is possible with the APIs. Yahoo! hosts its Application Gallery at http://gallery.yahoo.com. Developers are encouraged to submit their mashups and share them with the community.
Summar y This chapter introduced you to the following key map mashup concepts and tools:
16
❑
How the Web 2.0 way of web development has made mashups possible
❑
That XML data is used in responses to REST queries and in RSS Feeds
❑
That Yahoo! APIs such as Flickr, Upcoming.org and Local Search are perfect for mashing up with map APIs
❑
That the Yahoo! Developer network provides various channels of support for developing APIs
3 The Ajax API “We found this map that said that underneath this place there’s buried treasure.” — The Goonies, 1985 The Yahoo! Maps Ajax API applies a technology that has become one of the most significant web technologies ever. In this chapter, you will be introduced to the technology that fueled Web 2.0 and spelled the end of the HTML browser refresh as you knew it. This chapter discusses the fundamentals of JavaScript, Ajax and the Yahoo! Maps Ajax API, including ❑
What the Ajax API is
❑
How Ajax works in many exceptional applications
❑
Fundamentals of JavaScript, CSS and DHTML
❑
How Ajax uses the XMLHttpRequest object
❑
Benefits of the Ajax API
What the Ajax API Is The first of the four map APIs covered in this book is the Ajax API. This API makes available the full library of classes and events necessary for you to display the Yahoo! Maps developer offering. This includes the map tiles, navigation ability and elements, as well as key mapping functionality. The Ajax API is not installed, nor does it need to run on your server. As you will see, you can get all you need to display maps to your users by referencing and importing a simple JavaScript file into your HTML. Once the files are automatically included in your code, which you achieve by including the API’s library file within a JavaScript src tag, you can create an instance of the map. This instance is actually built on a container element defined by CSS (Cascading Style Sheets), a definition of how content will be laid out in HTML.
Chapter 3 Once you have an instance of the map, you can begin calling methods against it. Methods like drawZoomAndCenter and setMapType enable you to programmatically change the appearance and behavior of the map. Additional elements like events and objects, you will learn, enable you to create a unique map experience.
Ajax in Greater Depth Ajax is not a language. It is actually an approach to coding that leverages the rather limited individual capabilities of JavaScript, CSS, HTML and DOM. In fact, Ajax stands for Asynchronous JavaScript plus XML, referring to the combination of these two elements. This combination enables data exchange and communication to the server to take place from within the application rather than from the browser. Before people realized how effective an approach like Ajax was, most web-based applications built in HTML were developed to handle data through the browser. This required more browser refreshing and resulted in larger amounts of data needing to be exchanged. Fewer data means faster exchanges and display of content that, as in maps, may include images, text and other media. The Asynchronous in Ajax refers to the order in which data requests are made. With Ajax, requests are not queued up (scheduled) to be processed. Rather, in a nonlinear fashion, requests can be made and the application can continue without waiting for the response. When the response is received, the application will continue handling those data as needed.
Applications You Know That Use Ajax Just how prevalent is Ajax in the web world? Here are some Ajax applications you know of and probably use regularly:
18
❑
Flickr: As described in the last chapter, Flickr is a photo-sharing site. The site features some very effective Ajax, supporting image browsing and photo management. The site takes advantage of Ajax’s ability to transmit small amounts of data, particularly when the user scrolls through several images.
❑
Yahoo! Finance: If you explore Yahoo! Finance during a trading day, you may notice that the stock prices actually change to reflect the market value. Ajax makes these updates possible and enables the free flow of data without browser refreshing. It creates more of a seamless environment and lets you read articles on those stocks without interruption.
❑
Radario.com: This site displays top-ten product and media rankings from several popular sources. The rankings are updated daily and feature some key interactive elements to gauge user experience and opinion for each item. The user can click on items ranked by listing and, using Ajax, Radario will retrieve and display item details from the database quickly and without browser refresh. Additional Ajax-powered features include user comments that update an item’s rating as they are entered.
The Ajax API As Ajax has become more accepted and better understood, it has gained some serious traction in web development. Due to the strictly object-oriented approach of Ajax, those developers and teams tasked with deploying Ajax applications came to be considered more than just web developers. Front-end engineering is now known as the role of implementing dynamic web pages, most likely driven by Ajax.
Fundamentals of JavaScript While the API itself uses Ajax, much of the map application you will build will consist of JavaScript interacting with the map classes. It is very important to gain a solid understanding of the fundamentals and capabilities of JavaScript. JavaScript is a web-scripting language that has some ties to the programming language Java. It runs in the browser and is executed as an interpreted language. This means that it does not need to be compiled into another file or build to run. JavaScript became a very significant language early on, adding new levels of interaction and browser control to the web. Designers used it initially for effects like image animation, browser detection, plug-in detection, status messages in the browser and HTML form validation. As with any language that’s been around for 10 years, JavaScript has been reversioned several times. While its fundamentals have pretty much stayed the same, through the years many new uses of the language have been realized. Its dependency on the browser has helped in its evolution. With new browsers invariably came new abilities. Developers explored new ways to make their HTML and JavaScript applications more engaging. One of the keys to JavaScript’s success and its continued prevalence is the simple syntax it uses. Here is a sample of a popular JavaScript code used with HTML to launch a new browser window: Javascript > New Window function newWindow() {launchWindow = window.open(“http://www.mashupexperts.com”, “newWin”, “width=800,height=600”) } Launch Window
You will notice that the meat of the script is set in the Head tags of the HTML. This is where the JavaScript is defined and where the newWindow Function is set. This function becomes available to the rest of the code within the HTML and can execute the same code over and over again as called upon. The newWindow function will create a new browser window by calling open against the current browser window object, the one you are in. The function is actually called when the “Launch Window” link is clicked. This link is tagged with javascript:newWindow, which tells the browser to call the function of that name within the JavaScript set of code.
19
Chapter 3 JavaScript, as mentioned earlier, has a strong ability to control and manipulate the browser’s elements (or objects). It does this by accessing the DOM (document object model) of the browser. The DOM includes the window, location, history, document and navigator elements and objects of the browser. DOM control is a key ingredient in how JavaScript lends itself to the AJAX approach. Since JavaScript is an ECMAScript language, some of its abilities that are featured in other languages follow the ECMAScript standard. Later in the book you will work with Actionscript, the language of Flash and the key ingredient in working with the AS-Flash API.
Commenting Code Like many languages, JavaScript has a way to disable code. This is an important part of development. If you are new to JavaScript, a lot of your first passes at applications will be the result of much trial and error. You will need to master the simple art of commenting code as you try different ways to do things and repeat code throughout your first set of classes and the application you develop. Commenting is very important when you work on code that will be shared with other developers. It gives you a way to tell developers what you were doing and why. It is good practice to leave comments before each set of variables as well as above each function. Good third-party JavaScript editors will change code to a shade of gray when it is commented out. This is a very helpful feature, as it helps you identify and ignore unused sections of code: //This line is commented out. This line is not. /* * This is a good way to * comment out multiple * lines of code. */
Functions and Methods A function is a means of executing a task in JavaScript. A key benefit of coding a function, as you learned in the earlier example, is that it can become available to your entire application. Using functions can save you a lot of time if there are tasks that will be called more than once. Functions accept parameters, values that can be passed when the function itself is called. This example shows the earlier example modified to pass the URL to load as a parameter: Javascript > New Window function newWindow(url) {launchWindow = window.open(url, “newWin”, “width=800,height=600”) }
20
The Ajax API Launch Window
Instead of being coded inside the function, the URL is now passed into the function as the url parameter. This is a much better practice, as it further generalizes the function should you want to call it in other places and have it load different URLs. In the Ajax API, internal functions of the API are exposed to you when the classes are imported as methods. These methods can be called against the map container instance to control the map. Methods are so important in working with the API that each API featured in this book has a chapter dedicated to reviewing the methods available for it. As you learned with functions, you can pass parameters with methods like address or latlon to change the map’s location.
Events Events are an important and often overlooked part of JavaScript. They represent user interactions or code occurrences that can be further handled by additional functions. Events are executed with event handlers. An event handler is the script that executes when an event occurs. An example of an event is when a user brings the mouse over an element, such as an image. The user action will fire an event called onMouseOver. The event handler would look something like this:
This code will call the newWindow function, passing the image as a parameter when it is rolled over by the mouse. Events play as big a role with Ajax, based much more on code occurrence than on user interaction. Working more with data and code execution, events can be fired to signal when data have been sent or received or when certain code is completed in the application. The map API dispatches many events tied to map activity, including startPan, changeZoom and onStartGeocode. Each of these refers to an activity of the map as it happens. Setting up event handlers for these events lets you call other functions based on map occurrences.
XMLHttpRequest Prior to the adoption of Ajax, or the discovery of the Ajax approach, many interactive web flows worked like this:
1. 2. 3. 4.
HTML loads a form. The user fills out the form and submits it. Form data is submitted to CGI or ASP and processed. The script returns HTML, which loads as the browser refreshes.
21
Chapter 3 The key to most Ajax-based applications lies in the JavaScript object XMLHttpRequest. This object enables server communication to occur within the browser and is commonly referred to as the Ajax engine. Rather than the browser submitting data and refreshing with the server’s response, this object handles all the work. The flow looks like this:
1. 2. 3. 4.
HTML loads a form, which is displayed with JavaScript and CSS. The user fills out the form and submits it. Ajax submits the data and receives the response. The JavaScript loads the response with CSS, without refreshing the browser.
XMLHttpRequest is constructed within JavaScript in your HTML document. There is one quirk in the
process that needs to be noted. Microsoft’s Internet Explorer does not use the native object; rather it uses an ActiveX version of it called XMLHTTP. When coding the object, you can use the window object to determine how the XMLHttpRequest object can be set. var xmlhttp = null; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”); }
This script checks for the native object support first. If it is not there, the application will assume the browser is Internet Explorer and set the object to the Microsoft.XMLHTTP object. The next step is to create the request: xmlhttp.open(‘GET’, url, true); xmlhttp.send(null);
The url acts as a placeholder for where the actual web service or API URL is placed. You can begin to see how the internal handling of the Ajax call is formed. Finally, it is time to handle the returned data. The XMLHTTP will return data using an event handler called onreadystatechange. xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // do something with the results } else { // wait for the call to complete } };
Using some built-in properties, it is easy to check the status of the response. This example is very basic and you will find this and other slight variations at the core of many Ajax applications. In the next chapter you will learn how to construct and implement Ajax when using the Yahoo! Maps Ajax API.
22
The Ajax API
Fundamentals of CSS and DHTML CSS is a means of defining style for laying out HTML in the browser. The standard was designed to address the layout and appearance limitations of native HTML. Style sheets let you define sets of styles as classes within a style tag. These styles can be referenced and applied throughout your HTML. Within the sets of styles you will usually find properties like color, width, height, font weight, font style and several other style attributes. Style sheets can be coded within the HEAD tag of the HTML code. If you are looking to apply the same style classes to multiple HTML documents, you can centralize the CSS in its own file and then reference it from any HTML document. This enables you to maintain one file for your entire site or web application. While styles can be referenced within everyday HTML tags, they are more frequently used with tags like span and div. These tags are part of DHTML (Dynamic HTML), a slight modification to the language
that allows for more dynamic handling of web content. Both tags build containers, which are elements that exist on the web page within, over or outside the boundaries of regular HTML. These containers rely heavily on CSS for positioning and appearance. The syntax of CSS can be tricky, but is easy to get the hang of. This example shows how CSS and DHTML are used to position the DIV container for the Ajax API: #container { position: absolute; left: 100; top: 100; border-style: solid; border-color: #FF0000; border-width: medium; } This is a positioned DIV container.
The combination of CSS and DHTML in this sample will create a small rectangle that appears 100 by 100 pixels from the top-left corner of the browser. The rectangle has a sharp red border and displays the text within. As you can see, all the style sheet properties are inherited when the div tag references container in its id attribute. See Figure 3-1.
23
Chapter 3
Figure 3-1
With Ajax, many interactive elements are handled this exact way. The Ajax API, for example, displays within a div tag. Much of the dynamic data and subtle animation and popups you saw in the Ajax examples earlier in this chapter used code like the previous sample.
Benefits of the Ajax API JavaScript, CSS and DHTML working together as Ajax are very powerful. A solid understanding and implementation of JavaScript, combined with the Ajax Maps API, will enable you to build some great and innovative applications. Using Ajax, you will give your users an experience free of browser refreshing and interruption. The Ajax API also inherits the overall benefits of the Ajax approach. This includes no required browser plug-in, meaning that your users will never have to download a player prior to viewing your API-based map application or mashup. Another benefit is the Ajax API’s ability to handle data transactions quickly, giving your users a much smoother mapping experience. With the amount of map tiles being loaded as your user pans and zooms, the ability of Ajax gives maps a welcome performance boost.
24
The Ajax API The Ajax API shares two key benefits with the JavaScript Flash API (covered from Chapter 8, “The JSFlash API” through Chapter 12, “The JS-Flash Mashup”). First, since Yahoo! hosts the class files, you can always access the very latest version of the API by including them in your application through the API libraries. This means that you can always have access to the latest classes to code with and to offer your users, simply by modifying the version number in the JavaScript s tag. To keep up with the latest version available, as well as the changes it features, visit http://developer.yahoo.com/maps/. Finally, the Ajax API is a very effective means of building map mashups, as it does not require the purchase of coding software or server technology to work. In the simplest form possible, you can actually edit the files using Notepad and load them locally with your Internet browser. This is very convenient for someone who is not a web developer by trade and wants to get started building map-based web pages.
Summar y This chapter introduced the Ajax API with the following key concepts: ❑
Ajax is not a language, rather an approach combining web technologies including JavaScript, CSS and DHTML.
❑
JavaScript consists of a simple syntax that enables you to work with functions and events.
❑
The XMLHttpRequest object is what enables Ajax to work. It is instantiated differently in Internet Explorer and in other browsers.
❑
The Yahoo! Maps Ajax API inherits the benefits of the Ajax approach, including a faster experience than is provided by the typical HTML documents.
25
4 Get Started with the Ajax API It is time to get immersed in JavaScript and start developing with the Ajax API. This chapter discusses ❑
The steps for getting an application ID (in case you don’t have one yet)
❑
What the software requirements for developing with the Ajax API are (or aren’t is more like it)
❑
How to embed the API and its library of classes
❑
Setting the initial properties of the map when it loads for your users
Get an Application ID If you have already completed one of the other sections in the book, be it about the JS Flash API or the AS Flash API, you will already be familiar with these steps. Otherwise, this step is a critical one and needs to be completed so you can properly develop with the map APIs. The first step to achieving mashup greatness is to register an application ID with the Yahoo! Developer Network (YDN). This free ID is a string of your choice, used by YDN to track usage of all Yahoo! web services. Since the ID is tied to your Yahoo! user ID, it also enables you to track your own API’s usage and gauge the total traffic it has generated. If you already have registered an AppID, you can still register a new one for each API you will use. Here are the steps to getting your Yahoo! AppID:
1.
Open your browser and go to http://api.search.yahoo.com/webservices/ register_application.
Chapter 4 2.
You may be prompted to log in with your Yahoo! user account. If you do not have an account, you will need to get one as instructed.
3. 4. 5.
After logging in, your username will be displayed next to “Your Yahoo! id.” Enter your desired application ID (AppID) next to “Requested application id.” You can provide an additional e-mail at “Alternate email (optional).” By default, the e-mail you provided with your Yahoo! account will be associated with your AppID. See Figure 4-1. Write down or save the AppID somewhere. You will need it later in this chapter.
Figure 4-1
Software Requirements As mentioned in the last chapter, one of the key benefits of the Ajax API (also featured with the JavaScript Flash API) is that it does not require purchasing or ownership of coding or server software. While you do need a hosting account or access to a remote server to share your mashup with the world, to develop locally, nothing is required. If you are not a seasoned web developer, using Notepad or your favorite text editor will work just fine.
28
Get Started with the Ajax API Many web developers and front-end engineers do, however, prefer the use of an IDE (integrated development environment). You have several good ones to choose from, including Adobe (formerly Macromedia) Dreamweaver and Eclipse. You can get a trial version of Dreamweaver at www.adobe.com. Eclipse, which is distributed free under certain licenses, can be obtained at www.eclipse.org. Developers find working with IDEs an improved coding experience for many reasons, one of which is file management. Both Dreamweaver and Eclipse feature ways to manage your files alongside the coding window. This enables you to open and move around all the files within your site. Dreamweaver adds FTP ability, a means of uploading your files right to the server as you code. The other great benefit, which helps all levels of coders, is code hinting. This is a special helping feature that, based on the language you are coding with, allows the IDE to colorize specific elements of the code. It can also offer up a list of properties and methods available as you type an object or variable.
Integrating the Ajax API This chapter features two examples that will walk you through the simple steps of integrating the Ajax API with your HTML. The web pages you build here will become the foundation of each Ajax sample and mashup you will build over the next few chapters. You will cover how to include the API as well as how to set initial parameters. Keep in mind that all methods and classes discussed will be covered in much more detail in subsequent chapters.
Including the API Classes Unlike some of the other map APIs covered in this book, the Ajax API is not a component. To include the API in your HTML, you simply need to include the API library in your document. You do this by defining the library src URL in the JavaScript tag within your HTML document. This includes all the latest classes and methods that will allow you to display and control the map within the API. The first exercise will set you up with the baseline code you will use throughout the next several chapters.
Try It Out
Add the Ajax API
These steps will explain how to add the Ajax API to your web page:
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Go to File ➪ New and create a new (HTML) document. Save the file as ajax_mashup.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
#mapContainer {
29
Chapter 4 width: 500px; height: 400px; } // Create a map object var map = new YMap(document.getElementById(‘mapContainer’)); // Position the map centered on a given address map.drawZoomAndCenter(“Boston, MA”, 5);
4.
In the fourth line of code, where you are defining the JavaScript source for the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. See Figure 4-2. You should see the Yahoo! Maps Ajax API load in your HTML document. The map should be loaded displaying regular map tiles of Boston at a zoom level of 5 (about city level).
Figure 4-2
30
Get Started with the Ajax API How It Works By defining the JavaScript source using the Ajax API library, you have made all the classes available to your web page. You set the src attribute of the JavaScript tag. This effectively imports or “pulls in” the very latest fields available, under the version you specified in the URL. The next step is to create a space on your web page, a container for displaying the Ajax-generated map tiles. Using the style tag, you create a style class called mapContainer. This is set to have a width of 500 pixels (500px) and a height of (400px). In the future, you can change these dimensions based on the viewable area of the map you desire in your web page. Within the body tag of your html, you add a div tag with the ID mapContainer. This will assign the properties of the mapContainer class in the style tag to the div you are creating. Effectively, this will size the div to 500 by 400 and ultimately fill the space in with a map of that size. Still within the body tag, additional JavaScript will actually trigger the map to turn on with some example properties. This section of code deserves close review, as it is your first usage of the Ajax API code itself. // Create a map object var map = new YMap(document.getElementById(‘mapContainer’)); // Positions the map centered on a given address map.drawZoomAndCenter(“Boston, MA”, 5);
You create the map by instantiating (creating an instance of) the YMap object. When creating the YMap instance, you need to pass into the object the container to load the map in. Calling the getElementById method against the Javascript DOM object “document” achieves this. What it is actually doing is “looking up” a div container in the HTML that will be the home for the map within your web page. By specifying mapContainer, this tells the Ajax API library where to load a new map and its tiles. Lastly, the Ajax API requires an initial address or latitude/longitude coordinate to load in order to display. Having the map instance of the API, you can call drawZoomAndCenter against that instance. The parameters you pass are the address followed by the initial zoom level you want to display. Methods like these will be reviewed in great detail in the next two chapters. As I mentioned earlier, with this exercise you have built the foundation for every Ajax API example to come. For the remainder of this chapter, as well as the next three, you will be using this code. Although it is very basic, you must understand the order in which the code is placed and executed.
Setting Initial Map Parameters While most of the methods of the Ajax API will be covered in each of the next two chapters, this example will get you started on setting initial parameters for the map. These values will be used when the map originally renders, giving your users their first view of the location around which you are building your mashup.
31
Chapter 4 You have a head start, actually, because the example you just completed already does some initial setting. The drawZoomAndCenter method you applied in the first example to the map instance is responsible for setting the initial location and zoom level of the map. Now, in the next exercise, you will add the map properties that enable you to center on latitude/longitude and set the initial map view type (the type of tiles that will load).
Try It Out Set Default Parameters for the Map 1. Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. 2. Open the file ajax_mashup.htm and save it as ajax_mashup_settings.htm. 3. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view): #mapContainer { width: 500px; height: 400px; } // Create a map object var map = new YMap(document.getElementById(‘mapContainer’)); // Create a lat/lon object using YGeoPoint var myPoint = new YGeoPoint(37.826701,-122.423103); // Position the map centered on a latitude and longitude and set the zoom level map.drawZoomAndCenter(myPoint, 2); // Set map type to YAHOO_MAP_SAT for satellite, YAHOO_MAP_HYB for hybrid, YAHOO_MAP_REG for regular map.setMapType(YAHOO_MAP_SAT);
4.
In the fourth line of code, where you are defining the JavaScript source to the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. See Figure 4-3. You should see the Yahoo! Maps Ajax API load in your HTML document. The map should be loaded displaying satellite map tiles of the Rock (Alcatraz Island) in the San Francisco Bay at a zoom level of 2 (about street level).
32
Get Started with the Ajax API
Figure 4-3
How It Works The upper part of this code is pretty much identical to that of the first example in this chapter. You are becoming quite familiar with this code by now. It is responsible, once again, for including the Ajax API library of classes into your web page. The mapContainer has stayed the same, as it creates a holder for the map to ultimately display in. Consistent with the first example, too, is the way the map object is instantiated. The YMap class is passed the div location, in this case the mapContainer, to load the API. The difference starts when the latitude/longitude coordinates are defined. Using the YGeoPoint class, the latitude/longitude object will tell the map where to center on when it initially loads its tiles. The Ajax API (as well as the other Yahoo! Maps APIs) needs to have the latitude/longitude coordinates turned into an object in order to process them. The YGeoPoint serves this purpose, as it creates a JavaScript variable called latlon. Most developers don’t know latitude/longitude coordinates offhand, so the address option used in the first example may be a bit easier to leverage. Once the latlon object is created, it can be passed as a parameter of the drawZoomAndCenter method, along with the desired initial zoom level. This will resolve the coordinates, center the map on that location and call for tiles at the specified zoom level. The last action taken in this example is to define the type of tiles. Regular tiles will show up by default. In the example, which uses setMapType against the map instance, you are specifying that satellite tiles will be showing initially.
33
Chapter 4 The next chapter will discuss these methods and much more in detail. You now have a very strong foundation for building your Ajax map mashups. You are about to do a whole lot more with this API and Yahoo! Maps.
Summar y After reading this chapter, you are well on your way to mashing up the Ajax API and have done the following:
34
❑
Obtained a YDN AppID
❑
Became familiar with Yahoo!’s terms of use for the API
❑
Set up your potentially free development environment for working with and testing web pages with the Ajax API embedded
❑
Added the Ajax API libraries to your web page
❑
Built your first Ajax-based map application featuring methods to perform simple actions such as setting the map’s address, view type and zoom level
5 Ajax API Basics In the last chapter you learned steps to setting up the Ajax API. You started developing JavaScriptbased applications and implemented some simple API methods. In this chapter, you will build on that knowledge. This chapter discusses ❑
How working with the API is made easier with events using YEvent()
❑
The full usage of methods that control zoom level, the type of tiles the map displays and the positioning of the map
❑
What data the basic get methods return and how they can be used to further your application
Basic API Methods As you have already seen in earlier examples, methods are the building blocks of working with an API. These are the exposed functions that let you call for specific functionality and control against the instance of the map API you are working with. The Ajax API methods are the most distinct of the four APIs covered in this book. However, the naming conventions are very common from one API to the next. To get started coding with the methods, it is good to leverage the strong event support the API offers. As you will see, many of these basic methods have associated events that are dispatched as the method code is executed. As you learn each method, this book will cover any available events in parallel. Whether you are coding along while each method is introduced, or are working with the available code samples, working with the events will help you get a better understanding of the timing and activity of each method.
Chapter 5
The YEvent Class Events are an important part of Ajax development. Working with maps, they represent different actions that the API code takes to position and modify the map tiles. Events enable you to develop with these actions, perfecting the timing of certain user interactions and interface elements within your web page. Capturing is the process of telling your code to actively listen for an event. You can do this using the aptly named Capture method found in the YEvent class. This useful method consists of one line of code: YEvent.Capture(objectInstance, event, callback)
The first parameter of the Capture method is the object instance you are listening to. (The methods discussed in this chapter focus on the instance of the map you created. In the next chapter, you will explore listening to other instances created, like markers.) The event parameter defines the actual event you are listening for. Lastly, callback is the function you will call in your code to carry out the event. The YEvent class will be used heavily in this chapter to help you understand how most methods actually affect the map. As you complete this chapter, you will learn each event that is tied to a method of the API. As you will see, many methods are tied to associated user interactions.
Map Zoom Methods and Events The Ajax API offers a set of methods and events to programmatically control zooming. These methods can be tied to user interaction, such as clicking on a button outside the map to change the zoom level of the map tiles being displayed.
setZoomLevel() setZoomLevel() sets the zoom level of the map. It accepts one parameter, a number that is the value of the zoomLevel you want to change the map to. The zoomLevel can be set to between 1 and 16. mapInstance.setZoomLevel(zlevel);
In this sample, the zoomLevel is set to 6: myMap.setZoomLevel(6);
The next chapter will introduce you to two built-in zooming user interfaces, ZoomLong and ZoomShort. These tools feature predesigned buttons and code that will add instant zooming control to your map with minimal coding.
changeZoom The changeZoom event is dispatched when the map’s zoom level changes and includes the following actions:
36
❑
setZoomLevel() has been called from within the code and changes the zoom level of the map.
❑
drawZoomAndCenter() has been called from within the code. (You will work with this method a bit later in this chapter.)
Ajax API Basics ❑
The user is zooming in and out of the map using the scroll wheel on his or her mouse.
❑
The user has clicked on either the ZoomLong or ZoomShort built-in zooming tool. (You will work with these in the next chapter.)
Using YEvent, here is how to capture the changeZoom event: YEvent.Capture(map, EventsList.changeZoom, onChangeZoom);
This code will listen to the map instance for the changeZoom event. Here, the changeZoom event is defined as a property of the EventList class. Finally, onChangeZoom is a function that will be called when the event is heard (captured).
getZoomLevel() get methods work very efficiently in the API. Since the value is already set, most likely by you calling their set method counterparts, all the API needs to do is return the value to you. For development, get
methods are very easy to implement, as they require no parameters to operate. As you code your application, you will find that get methods make development much easier. Rather than make sure your code “remembers” what values have been set throughout your application’s operation, you can call a get method anytime and have the latest value. The get methods also help with user interface implementation. You will need a starting point, a default value at which to position your user interface elements. The get methods will provide those data. The getZoomLevel() method enables you to obtain the current zoom level of the map. You can use it to adjust a custom zoombar or zooming interface that you have created. As you will see in the next chapter, knowing the current zoom level plays a key role when you are using overlays and other custom features of the API. mapInstance.getZoomLevel () ;
The following is an example showing how the method works if the map is set to a ZoomLevel of 5: var currentZoomLevel = myMap.getZoomLevel(); alert(currentZoomLevel); // Outputs: 5
Now that you have learned the set and get methods, as well as the event associated with changing the zoom level, it is time to put it all together.
Try It Out
Change the Map Zoom Level
In this exercise you will build a form that lets your users change the zoom level of a map and display the new zoom level after the map zooms. You will do this by building a simple form below the mapContainer.
1. 2.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Open the file ajax_mashup.htm and save it as ajax_mashup_zoomLevel.htm.
37
Chapter 5 3.
Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
Yahoo! Maps Mashups, Ajax API zoomLevel example #mapContainer { width: 500px; height: 400px; } New Zoom Level: Event Output: // Create a map object var map = new YMap(document.getElementById(‘mapContainer’)); // Position the map centered on a given address map.drawZoomAndCenter(“Miami, FL”, 5); // Changes zoom level based on value entered in forms function zoomLevel() { map.setZoomLevel(document.apiForm.newLevel.value); } // Captures changeZoom event and calls onChangeZoom YEvent.Capture(map, EventsList.changeZoom, onChangeZoom); // Displays new zoom level in form when event is fired function onChangeZoom() { document.apiForm.eventDisplay.value = “The zoomLevel is: “ + map.getZoomLevel(); }
38
4.
In the fifth line of code, where you are defining the JavaScript source to the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. See Figure 5-1.
Ajax API Basics
Figure 5-1
You should see the Yahoo! Maps Ajax API load in your HTML document. The map should be loaded displaying regular map tiles of Miami at a zoom level of 5 (about city level). Beneath the map are some form elements. Changing the value in the first text field and clicking “Zoom” should change the zoom level. The text area below that, labeled “Event Output,” will display the new zoom level as it changes.
How It Works After importing the Ajax API library, the classes become available to your JavaScript and HTML. The mapContainer style defines the size and placement of the map. The div tags will display the map as it is rendered and inherit the style sheet properties of the mapContainer class. The apiForm is written in HTML and will carry out two aspects of functionality. First, the form contains a text input field and a button. These two elements together will allow the user to enter a new zoom level and submit it. Upon submission, this will ultimately change the zoom level of the map. The other purpose of the form is to create a space for displaying event data related to the example as they occur. This space is a text area that will display the map’s new zoom level when the zoom event has fired. The zoom level changes when the Submit button is clicked within the form. The onClick() event handler calls the zoomLevel function. Within this function, the setZoomLevel method is called against the map instance. JavaScript references the user-entered zoom level, which is passed as the new zoomLevel parameter.
39
Chapter 5 You use the YEvent.Capture method to listen for the changeZoom event. That event is fired from the map when the zoom change is complete and is picked up by the event capture. The event capture then calls the onChangeZoom function, defined as the callback function. This function will populate the textarea element eventDisplay, inside the apiForm, with the new zoom level. This value is attained by calling the getZoomLevel() method against the map instance. This example should be easily replicated for each set of methods and events to follow in this chapter. By simply customizing the form to let the user enter relevant data, you will be able to call other methods against the map API’s instance. The event display part of the example is very flexible. All you need to do is modify the event being listened for, as well as the data being displayed, and you are all set to test other methods and events together.
Map Type Methods and Events The Ajax API considers the map type to be that of the tiles being loaded. You may recall an example in the last chapter that set the map type so the map would display satellite tiles. The Ajax API supports three types of tiles: regular (YAHOO_MAP_REG), satellite (YAHOO_MAP_SAT) and hybrid (YAHOO_MAP_HYB). Hybrid tiles are a combination of regular tiles and satellite tiles.
setMapType() The setMapType() method accepts one parameter, the view type to which you want to set the map. Here is how the call should look: var newMapViewType = “YAHOO_MAP_SAT”; myMap. setMapType (YAHOO_MAP_SAT);
This call will change the map type to satellite, refreshing the map with new tiles reflecting its existing location. In the next chapter you will discover the TypeControl, a prepackaged interface that achieves the same result.
getCurrentMapType() You want to call getCurrentMapType() to determine what tiles the map is currently displaying. This is useful if you have created your own buttons to let your users toggle between map view types. You may also include some effects in your application that activate depending on what layer is currently being displayed. mapInstance.getCurrentMapType();
This method could reveal that, based on changing the initial setting or by user interaction, the map is now displaying satellite tiles instead of its default map tiles: var currentMapType = map.getCurrentMapType (); alert(currentMapType); // Outputs: “YAHOO_MAP_SAT”
40
Ajax API Basics getMapTypes() getMapTypes() is most useful if you want to create your own map view buttons. Letting your users
choose their map view can add a hint of customization to it. Not to mention that the ability to display satellite images of the world, from space all the way down to street level, is quite an enticing feature that will draw users to your mashup. mapInstance.getMapTypes() ;
This method is a little more complex than the other basic get methods, as it returns an array. That means that the data returned by this method appear in something like a list. To view each item, you must loop through this list and save or trace out each value within the array. Whereas earlier you used a for/in loop to view the contents of EVENT_MAP_GEOCODE_SUCCESS and EVENT_MAP_GEOCODE_ERROR, here you will use a for/each loop. (The for/each loop will be discussed much more in the very next example.) var mapTypes = map.getMapTypes(); alert(mapTypes); // Outputs: “YAHOO_MAP,YAHOO_SAT,YAHOO_HYB”
Map Positioning Methods and Events This set of basic methods enables you to control the positioning of the map. In addition, these methods let you toggle certain built-in functionalities of the API.
drawZoomAndCenter() The drawZoomAndCenter() method accepts two parameters, address or YGeoPoint (latitude/longitude) and zoomLevel. A successful address can be a ZIP code or a street name, city, state and ZIP code. Certain major metropolitan areas will work as well. The address is converted by the API geo-coder into a latitude/longitude pair, and the map reloads its tiles and centers on that value. YGeoPoint is the class in the Ajax API that converts latitude/longitude coordinates into an object that can be properly handled by the API. This method gives you the option of passing either address or YGeoPoint, depending on what you have available: mapInstance.drawZoomAndCenter (address, zoomLevel);
or mapInstance.drawZoomAndCenter (YGeoPoint, zoomLevel);
This example shows the code to set or change the address to San Francisco and adjust the zoom level to 3: var address = “San Francisco, CA”; var zoomLevel = 3; map.drawZoomAndCenter (address, zoomLevel); >> zoomLevel not duration (mirek)
41
Chapter 5 endMapDraw This event is fired when the map completes redrawing as a result of drawZoomAndCenter. In addition, since the method calls for zooming to change, the changeZoom event may also be fired if the method calls for a zoomLevel change. YEvent.Capture(map, EventsList.endMapDraw, onMapDraw);
This code will listen to the map instance for the endMapDraw event. Here, the endMapDraw event is defined as a property of the EventList class. Finally, onMapDraw() is a function that will be called when the event is heard (captured).
panToLatLon() panToLatLon() is one of two manual panning methods. This method enables you to define a new YGeoPoint to which to change the map position. Calling this method will force the map to pan to the new location. The one parameter to pass is YGeoPoint, the latitude/longitude you want the map to pan to. mapInstance.panToLatLon (YGeoPoint);
This example shows the code to pan the map to the specified latitude/longitude coordinate: var myPoint = new YGeoPoint(37.826701,-122.423103); map.panToLatLon (myPoint);
panToXY() panToXY() mimics the functionality of panToLatLon. Instead of passing a latitude/longitude YGeoPoint, this method accepts an x/y YCoordPoint object as a parameter. Calling this method will force the map
to pan to the new location. mapInstance.panToXY (YCoordPoint);
This example shows the code to pan the map to the x/y coordinate: var myPoint = new YCoordPoint (100,100); map. panToXY(myPoint);
startAutoPan and endAutoPan Accompanying the panToLatLon and panToXY() methods are two events called startAutoPan and endAutoPan. These are fired when the method is first called and when the call’s actions complete, respectively.
disableDragMap() and enableDragMap() One of the features that all Yahoo! Maps APIs have is the ability of the user to click on the map and drag it around. This level of interactivity is one of the most popular features of Yahoo!’s developer offerings, and the Ajax API does not disappoint. With the Ajax API, this feature comes enabled by default. Should
42
Ajax API Basics you want to turn it off, you can use the supplied disableDragMap() method. There is no parameter required for this method: mapInstance.disableDragMap();
Once dragging is disabled, it is not lost forever. The counterpart to this method is enableDragMap(). Called in identical fashion, this method enables the map’s dragability: mapInstance.enableDragMap();
startPan, onPan and endPan A trio of events is tied to the user’s dragging the map. These events are similar to the ones associated with the panTo methods discussed earlier. Since dragging the map simulates panning it, these events also have a similar naming convention. When the user clicks on the map to drag it, the startPan event is fired. While the map is being dragged, onPan is dispatched. Upon release of the map, the endPan event is sent.
isDragMapEnabled() This method allows you to detect the map’s current ability to be dragged: mapInstance. isDragMapEnabled ();
Using this method in your code, you can determine whether you need to enable or disable map dragging: if (map.isDragMapEnabled()) { map.disableDragMap(); } else { map.enableDragMap(); } >> isDragMapEnabled – actual method name (mirek)
getCenterLatLon() getCenterLatLon() returns the latitude/longitude coordinate found in the center of the map. Using this method is the inverse of using drawZoomAndCenter with a lat/lon. mapInstance.getCenterLatLon() ;
This sample verifies that the map, by default, is centered on the point at latitude -99.84375 and longitude 39.232253: var currentCenter = map.getCenterLatLon (); alert(currentCenter); // Outputs: “-99.84375, 39.232253”
Now that you have learned the set and get methods, as well as the associated events for changing the map’s center and panning and dragging the map, it is time to put it all together.
43
Chapter 5 Try It Out
Change the Address
In this exercise you will build a form that lets your users change the address of a map and display the new latitude and longitude after the map re-centers. Another control will allow the user to pan to a specific location on the map.
1. 2.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse.
3.
Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
You can leverage the file you created in the last example or start from scratch. Open the file ajax_mashup_zoomLevel.htm or ajax_mashup.htm and save it as ajax_mashup_controlMap.htm.
Yahoo! Maps Mashups, Ajax API controlMap example #mapContainer { width: 500px; height: 400px; } New Address: Event Output: // Create a map object with satellite tiles by default var map = new YMap(document.getElementById(‘mapContainer’), YAHOO_MAP_SAT); // Position the map centered on a given address map.drawZoomAndCenter(“Denver, CO”, 5); // Changes address based on value entered in forms function drawMap() { map.drawZoomAndCenter(document.apiForm.newAddress.value, 5); } // Captures endMapDraw event and calls onMapChange YEvent.Capture(map, EventsList.endMapDraw, onMapChange); // Captures onPan event and calls onMapChange YEvent.Capture(map, EventsList.onPan, onMapChange);
44
Ajax API Basics // Displays latitude/longitude in form when event is fired function onMapChange() { var latlon = map.getCenterLatLon(); document.apiForm.eventDisplay.value = latlon.Lat + “, “ + latlon.Lon; }
4.
In the fifth line of code, where you are defining the JavaScript source of the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. See Figure 5-2. You should see the Yahoo! Maps Ajax API load in your HTML document. The map should be loaded displaying satellite map tiles of Denver, Colorado, at a zoom level of 5 (about city level). Beneath the map are some form elements. Changing the value in the first text field and clicking Go should change the location the map displays. The text area below that, labeled “Event Output,” will display the new latitude/longitude coordinates of the center point of the map. Clicking on the map and dragging it around should actively update the text area as well.
Figure 5-2
45
Chapter 5 How It Works Much like the example at the beginning of this chapter, this web page starts by importing the Ajax Maps API library. After defining the style and positioning the map, a form is constructed. This form features a text input field labeled “New Address” paired with a button labeled “Go.” Also part of the form is a text area for displaying event data as they occur. The JavaScript handles the population of the map. Note that the satellite tile definition is included in the constructor of the map instance itself. Once the map instance is created, the initial position of the map is set to Denver, Colorado, using the drawZoomAndCenter method. The drawZoomAndCenter() method appears again, inside the drawMap() function. This function is called when the Go button within the form is clicked, instructing the map to redraw itself to a location the user defines. (While this method supports change in the zoom level as well, the exercise does not include support for that functionality. You could combine elements from the first exercise in this chapter to include it.) Once the map re-centers, the endMapDraw event is fired. The YEvent.Capture method will hear this and call for onMapChange. This function populates the text area in the form with the latitude and longitude of the new center of the map. Finally, a second YEvent.Capture will pick up the onPan event. As you learned in this section of the chapter, the onPan event is fired when the map is clicked and dragged. Tying this event to the same onMapChange function creates the unique effect of continuously displaying the updated map center point as the map is dragged. The level of activity this functionality displays is further evidence of how well the Yahoo! Maps Ajax API really performs.
Summar y This chapter introduced you to several of the basic methods available in the Ajax API. Here is a summary of what was covered in this very significant chapter:
46
❑
The Ajax API dispatches events that can be captured and handled with one simple line of code.
❑
set methods are responsible for defining and changing different elements of the map.
❑
get methods can be called to retrieve specific properties of the map instance.
❑
HTML form elements, working with the Ajax API, can let users control and change most aspects of the map’s functionality.
6 Ajax API Advanced Features Now that you’ve learned the basic methods and functionalities of the Yahoo! Maps Ajax API, it is time to dive into more advanced features. In covering the more advanced classes and methods of the API, you will become better equipped to build a full-on mashup. This chapter is separated into sections that cover the following essential mashup techniques. This chapter discusses ❑
Adding markers to your map, which you can customize to feature labels, HTML popups and images
❑
Adding tools and compact interfaces with built-in buttons to let the user zoom, pan and change map type
❑
Coding and adding overlays to the map that can connect lines from point to point as well as from common GeoRSS feeds
Working with Markers You can’t really make a mashup without adding markers. Markers are the indicators of important locations on your map. They are added with precision by address or latitude/longitude. In addition to methods, there are ways to remove markers programmatically based on user interaction. Marker classes enable you to define the type of marker you add, be it a standard type or one you can design and develop from scratch. You can add markers one by one as well by loading certain overlays. If you have a database, XML file, web service response or other data source with many addresses or lat/lon coordinates, you will likely use a looping method in JavaScript.
Chapter 6
Marker Methods and Classes This small set of methods represents the functions most commonly featured in mashups: those that add markers. Each method lets you ultimately control the location and appearance of every marker you add on the map.
addMarker() This method lets you add markers to a location using a latitude/longitude coordinate or an address. mapInstance.addMarker(YGeoPoint);
or mapInstance.addMarker(address);
This will add a basic, orange-balloon-style marker to the coordinate or address you define.
YMarker To add a more customized marker, you will need to use the YMarker class. This class lets you add a label to the otherwise blank marker. It also lets you define, using HTML, how the marker will display when the user clicks it. var marker = new YMarker(YGeoPoint);
The marker object is created with a YGeoPoint, the latitude and longitude of the location on which you want to place the marker. Once you have created the marker object, you can begin to modify its properties: // Add a label to the marker marker.addLabel(“Marker Label”); // Add auto expand to marker var _autoExpand = ‘Click to popup Marker’; marker.addAutoExpand(_autoExpand); // Add an event and popup state to the marker YEvent.Capture(marker, EventsList.MouseClick, popupMarker); function popupMarker() { var _popup = ‘Marker Popup’; marker.openSmartWindow(_popup); }
Using the addLabel() method of the YMarker class, you can add a label with simple HTML. This will become the marker’s new default (idle) state. addAutoExpand() adds a string of HTML to represent the popup state of the marker. This will display when the user moves the mouse over the marker. To add a popup state to the marker, you first need to listen for the mouseClick event from the marker instance. Using YEvent.Capture, you enable the code to pick up the user’s mouse click on the marker. This will call the popupMarker() function. Within this function, you define a string of HTML that will
48
Ajax API Advanced Features act as the popup state of the map. Finally, openSmartWindow() is called against the marker instance with the popup state HTML as the parameter.
addOverlay() In order to add a YMarker instance to the map, you need to use the addOverlay() method instead of addMarker(). While I will review this method in more detail when I discuss overlays later in this chapter, the method is required in this context. mapInstance.addOverlay(markerInstance);
removeMarker() This method lets you remove a specific marker by calling it and passing the instance of that marker. mapInstance. removeOverlay (markerInstance);
removeMarkersAll() removeAllMarkers() will clear out all markers that have been loaded to the map instance. Since this
method affects all markers rather than a single marker, it does not need a parameter. mapInstance.removeAllMarkers();
YImage The YImage class, used in combination with the YMarker class, lets you add an image within a marker. This is very useful for marking various locations with an image rather than just text. var imageMarker = new YImage();
Once the imageMarker object is created, you can modify its properties. The properties include the image source and size. // Define source property with URL to image imageMarker.src = ‘http://urlOfImage’; // Define size of image using YSize Object imageMarker.size = new YSize(50, 50); // Define position offset of popup window for image imageMarker.offsetSmartWindow = new YCoordPoint(0, 0);
The imageMarker instance becomes the second parameter when the marker instance is created: var marker = new YMarker(YGeoPoint, imageMarker);
In the upcoming exercise, you will put all this information together and create on the map a marker featuring an image.
49
Chapter 6 Try It Out
Add an Image Marker to the Map
This exercise will help you display an image marker on the island of Nantucket off the coast of Massachusetts.
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Open the file ajax_mashup.htm and save it as ajax_mashup_addImageMarker.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
#mapContainer { width: 800px; height: 400px; } // Create a lat/lon object for positioning map var centerPoint = new YGeoPoint(41.289158,-70.094181); // Set up map type in the constructor var map = new YMap(document.getElementById(‘mapContainer’),YAHOO_MAP_SAT); // Display the map centered on a lattitude and longitude map.drawZoomAndCenter(centerPoint, 7); // Create YImage object var imageMarker = new YImage(); // Define source property with URL to image imageMarker.src = “http://www.mashupexperts.com/yahoomapsmashups/source/media/lighthouse.jpg”; // Define size of image using YSize Object imageMarker.size = new YSize(200, 162); // Define position offset of popup window for image imageMarker.offsetSmartWindow = new YCoordPoint(0, 0); // Create a lat/lon object for positioning marker var markerPoint = new YGeoPoint(41.283612,-69.965145); // Create a marker positioned at a lat/lon with image marker var marker = new YMarker(markerPoint, imageMarker); // Add a label to the marker marker.addLabel(“Click”); // Call onSmartWinEvent when the user clicks on the marker YEvent.Capture(marker, EventsList.MouseClick, onSmartWinEvent); // Capture the user mouse-click and expand the SmartWindow function onSmartWinEvent() { // Define content of popup var words = ‘Built in 1849 and lit in 1850, this distinctive lighthouse on the east side of Nantucket stands on a bluff 90 feet above sea level, overlooking an area of dangerous shoals.’;
50
Ajax API Advanced Features var words = words + ‘Learn More’; marker.openSmartWindow(words); } // Display the marker using addOverlay map.addOverlay(marker);
4.
In the fourth line of code, where you are defining the JavaScript source for the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID. The version of the API you are using is also defined in this line; be sure that it is at least version 3.4.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. You should see the Yahoo! Maps Ajax API load in your HTML document, as shown in Figure 6-1.
Figure 6-1
The map should be loaded displaying satellite map tiles of the island of Nantucket, off the coast of Massachusetts, at a zoom level of 7. Appearing next to the map should be an image of the lighthouse. On the image should be the label “Click.” When you click the image, a marker should pop up with a description of the lighthouse and a link.
51
Chapter 6 How It Works After setting up the map to display with the usual style definition and div tag, the initial map properties are set. The map’s type is defined when the map object is created and set to display satellite tiles. Using drawZoomAndCenter, the map is centered on an address and the zoom level is set. An instance of the YImage is created to ultimately display an image within a marker. Once this instance is created, a series of methods are called against the imageMarker instance to set the source, size and offset positioning of the image. Similar steps are repeated to create the marker instance itself. The YMarker constructor is passed the location as well as the imageMarker instance. In setting the properties of the marker instance, it is necessary to code the event listener to register when the user clicks the marker. This will call a function that launches the popup state of the marker. This state is populated with some HTML that features a description of the photo in the imageMarker and a link. Finally, the marker instance is added using the addOverlay() method of the YMap instance. This loads the marker on the map, featuring the image you defined.
Working with Tools Tools are prepackaged sets of user interfaces that ship with the Ajax API. They reflect some of the most commonly used technology on consumer map applications like Yahoo! Maps. Adding existing tools can save you time over having to replicate the functionality with your own user interface.
Control Methods The simple methods available for tools are part of the map class. These methods become available when the map instance is initialized.
addTypeControl() The type control is a widget that lets you toggle the map type among regular, satellite and hybrid tiles. This method saves time but does not offer the flexibility of creating your own buttons, as you learned in the last chapter with the map type methods. mapInstance.addTypeControl();
This line will add the type control tool to the top-left corner of your map.
addPanControl() This tool adds to the map a widget featuring four directional arrow buttons. Clicking each button will pan the map in the corresponding direction. The map comes with a default panning functionality. This tool adds some precision and more direct navigation to the map. mapInstance.addPanControl();
This line will add the pan control tool to the top-right corner of your map.
52
Ajax API Advanced Features addZoomLong() One of the most engaging features of the Yahoo! Maps APIs is the ability it gives the user to zoom between layers of the map. While the map comes with an interesting trick, the ability to zoom the map with the scroll wheel, this tool adds a more obvious interface for the effect. This tool has a minus and plus button at the top and bottom of the map, respectively. Clicking allows you to either zoom out or zoom in. The space in between the minus and plus buttons is occupied by a slider mechanism. Clicking on this and dragging it up and down will zoom the map out and in. mapInstance.addPanControl();
This line will add the long zoom control tool to the top-right corner of your map.
addZoomShort() The short zoom tool is a “lite” version of the long zoom tool. This zoom interface features the plus and minus buttons but without the slider in between. This tool is best used when you are trying to save map real estate or in conjunction with another tool. mapInstance. addZoomShort ();
This line will add the short zoom control tool to the top right of your map.
removePanControl() and removeZoomControl() These methods can be called, usually based on user interaction, to remove tools added to the map. Adding and removing tools can be confusing to the user. The combination of adding and zooming usually indicates a change in modes of the map, and can be effective when used in moderation. mapInstance.removePanControl(); mapInstance.removeZoomControl();
The first method will remove the panControl tool from the map. The second method will remove whichever zoom control has been added.
Try It Out
Add Controls to the Map
In this exercise you will add three controls to the map using some of the methods you just learned.
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Open the file ajax_mashup.htm and save it as ajax_mashup_addControls.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
53
Chapter 6 #mapContainer { width: 500px; height: 400px; } // Create a map object var map = new YMap(document.getElementById(‘mapContainer’)); // Define address var myAddress = “Seattle, WA”; // Position the map centered on an address and set the zoom level map.drawZoomAndCenter(myAddress, 2); // Add Long Zoom Tool map.addZoomLong(); // Add Pan Tool map.addPanControl(); // Add Type Tool map.addTypeControl();
4.
In the fourth line of code, where you are defining the JavaScript source for the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. See Figure 6-2.
You should see the Yahoo! Maps Ajax API load in your HTML document. The map should be loaded displaying regular map tiles of Seattle at a zoom level of 2 (about street level). In the top-left corner of the map you should see the type control with the Map button selected. In the top-right corner you should see the pan control and the long zoom control.
How It Works After setting up the map to display with the usual style definition and div tag, the initial map properties are set. Using drawZoomAndCenter, the map is centered on an address and the zoom level is set: // Add Long Zoom Control map.addZoomLong(); // Add Pan Control map.addPanControl(); // Add Type Control map.addTypeControl();
These three calls in succession represent the simplicity of adding tools to the map. The layout is automatic and the tools will move as the user resizes the browser.
54
Ajax API Advanced Features
Figure 6-2
Working with Overlays An overlay adds a new layer over the existing map layer. It moves along with the map as the map is panned. Overlays are most commonly used as containers for sets of markers representing related data such as local search results and traffic. As you will see, the overlays have the incredible ability to act as their own mashups. Adding some of the overlay classes will actually request data, parse the response and add markers all by itself. It is good to test out each overlay, as it may save you some time as well as add even more functionality to what you will ultimately build.
Overlay Methods and Classes Adding an overlay is simple and will enable you to display and explore a wealth of data. Included in the Ajax API are several overlay classes that will let you deliver useful common data as well as custom, one-of-a-kind sets of information.
55
Chapter 6 addOverlay() Once the map instance is initialized, you can add the overlay instance using addOverlay(). Working with overlays as markers do, the addOverlay() method accepts one parameter, the overlay class you are adding to the map. In most cases, you will need to instantiate the overlay class with its required properties before adding it to the map with this method. var overlay = new YcustomOverlay (); mapInstance.addOverlay(overlay);
Most commonly, you will use addOverlay to add a new overlay class and layer to the map. However, you can also use it to add markers to the map. To use this alternative approach, you will need to create an instance of the marker class first and then add it as an overlay.
YPolyline The YPolyline class gives you the ability to connect points on the map with colored lines. This unique functionality can be used to define hiking or biking routes throughout a national park, for example. It can also let you draw the travel path of a cruise ship or plane. //Create YPolyline object var polyline = new YPolyline(points, color, width, alpha); //Add polyline overlay object as overlay to map mapInstance.addOverlay(polyline);
The first property in a polyline object is points. These represents an array of YGeoPoint instances (latitude/longitude coordinates) that will make the up the “points” you will be connecting. Next is an optional color property, which will define the color of the line being drawn. (It will be colored red by default.) Another optional property defines the width of the line being drawn. Finally, the alpha property defines the transparency of the line.
Try It Out
Add a Polyline Overlay
This exercise will help you display the path of a cruise in the Bahamas.
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Open the file ajax_mashup.htm and save it as ajax_mashup_polyline.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
#mapContainer { width: 500px; height: 400px; }
56
Ajax API Advanced Features // Create a map object with hybrid tiles var map = new YMap(document.getElementById(‘mapContainer’),YAHOO_MAP_HYB); // Define center point var centerPoint = new YGeoPoint(25.552354,-78.805481); map.drawZoomAndCenter(centerPoint,11); // Create each point to be drawn with polyLine var p1 = new YGeoPoint(26.092863,-80.124501); var p2 = new YGeoPoint(25.086221,-77.327305); var p3 = new YGeoPoint(25.371328,-76.811634); var p4 = new YGeoPoint(26.495771,-78.692356); // Create polyOverlay object var polyOverlay = new YPolyline([p1,p2,p3,p4,p1],’yellow’,5,0.6); // Add polyOverlay to map map.addOverlay(polyOverlay);
4.
In the fourth line of code, where you are defining the JavaScript source for the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID. The version of the API you are using is also defined in this line; be sure that it is at least version 3.4.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. Refer to Figure 6-3.
Figure 6-3
57
Chapter 6 You should see the Yahoo! Maps Ajax API load in your HTML document. The map should be loaded displaying hybrid map tiles of the Bahamas, off the coast of Florida, at a zoom level of 11. Appearing over the map should be a series of yellow lines connecting Ft. Lauderdale, Florida, with various points in the Bahamas.
How It Works After setting up the map to display with the usual style definition and div tag, the initial map properties are set. The map’s type is defined when the map object is created and is set to display hybrid tiles. Using drawZoomAndCenter, the map is centered on an address and the zoom level is set. A series of YGeoPoints are defined and will represent the points the lines will be drawn to and from. The YPolyline object is created and passes the list of defined points, along with properties defining the line
style to be thin, yellow and semitransparent. As the YPolyline object, represented by polyOverlay, is added, the API will draw a series of lines in a layer above the map. This layer will stay attached to the map as you pan, drag and zoom it.
YGeoRSS This class and type of overlay enables you to populate the map with markers defined from a geo-coded RSS feed. This special version of RSS XML contains geo-coded objects. A geoRSS feed adds extra data like latitude/longitude or address in addition to location information. The following is a sample of a geoRSS feed that will be used in the upcoming exercise: ... Title to appear in Marker Link to appear in Marker Address where Marker will locate on map Address where Marker will locate on map Phone Number to appear in Marker ...
The GeoRSSOverlay is fed this XML as a URL. The parameter is set when the overlay instance is created. The file should reside remotely. //Create geoRSS object var georss = new YGeoRSS (‘http://urlToGeoRSS.xml’); //Add geoRSS object to map mapInstance.addOverlay(georss);
Two events are associated with the YGeoRSS class. onEndGeoRSS fires when the addition of the overlay has completed.
58
Ajax API Advanced Features Try It Out
Add a GeoRSS Overlay
In this exercise, you will add a geoRSS XML file as an overlay to your map.
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Open the file ajax_mashup.htm and save it as ajax_mashup_geoRSS.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
#mapContainer { width: 500px; height: 400px; } // Create a map object with hybrid tiles var map = new YMap(document.getElementById(‘mapContainer’),YAHOO_MAP_REG); // Define center point map.drawZoomAndCenter(“25 Buick St, Boston, MA”, 5); // Create YGeoRSS Object and add as overlay map.addOverlay(new YGeoRSS(‘http://www.mashupexperts.com/ymaps/source/georss/boston_colleges_georss.xm l’));
4.
In the fourth line of code, where you are defining the JavaScript source for the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. Refer to Figure 6-4.
The map will load showing Boston, as in Figure 6-4, and featuring the logos of various Boston-based colleges and universities.
59
Chapter 6
Figure 6-4
How It Works After setting up the map display space, the map’s location and zoom level are set. The GeoRSS object is created inline with the addOverlay method. The URL of the GeoRSS feed XML is the only parameter passed. The full XML being added defines the location of the marker, as well as the details that will be displayed inside the marker when it is clicked. Boston University 25 Buick St Boston, MA (617) 353-2000 Boston College 140 Commonwealth Ave Chestnut Hill, MA (617) 552-8000
60
Ajax API Advanced Features MIT 200 Technology Sq Cambridge, MA (617) 452-1100 Harvard University University Hall Cambridge, MA
Looking closer at the actual XML used in the example, you can see how each item represents a marker. Using the title fields, you determine what appears at the top of the inside of the marker when the logo is clicked. The link fields appear at the bottom of the marker and load the URL in another window. The address and cityState fields are used to geo-code the location of the marker. They are also displayed, with a phone number and description inside the marker.
Summar y This chapter introduced you to the more advanced classes and methods available in the Ajax API. To get ready for building the mashup in the next chapter, here is what you learned: ❑
There are two methods for adding markers. addMarker() places a simple marker on the map while addOverlay() enables you to add a customizable HTML marker. You can also add an image as a marker using the YImage class.
❑
Tools can help you save time by adding prepackaged button interfaces to your map. The tools you can add will let the user change map type, pan with precision and zoom with or without a slider feature.
❑
Very little coding is needed to add the dynamic feature of overlays. The YPolyline overlay class can connect specified points on the map with a line in the style of your choice. You can also reference common GeoRSS XML files to draw points in an overlay on the map.
61
7 The Ajax Mashup The goal of this chapter is for you to build an Ajax maps mashup using the Ajax API and Flickr. To do this, you will also do the following: ❑
Establish an idea for your mashup and plan out the key details and development approach
❑
Learn how to retrieve external data from the Flickr API and display it on the map
❑
Create links that center the map on a photo stored in Flickr
Time to Mash Up Now that you have learned all the methods and classes of the Ajax API, it’s time to build a mashup. As with the other APIs featured in this book, this chapter will guide you through building a mashup with a data source and the map API.
The Big Idea Way back at the beginning of the book, you discovered just a few of the most popular sites that are the subject of mashups. Perhaps the granddaddy of them all is Flickr. You will see more Flickr mashups than almost any other kind, and for good reason. As a leading photo collection and repository, Flickr serves up a wealth of its users’ photos. As stand-alone visual interfaces, maps themselves can be more than sufficient in captivating your user. Displaying photos taken by any one of Flickr’s millions of users, on subjects ranging from newborn babies to mountaintops, is just as good. Combining the two, displaying photos exactly where they were taken in the world against an interactive map, is even better. In this chapter you will build a mashup that will enable you to display your photos as markers on the Ajax-generated Yahoo! map. Using the geo-tagging data widely available from Flickr, these image markers will be positioned precisely where you took the photo.
Chapter 7 Believe it or not, you already possess the map skills to do this. What you will learn in this chapter and by doing this mashup is how to work with the Flickr API and display the data it returns on the map.
Planning an Approach As with any application, planning an approach is important. It helps to know the APIs and web services you are working with very well, but having completed the previous chapters on the Ajax API, you should have all you need to work with the map. Later in this chapter you will examine the Flickr API, how the request is constructed and what data to expect to have returned upon a successful request. Before coding, it is always good to lay out your objectives and then determine how best to achieve those tasks. Begin with thinking out what your application should achieve. Through the rest of the chapter, you will see how the following steps are developed into the mashup:
1. 2. 3. 4. 5.
Display the map initially. Position the map and set its view type accordingly. Call the external API and retrieve the data. Give the user the ability to navigate through the data. Display the data as markers on the map, based on user selection.
You should find it easy to replicate this pattern of user interaction with other APIs and web services.
The Flickr API Flickr lets you post and share your photos with the public via a very popular website at www.flickr.com. Since Flickr is a property of Yahoo!, the support for its API is similar to that of the Yahoo! Maps APIs. Like them, the Flickr API and its documentation are supported by the Yahoo! Developer Network (YDN). To check out the web service firsthand, visit http://developer.yahoo.com/flickr/ for the most up-todate documentation and news on the API.
How Flickr Photos Are Geo-Tagged As map mashups using Flickr grew, it became apparent that Flickr’s users needed an easy way to define the places their photos were taken. Flickr added an interface so its users could define the latitude and longitude of a photo as it was added to their photo collection or a specific photoset of theirs. The interface chosen to enable this form of data entry is none other than a mashup with the Yahoo! Maps Ajax API (shown in Figure 7-1). That’s right, using the very API you are learning about in this book, Flickr put together a simple drag-and-drop application that lets users upload photos and then place those photos on a map. Once a photo is placed on the map, the corresponding latitude/longitude points are saved as attributes of the photo. This precise geo-tagging means that mashups built between maps and Flickr can display photos across the world, on or near the locations at which those photos were taken.
64
The Ajax Mashup
Figure 7-1
As you will see in the coming Flickr API methods, the latitude and longitude of a photo, when available, can be collected with a field called geo. There is actually a set of method calls specific to the management of the geo-tags for a specific photo. Geo-tagging photos is a natural process, as every photo taken can be associated with a location. The performance of this real-world mashup, between Yahoo! Maps APIs and Flickr, is proof of how effective working with photos and maps can be.
API Authentication Flickr has an authentication process different from most YDN-supported APIs and web services. You must receive authentication for your mashup from Flickr in the form of an API key. You can apply for and receive the key at http://www.flickr.com/services/api/misc.api_keys.html. The current application requires your name and e-mail, declaration of a commercial or non-commercial usage, and a description of how you plan to use your mashup. You must also acknowledge the usage terms of the Flickr API. You will likely be given an API key immediately upon submitting your application. You will need the API to complete the mashup for this chapter. As you learn the steps to piecing together a call to the Flickr API, the following text will appear as an indication of where you need to plug in your own API key: {your_flickr_api_key}
65
Chapter 7
API Methods Like the Maps APIs, Flickr offers a wide set of very functional yet simple API methods. Each method is responsible for letting you, the developer, interact with Flickr in important ways. The methods can be organized into categories based on functionality. The most relevant methods for mashing up photos and their data with maps will be reviewed in this chapter to give you a solid overview of the capabilities of the API. Flickr supports its API calls through a very useful and effective documentation site. The documentation is actually a living, breathing interface that enables you to test each API call and view the responses. By default, the documentation crafts the method call as a REST request and returns very readable XML.
flickr.photos.search This popular Flickr method call returns a list of photos based on given parameters. It effectively enables you to search through nearly all of Flickr’s photo repository. Since Flickr users can mark their photos visible only to certain users, this call requires certain authentication or permissions to reveal all photos. The only required parameter for this call is api_key. A useful mashup parameter is the optional extras. Here you can add the field geo, which will return the photo’s latitude and longitude as defined by the user. Another useful parameter for this call is tags, which enables you to search for photos based on the tag the uploader entered. This is often a precise means of filtering out photos you want to display. The fully constructed flickr.photos.search REST call looks like this: http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={your_flic kr_api_key}&tags=yahoo+hack+day&extras=geo
You can see the parameter in which to plug in your api_key. The searching tags yahoo+hack+day instruct the search to return photos tagged with those words. Finally, the extras=geo parameter will return the latitude and longitude of each photo, where available. Copying and pasting the preceding into your browser will result in XML that an application can parse. An excerpt of such a response to this method call looks like this: ... ...
Among the attributes of this actual photo in Flickr, you can see the latitude and longitude. As you will see later in this chapter, parameters from a call like this one will be used to place a marker on the map with the specified coordinates.
66
The Ajax Mashup flickr.people.getPublicPhotos As you can tell by the get in the method name, this call is positioned to return certain values based on given parameters. The getPublicPhotos method will return all public photos posted by a specific user. This is the method that will be used in this chapter’s mashup, setting you up to display your own photos on your own map. This call requires two parameters. The api_key, once again, is the key you were given when you applied for access to Flickr’s APIs. The other required parameter is the user ID of the user whose photos you want to display. This call is ideal for requesting your own photos, and so the user ID you define will likely be yours. Additionally, adding the geo field will add the latitude/longitude attributes to the photo data. A successful request looks like this: http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&format=js on&api_key={your_flickr_api_key}&user_id={your_flickr_user_id}&extras=geo
The XML data returned by this call, after you substitute the necessary values, will be similar to that of the flickr.photos.search call. Once again, the photos geo-tagged by the user you are requesting will appear with latitude and longitude data.
Understanding JSON JSON stands for JavaScript Object Notation and is a simplified version of XML. JSON was developed to be a much more lightweight and thus faster way to pump data into JavaScript. Its popularity has grown with the increase of Ajax-built web pages. As with XML, data in JSON are organized easily and are human-readable, meaning they can be understood onscreen without code interpretation. Favorable articles on JSON cite that it “cuts the fat” out of XML by removing the cumbersome tag syntax. Equally beneficial is its ability to be loaded directly into JavaScript. As you will see in later sections, JSON has a callback ability, which lets it virtually parse itself by calling a defined function in JavaScript when it is returned.
Making a JSON Request A JSON request is constructed similarly to a typical REST request. It is important to note that an API needs to provide specific support for JSON, but unfortunately most still do not. Flickr, however, has added strong support for JSON and that makes map mashups much easier and more accessible. In a familiar REST response URL, adding the parameter &format=json will instruct the API to respond with JSON: http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={your_flic kr_api_key}&tags=yahoo+hack+day&extras=geo&format=json
To make the request in JavaScript, the URL must be embedded in a JavaScript src tag, much as you load the classes of the Ajax maps API.
67
Chapter 7 Instead of XML, this request will return a string of text looking like this: jsonFlickrApi({“photos”:{“page”:1, “pages”:17, “perpage”:100, “total”:”1679”, “photo”:[{“id”:”259464940”, “owner”:”...”, “secret”:”...”, “server”:”45”, “title”:”The Mosh pit at Yahoo!”, “ispublic”:1, “isfriend”:0, “isfamily”:0, “latitude”:37.418363, “longitude”:-122.025135, “accuracy”:”16”}]}, “stat”:”ok”})
As you can see, most of the XML “fat” has indeed been removed. These returned data are still easy to read and, even better, in a format similar to a JavaScript array, so they can be parsed much more smoothly.
Using the JSON Callback Looking at the syntax returned with JSON, you can see that the string begins with a defined method name. By default, the Flickr JSON response starts with the function name jsonFlickrApi. When JavaScript loads this response, it will automatically call the function defined and pass the data of the response itself. To properly handle a JSON response, you will need to code a function, matching that in the response, to receive the response data. Using the default of jsonFlickrApi, here is how that function may look in your code: function jsonFlickrApi(rsp){ if (rsp.stat == “ok”){ alert(rsp.photos.photo.length); } }
This function will execute when the JSON is returned. The response data will be passed to jsonFlickrApi as the object rsp. Within the function is a condition checking for the property of the JSON response stat. If it has the value ok, the JavaScript will execute an alert with the number of photos in the response. You can see how rsp, the datum from the JSON response, is handled as an array. This means that JSON results can be looped through easily as well. If you want or need to change the default function in the JSON response, you can add the parameter jsoncallback= followed by the desired function name. Additionally, if you are looking to get the JSON data back without a defined callback function, you can use the parameter nojsoncallback=1.
Build the Mashup It is now time to put it all together and build your mashup of the Yahoo! Maps Ajax API and Flickr. You will need the following information from Yahoo! Maps and Flickr to complete this mashup:
68
❑
Your Yahoo! Maps application ID
❑
Your Flickr API authentication key
❑
Your Flickr user ID (You can also look up another user’s ID, but working with your own photos should be more fun.)
The Ajax Mashup If you haven’t already, I suggest that you upload some photos of your own to mash up. In uploading the photos, be sure to geo-tag all the ones you would like to mash up. The easiest way to do this is by using the Organize tab after you have uploaded your photos. There you will find a map to which you can drag your uploaded photos.
Code the Mashup This mashup will enable you to display your photos on a map. You will also supply navigation so that your users can zoom in on each photo you display.
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Open the file ajax_mashup.htm and save it as ajax_flickr_mashup.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
Yahoo! Maps Mashups, Ajax API Flickr Mashup #mapContainer { width: 700px; height: 400px; float: right; } var map = new YMap(document.getElementById(‘mapContainer’),YAHOO_MAP_REG); map.drawZoomAndCenter(“Lincoln, NE”, 15); function jsonFlickrApi(rsp){ if (rsp.stat != “ok”){ alert(‘something broke!’); return; } for (var i=0; i New Window function newWindow(url) { launchWindow = window.open(url, “newWin”, “width=800,height=600”) } Launch Window
Instead of the URL being coded inside the function, it is now passed into the function as the url parameter. This is a much better practice, as it further generalizes the function should you want to call it in other places and have it load different URLs. In the JS-Flash API, internal functions of the API are exposed to you when the classes are imported as methods. These methods can be called against the map container instance to control the map. Methods are so important in working with the API that each API featured in this book has a chapter dedicated to reviewing the methods available. As you learned with functions, you can pass parameters with methods like address or latlon to change the map’s location.
Events Events are an important and often overlooked feature of JavaScript. They represent user interactions or code occurrences that can be further handled by additional functions. Events are executed by means of event handlers. An event handler is the script that executes when an event occurs. An example of an event is a user bringing the mouse over an element, like an image. The user action will fire an event called onMouseOver. The event handler would look something like this:
This code will call the newWindow function, passing the image as a parameter when it is rolled over with the mouse.
78
The JS-Flash API Events play a big role with the JS-Flash API, and are based much more on code occurrence than user interaction. Working more with data and code execution, events can be fired to signal when data have been sent or received or when certain code is completed in the application. The maps API dispatches many events tied to map activity, including startPan, changeZoom and onStartGeocode. Each of these refers to an activity of the map as it happens. Setting up event handlers for these events lets you call other functions based on map occurrences.
Fundamentals of CSS and DHTML CSS (Cascading Style Sheets) is a means of defining style for laying out HTML in the browser. The standard was designed to address the layout and appearance limitations of native HTML. Style sheets let you define sets of styles as classes within a style tag. These styles can be referenced and applied throughout your HTML. Within the sets of styles you will usually find properties like color, width, height, font-weight, font-style and several other style attributes. Style sheets can be coded within the head tag of the HTML. If you are looking to apply the same style classes to multiple HTML documents, you can centralize the CSS in its own file and then reference it from any HTML document. This enables you to maintain one file for your entire site or web application. While styles can be referenced within everyday HTML tags, they are more frequently used with tags like SPAN and DIV. These tags are part of DHTML (Dynamic HTML), a slight modification to the language
that allows for more dynamic handling of web content. Both tags build containers, elements that exist on the web page outside, within, over or outside the boundaries of regular HTML. These containers rely heavily on CSS for positioning and appearance. The syntax of CSS can be tricky, but is easy to get the hang of. This example shows how CSS and DHTML are used to position the DIV container for the JS-Flash API: #container { position: absolute; left: 200; top: 200; border-style: ridge; border-color: #FFFF00; border-width: medium; } This is a positioned DIV container.
79
Chapter 8 The combination of CSS and DHTML in this sample will create a small rectangle that appears 100 by 100 pixels from the top-left corner of the browser. The rectangle has a sharp border and displays the text within. As you can see, all the style sheet properties are inherited when the DIV tag references container in its ID attribute. See Figure 8-1.
Figure 8-1
As you will see in the next chapter, the map instance of the JS-Flash API will appear within a DIV tag much as in this example.
Benefits of the JS-Flash API The single greatest benefit of developing with the JS-Flash API is the ability to include a Flash-generated map without knowing Flash. This means your users will enjoy the smooth transitions and enhanced visual features that Flash provides. The map tiles appear in a precompiled SWF that is loaded when you include the JavaScript library. By using JavaScript, CSS and DHTML, you can easily position and control the map. Another benefit is the JS-Flash API’s ability to serve as a great transitional API. Its position in this book is no accident. Understanding the Ajax API really teaches you how to work with the Ajax API and include the JS-Flash API. However, being able to work with the JS-Flash API will set you up to code with the AS-Flash API later in this book.
80
The JS-Flash API
Summar y This chapter introduced the JS-Flash API and the following key concepts: ❑
Flash-generated maps feature more enhanced map transitions, particularly for zooming from one level to another.
❑
Working with the JS-Flash API requires no knowledge or prior use of ActionScript or Flash development. A precompiled SWF, which displays the Flash-generated map, becomes available to your web page when you include the JS-Flash library.
❑
An external JavaScript file with the extension .js can be included in HTML and used as a JavaScript library.
❑
CSS and DHTML are used to stylize and position various elements on a web page. The JS-Flash API map instance will live within a DIV tag on your page.
81
9 Get Started with the JS-Flash API It is time to get immersed in JavaScript and start developing with the JavaScript-Flash (JS-Flash) API. This chapter discusses ❑
The steps for getting an application ID — in case you don’t have one yet
❑
The software requirements for developing with the JS-Flash API
❑
How to embed the API and its library of classes
❑
Setting the initial properties of the map when it loads for your users
Get an Application ID If you have already completed one of the other sections of the book, be it the JS Flash API or the ActionScript-Flash (AS-Flash) API, then you will already be familiar with these steps. Otherwise, this step is a critical one and needs to be completed so you can properly develop with the map APIs. The first step to achieving mashup greatness is to register an application ID with the Yahoo! Developer Network. This free ID is a string of your choice, used by YDN to track usage of all Yahoo! web services. Since the ID is tied to your Yahoo! user ID, it also enables you to track your own API’s usage and gauge the total traffic it has generated. If you already have registered an AppID, you can still register a new one for each API you will use. Here are the steps to getting your Yahoo! AppID:
1.
Open your browser and go to http://api.search.yahoo.com/webservices/ register_application.
2.
You may be prompted to log in with your Yahoo! user account. If you do not have an account, you will need to get one as instructed.
Chapter 9 3. 4. 5.
After logging in, your username will be displayed next to the field labeled “Your Yahoo! id.” Enter your desired application ID (AppID) next to “Requested application id.” You can provide an additional e-mail at “Alternate email (optional).” By default, the e-mail you provided with your Yahoo! account will be associated with your AppID. See Figure 9-1.
Figure 9-1
Write down or save the AppID somewhere. You will need it later in this chapter.
Software Requirements As mentioned in the last chapter, one of the key benefits of the JS-Flash API (as well as the Ajax API) is that it does not require you to buy or own coding or server software. While you do need a hosting account or access to a remote server to share your mashup with the world, to develop locally nothing is required. If you are not a seasoned web developer, using Notepad or your favorite text editor will work just fine. Many web developers and front-end engineers do, however, prefer to use an IDE (integrated development environment). There are several good ones to choose from, including Adobe (formerly Macromedia) Dreamweaver and Eclipse. You can get a trial version of Dreamweaver at www.adobe.com. Eclipse, which is distributed free under certain licenses, is available at www.eclipse.org.
84
Get Started with the JS-Flash API Developers find working with IDEs an improved coding experience for many reasons. One of these is file management. Dreamweaver and Eclipse feature ways to manage your files alongside the coding window. This enables you to open and move around all the files within your site. Dreamweaver adds FTP ability, a way to actually upload your files right to the server as you code. The other great benefit, which helps coders at all skill levels, is code hinting. This is a special feature that, based on the language you are coding with, allows the IDE to colorize specific elements of the code. It can also offer up a list of properties and methods available as you type an object or variable.
Transitioning Between APIs Having completed the Ajax API chapters, developing many examples and a full-fledged mashup, you already have a solid understanding of building Yahoo! Maps–based mashups. As you transition from Ajax-generated maps to Flash map APIs, by way of learning the JS-Flash API, you may note some key differences in form and functionality. While the JS-Flash API benefits from being included in your HTML in a nearly identical way to the Ajax API, some key differences do exist. Those differences will be pointed out in this chapter and the next to ease the transition between APIs. The slight differences you will observe include different names for classes and methods as well as different means of creating objects. As you move into the basic- and advanced-feature chapters in this book about the JS-Flash API, you will be introduced to many new tools, widgets and marker types that become available with the Flash APIs. Also new will be the custom SWF classes, consisting of marker, overlay and tool capabilities that can be completely customized by you.
Integrating the JS-Flash API This chapter features two examples that will walk through the simple steps of integrating the JS-Flash API with your HTML. The web pages you build here will become the foundation of each sample and mashup you build over the next few chapters. You will cover how to include the API as well as how to set initial parameters. Keep in mind that all methods and classes discussed here will be covered in much more detail in subsequent chapters.
Including the API Classes Unlike some of the other map APIs covered in this book, the JS-Flash API is not a component. To include the API in your HTML, you simply need to include the API library in your document. You do this by defining the library src URL in the JavaScript tag within your HTML document. This includes all the latest classes and methods that will enable you to display and control the map within the API. The first exercise will set you up with the baseline code you will use throughout the next several chapters.
85
Chapter 9 Try It Out
Add the JS-Flash API
These steps will explain how to add the JS-Flash API to your web page.
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Go to File ➪ New and create a new (HTML) document. Save the file as jsflash_mashup.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
Yahoo! Maps Mashups, JS-Flash setup #mapContainer { width: 800px; height: 400px; } // Create a map object and position the map centered on a given address // Include your application ID. var map = new Map(“mapContainer”, “WroxBook”, “London”, 12);
4.
In the fifth line of code, where you are defining the JavaScript source for the JS-Flash API library, replace the WroxBook AppID parameter with your own YDN AppID.
5. 6.
Replace the AppID in the line fourth to last, where the map instance is created. Save the file and load it into your browser. You can also upload it to your web server at this time to view it. Refer to Figure 9-2.
You should see the Yahoo! Maps JS-Flash API load in your HTML document. The map should be loaded displaying regular map tiles of London, England, at a zoom level of 12 (about country level).
86
Get Started with the JS-Flash API
Figure 9-2
How It Works By defining the JavaScript source using the JS-Flash API library, you have made all the classes available to your web page. You set the src attribute of the JavaScript tag. This effectively imports or “pulls in” the very latest fields available, under the version you specified in the URL. The next step is to create a space on your web page, a container for displaying the Flash-generated map tiles. Using the style tag, you create a style class called #mapContainer. This is set to have a width of 800 pixels (800px) and a height of 400 pixels (400px). In the future, these dimensions can change based on the viewable area of the map you desire in your web page. Within the body tag of your HTML, you add a div tag with the ID mapContainer. This will assign the properties of the mapContainer class in the style tag to the DIV you are creating. Effectively, this will size the DIV to 800 by 400 pixels and ultimately fill the space in with a map of that size. Still within the body tag, additional JavaScript here will actually trigger the map to turn on with some example properties. This section of code deserves close review, as it is your first usage of the JS-Flash API code itself:
87
Chapter 9 // Create a map object and position the map centered on a given address // Include your application ID. var map = new Map(“mapContainer”, “WroxBook”, “London”, 12);
You create the map by instantiating (creating an instance of) the Map object. When creating the Map instance, you need to pass into the object the container to load the map in. By specifying the mapContainer, this tells the JS-Flash API library where to load a new map and its tiles. Additionally, your AppID and initial map location and zoom level are passed into the Map constructor. The following are some notes to help you understand the transition between the Ajax and JS-Flash APIs: ❑ ❑
The Map class used to construct the map instance is similar to the YMap class in the Ajax API. You can set the initial address (or latitude/longitude as shown in the next example) within the Map class constructor.
As I mentioned earlier, you have built the foundation for every JS-Flash API example to come with this exercise. For the remainder of this chapter, as well as the next three chapters, you will be using this code. Although it is very basic, you must understand the order in which it is placed and executed.
Setting Initial Map Parameters While most of the methods of the JS-Flash API will be covered in each of the next two chapters, this example will get you started on setting initial parameters for the map. These values will be used when the map originally renders, giving your users their first view of the location around which you are building your mashup. You have a head start, actually, as the example you just completed already does some initial setting. In the next exercise you will add simple functionality to your code that will enable you to center on latitude/ longitude and set the initial map view type (the type of tiles that will load).
Try It Out Set Default Parameters for the Map 1. Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. 2. Open the file jsflash_mashup.htm and save it as jsflash_mashup_settings.htm. 3. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view): Yahoo! Maps Mashups, JS-Flash settings example #mapContainer { width: 800px; height: 400px;
88
Get Started with the JS-Flash API } // Create a latitude/longitude object var latlon = new LatLon(-33.857017,151.209623); // Create a map object and position the map centered on a given latlon // Include your application ID. var map = new Map(“mapContainer”, “WroxBook”, latlon, 6); // Change map view type to satellite map.setMapViewType(“satellite”);
4.
In the fifth line of code, where you are defining the JavaScript source to the JS-Flash API library, replace the WroxBook AppID parameter with your own YDN AppID. Also, replace the AppID in the line where the map instance is created.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. See Figure 9-3.
Figure 9-3
89
Chapter 9 You should see the Yahoo! Maps JS-Flash API load in your HTML document. The map should be loaded displaying satellite map tiles of Sydney, Australia, at a zoom level of 6 (about state/province level).
How It Works The upper part of this code is pretty much identical to that of the first example in this chapter. You are becoming quite familiar with this code by now. It is responsible, once again, for including the JS-Flash API library of classes in your web page. The mapContainer has stayed the same, as it creates a holder in which the map will ultimately be displayed. Consistent with the first example, too, is the way the map object is instantiated. The YMap class is passed the div location, in this case the mapContainer, to load the API. The difference starts when the latitude/longitude coordinates are defined. Using the LatLon class, the latitude/longitude object will tell the map where to center when it initially loads its tiles. The JS-Flash API (as well as the other Yahoo! Maps APIs) needs to have the latitude/longitude coordinates turned into an object in order to process them. The LatLon object serves this purpose by creating a JavaScript variable called latlon. Most developers don’t know latitude/longitude coordinates offhand, so the address option used in the first example may be a bit easier to leverage. Once the latlon object is created, it can be passed as a parameter of the map constructor along with the desired initial zoom level. This will resolve the coordinate, center the map on that location and call for tiles at the specified zoom level. The last action taken in this example is to define the type of tiles used. Regular tiles will show up by default. In the example, by using setMapViewType against the map instance, you are defining that satellite tiles will be showing initially. The following are some notes to help you understand the transition between the Ajax and JS-Flash APIs: ❑
The LatLon class is the equivalent of the YGeoPoint class in the Ajax API.
❑
The method setMapViewType is similar to the setMapType method in the Ajax API.
❑
To load satellite tiles, the JS-Flash API uses the simplified property satellite, rather than the lengthier YAHOO_MAP_SAT property of the Ajax API.
The next chapter will discuss these methods and much more in detail. You now have a very strong foundation for building your JS-Flash maps mashups. You are about to do a whole lot more with this API and Yahoo! Maps.
Summar y After reading this chapter, you are well on your way to mashing up the JS-Flash API and have done the following:
90
❑
Obtained a YDN AppID
❑
Become familiar with Yahoo!’s terms of use for the API
Get Started with the JS-Flash API ❑
Gained more awareness of the subtle differences between the way the Ajax API and the JS-Flash API are coded
❑
Set up your potentially free development environment for working with and testing web pages with the JS-Flash API embedded
❑
Added the JS-Flash API libraries to your web page
❑
Built your first JS-Flash-based map application featuring simple methods such as those for setting the map’s address, view type and zoom level
91
10 JS-Flash API Basics In the last chapter you learned how to set up the JavaScript-Flash (JS-Flash) API. You started developing JavaScript-based applications and implemented some simple API methods. In this chapter, you will build on that knowledge and learn the following: ❑
How to use methods that control zoom level, the type of tiles the map displays and the positioning of the map
❑
What data the basic get methods return and how they can be used to further your application
❑
How to listen for and use events related to the basic methods of the API
Basic API Methods As you have already seen in earlier examples, methods are the building blocks of working with an API. These are the exposed functions that let you call for specific functionality and control against the instance of the map API you are working with. The JS-Flash API methods are nearly identical to those in the ActionScript-Flash (AS-Flash) API, which is covered in Chapters 13–17. While different in their naming conventions, they are fundamentally the same as the Ajax APIs. While the parallels will not be pointed out in this chapter, you should note the similarities, as it will make it easier for you to adapt to one API from another.
Map Zoom Methods and Events The Ajax API offers a set of methods and events to programmatically control zooming. These methods can be tied to user interaction, such as clicking a button outside the map to change the zoom level of the map tiles being displayed.
Chapter 10 setZoomLevel() setZoomLevel() sets the zoom level of the map. It accepts one parameter, a number that is the value of
the zoom level you want to change the map to. The zoom level can be set to a number between 1 and 16: mapInstance.setZoomLevel(zoomLevel);
In this sample, zoomLevel is set to 6: myMap.setZoomLevel(6);
The next chapter will introduce you to a built-in zooming user interface called NavigatorWidget. This tool features predesigned buttons and code that will add instant zooming control to your map with minimal coding.
zoomStart, zoomEnd The zoom events zoomStart and zoomEnd are dispatched when the map zoom level changes. Here is how to listen for the zoomStart and zoomEnd events: //Listen for the zoomStart event mapInstance.addEventListener(Map.EVENT_ZOOM_START, onZoomStart); //Listen for the zoomEnd event mapInstance.addEventListener(Map.EVENT_ZOOM_END, onZoomEnd);
Once the events are picked up, the JavaScript function specified will be called to carry out the event. The two functions shown here will display the starting zoom level and ending zoom level respective to the events they are carrying out: //Display the starting zoom level function onZoomStart( eventData ) { alert(eventData.startZoomLevel); } //Display the ending zoom level function onZoomEnd( eventData ) { alert(eventData.endZoomLevel); }
getZoomLevel() get methods work very efficiently in the API. Since the value is already set, most likely by your calling their set method counterparts, all the API needs to do is return the value to you. For development, get
methods are very easy to implement, as they require no parameters to operate. As you code your application, you will find that get methods make development much easier. Rather than make sure your code “remembers” what values have been set throughout your application’s operation, you can call a get method anytime and have the latest value. The get methods also help with user interface implementation. You will need a starting point, a default value to position your user interface elements. The get methods will provide those data.
94
JS-Flash API Basics The getZoomLevel() method lets you obtain the current zoom level of the map. It can be used to adjust a custom zoombar or zooming interface that you have created. As you will see in the next chapter, knowing the current zoom level is important when you are using overlays and other custom features of the API. mapInstance.getZoomLevel () ;
The following is an example showing how the method works if the map is set to a zoom level of 5: var currentZoomLevel = myMap.getZoomLevel(); alert(currentZoomLevel); // Outputs: 5
Now that you have learned the set and get methods, as well as the associated event for changing the zoom level, it is time to put it all together.
Try It Out
Change the Map View Type
In this exercise you will build a form that lets your users change the zoom level of a map and display the new zoom level after the map zooms. You will do this by building a simple form below the mapContainer.
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Open the file jsflash_mashup.htm and save it as jsflash_mashup_zoomLevel.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
Yahoo! Maps Mashups, JS-Flash setZoomLevel #mapContainer { width: 800px; height: 350px; } New Zoom Level: Event Output:
95
Chapter 10 // Create a map object and position the map centered on a given address // Include your application ID. var map = new Map(“mapContainer”, “WroxBook”, “Venice, Italy”, 12); // Changes zoom level based on value entered in forms function zoomLevel() { map.setZoomLevel(document.apiForm.newLevel.value); } // Listens for zoomEnd event and calls onZoomEnd map.addEventListener(Map.EVENT_ZOOM_END, onZoomEnd); // Displays new zoom level in form when event is fired function onZoomEnd( eventData ) { document.apiForm.eventDisplay.value = “The zoomLevel is: “ + map.getZoomLevel(); }
4.
In the fifth line of code, where you are defining the JavaScript source for the JS-Flash API library, replace the “WroxBook” AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. See Figure 10-1.
Figure 10-1
96
JS-Flash API Basics The map should be loaded displaying regular map tiles of Italy at a zoom level of 12 (about country level). Beneath the map are some form elements. Changing the value in the first text field and clicking Zoom should change the zoom level. The text area below that, labeled “Event Output,” will display the new zoom level as it changes.
How It Works After importing the JS-Flash API library, the classes become available to your JavaScript and HTML. The mapContainer style defines the size and placement of the map. The div tags will display the map as it is rendered and inherit the style sheet properties of the mapContainer class. The apiForm is written in HTML and will do two things. First, the form contains a text input field and a button. These two elements together will allow the user to enter a new zoom level and submit it. This will ultimately change the zoom level of the map. The other purpose of the form is to create a space for displaying event data related to the example, as it occurs. This space is a text area that will display the map’s new zoom level when the zoom event has fired. The zoom level changes when the Submit button is clicked within the form. The onClick() event handler calls the zoomLevel function. Within this function, the setZoomLevel method is called against the map instance. JavaScript references the user-entered zoom level and that is passed as the new zoomLevel parameter. You use the addEventListener method to listen for the zoomEnd event. That event is fired from the map when the zoom change is complete. The event listener then calls the onZoomEnd function, defined to carry out the event. This function will populate the text-area element eventDisplay, which is inside the apiForm, with the new zoom level. This value is attained by calling the getZoomLevel() method against the map instance. This example is designed to be easily replicated for each set of methods and events to follow in this chapter. By simply customizing the form to let the user enter relevant data, you will be able to call other methods against the map API’s instance. The event-display part of the example is very flexible. All you need to do is modify the event being listened for, as well as the data being displayed, and you are all set to test other methods and events together.
Map Type Methods and Events The JS-Flash API considers the map view type to be the type of tile being loaded. You may recall an example in the last chapter that set the map view type so the map would display satellite tiles. The JSFlash API supports three types of tiles: regular, satellite and hybrid. Hybrid tiles are a combination of regular tiles and satellite tiles.
setMapViewType() The setMapViewType() accepts one parameter, the map view type you want to change the map to. Here is how the call should look: var newMapViewType = “satellite”; myMap. setMapViewType (newMapViewType);
97
Chapter 10 This call will change the map type to satellite, refreshing the map with new tiles reflecting its existing location. In the next chapter you will discover the satelliteControlWidget, a prepackaged interface that achieves the same result.
mapTypeChanged This event is broadcast when the map view type — the type of tiles loaded in the map — is changed. Here is how to listen for the mapTypeChanged event: //Listen for the mapTypeChange event mapInstance.addEventListener(Map. EVENT_MAP_TYPE_CHANGED, onMapViewTypeChanged);
Once the events are picked up, the JavaScript function specified will be called to carry out the event. The function shown here will display what the map view type has changed to: //Display the new map view type function onMapViewTypeChanged ( eventData ) { alert(eventData.view); }
getCurrentMapViewType() You want to call getCurrentMapViewType() to determine what tiles the map is currently displaying. This is useful if you have created your own buttons that let your users toggle between map view types. You may also include some effects in your application that activate depending on what layer is currently being displayed. mapInstance.getCurrentMapViewType();
This method could reveal that, based on a change to the initial setting or through user interaction, the map is now displaying satellite tiles instead of its default map tiles: var currentMapViewType = map.getCurrentMapViewType (); alert(currentMapViewType); // Outputs: “satellite”
getMapViewTypes() getMapViewTypes() is most useful if you want to create your own map view buttons. Letting users
choose their map view can add a hint of customization to it. Not to mention that being able to display satellite images of the world, from space all the way down to street level, is quite an enticing feature that will draw users to your mashup. mapInstance.getMapViewTypes() ;
This method is a little more complex than the other basic get methods, as it returns an array. That means that the data returned by this method appear in something like a list.
98
JS-Flash API Basics var mapViewTypes = new Array(); mapViewTypes = map.getMapViewTypes(); alert(mapViewTypes); // Outputs: “map, satellite, hybrid”
Try It Out
Change the Map Zoom Level
In this exercise you will build a form that lets your users change the map view type of a map and display the map view type when it changes. You will do this by building a simple form below the mapContainer.
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Open the file jsflash_mashup.htm and save it as jsflash_mashup_mapViewType.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
Yahoo! Maps Mashups, JS-Flash setZoomLevel #mapContainer { width: 800px; height: 350px; } Map View Type: MapSatelliteHybrid Event Output: // Create a map object and position the map centered on a given address // Include your application ID. var map = new Map(“mapContainer”, “WroxBook”, “Moscow”, 10, “hybrid”);
99
Chapter 10 // Changes map view type based on value entered in form function mapViewType() { map.setMapViewType(document.apiForm.newType.value); } // Listens for zoomEnd event and calls mapTypeChanged map.addEventListener(Map.EVENT_MAP_TYPE_CHANGED, onViewTypeChange); // Displays new map view type in form when event is fired function onViewTypeChange( eventData ) { document.apiForm.eventDisplay.value = “The current map view type is: “ + map.getCurrentMapViewType(); }
4.
In the fifth line of code, where you are defining the JavaScript source for the JS-Flash API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. See Figure 10-2.
Figure 10-2
100
JS-Flash API Basics Figure 10-2 shows the Yahoo! Maps JS-Flash API loaded in your HTML document. The map should be loaded displaying hybrid map tiles of Moscow at a zoom level of 10 (about city level). Beneath the map are some form elements. Changing the value in the dropdown should change the map view type. The text area below that, labeled “Event Output,” will display the new map view type as it changes.
How It Works As in the previous example, the initial code in the exercise sets the placement of and instantiates the map object. This time, the map view type is passed when the map object is created, setting it to load hybrid tiles. The dropdown form element calls the mapViewType() JavaScript function through the onClick event handler. Within this function, the setMapViewType method is called against the map instance, passing the newly selected map view type. Once the map view type is changed, the mapTypeChanged event fires and its view property is displayed in the form’s text area. This will relay the newly modified map view type.
Map Positioning Methods and Events This set of basic methods enables you to control the positioning of the map. In addition, these methods let you toggle certain built-in functionalities of the API.
setCenterByAddress() The setCenterByAddress() method accepts two parameters, address and duration. A successful address is a full street address with city, state and ZIP. (Certain major metropolitan areas will work as well.) The address is converted by the API geo-coder into a latitude/longitude and the map reloads its tiles and centers on that value. To handle this transition smoothly, you can use the duration parameter to tell the API how long it should take to pan from its current position to the new one you have defined. The duration parameter is the number of milliseconds the map will take to pan. mapInstance.setCenterByAddress(address, duration);
This example shows what the code would be like to change the address to Casablanca and pan from its current location for 300 milliseconds: var address:String = “Casablanca” var duration:Number = 300; myMap. setCenterByAddress(address, duration);
setCenterByAddressAndZoom() Developers looking to change the map location and zoom level in one shot have some options. setCenter ByAddressAndZoom() is a very capable method and combines the power of setCenterByAddress() with setZoomLevel().
101
Chapter 10 The order of operation for this method is as follows:
1.
The method is called:
mapInstance.setCenterByAddress(address, zoomLevel, duration);
2.
The address is geo-coded, firing either EVENT_MAP_GEOCODE_SUCCESS or EVENT_MAP_GEOCODE_ERROR.
3. 4. 5.
The map pans based on the duration, in milliseconds, defined in the duration parameter. The map centers on the resolved latitude/longitude coordinate. The map zooms in to the level defined in the zoomLevel parameter.
Common usage of this method looks like this: var address:String = “Casablanca” var zoomLevel:Number = 6; var duration:Number = 3000; myMap. setCenterByAddress(address, zoomLevel, duration);
The first three lines declare and set the variables to pass inside the method. Finally, the method is called. Note that zoomLevel is placed between address and duration.
mapGeocodeSuccess, mapGeocodeError There are some useful events fired when setCenterByAddress() and setCenterByAddressAndZoom are called. EVENT_MAP_GEOCODE_SUCCESS is dispatched when the API has successfully geo-coded the address passed in and has resolved it as a latitude/longitude coordinate. If the address entered cannot be geo-coded, then the EVENT_MAP_GEOCODE_ERROR is broadcast. If the latter should happen, an array of suggested addresses will be sent as a data object with this event along with the originalAddress. You can use the message attribute returned with this event to alert users to try a new address or select from a suggested one. Since international geo-coding recognizes so many variations of cities, it is difficult to generate a geo-code error event.
setCenterByLatLon() If you know the latitude/longitude coordinate on which you want to center the map, you can use setCenterByLatLon(). A major benefit of this method is that it executes much more quickly than setCenterByAddress(). The reason for this is that this method does not need to geo-code an address and resolve a latitude/longitude because it already knows the latitude/longitude. setCenterByLatLon() also accepts the duration parameter. Because there is no conversion between address and lat/lon, the panning effect will engage much more quickly. mapInstance.setCenterByLatLon (latlon:Latlon, duration);
You’ll notice that the latlon variable does not belong to any of the variable types defined in the last chapter. That is because the latlon variable being passed is an instance of the map API’s Latlon object. You must pass a Latlon object as the first parameter of the setCenterByLatLon() method, and for that to happen, the latitude/longitude you want to pass needs to be cast as a parameter.
102
JS-Flash API Basics To create a Latlon object using the coordinates 40.380029, -3.714478 for Madrid, Spain, you must import or reference the Latlon class. The following code demonstrates this in the context of the setCenterByLatLon() method: var latlon = LatLon(40.380029,-3.714478); var duration:Number = 300; myMap. setCenterByLatLon (latlon, duration);
setCenterByLatLonAndZoom() Like setCenterByAddressAndZoom(), this method gives you access to more functionality in one shot. The sequence, as reviewed before, is slightly different because there is no address that needs to be converted to latitude/longitude; if you have selected this method, you already know the latitude and longitude. As a result, this method, like its simpler counterpart setCenterByLatLon(), works a bit more efficiently, thus generating faster results. The order of operation for this method is as follows:
1.
The method is called:
mapInstance.setCenterByLatLon (latlon:LatLon, zoomLevel, duration:);
2. 3. 4.
The map pans based on the duration, in milliseconds, defined in the duration parameter. The map centers on the resolved latitude/longitude coordinate. The map zooms in to the level defined in the zoomLevel parameter.
Common usage of this method looks like this: var latlon = new LatLon(40.380029,-3.714478); var zoomLevel:Number = 6; var duration:Number = 3000; myMap. setCenterByAddress(address, zoomLevel, duration);
The first line creates a Latlon object by calling in the Latlon class. Zoom level and duration are set and finally the method is called.
setCenterByPointDelta (point, duration) setCenterByPointDelta() is a unique means of recentering the map that lets you use other relative points on the stage. A point is a pixel coordinate defined by an x/y position. The first parameter of this method is not a point on the map, like a latitude/longitude coordinate, but rather the total difference of points within the map tile matrix.
Keep in mind that you are not moving the map to a specific point. You are moving it the difference in x/y from its current position. In other words, if you were using this method to pan the map to the right 20 pixels and down 30 pixels, you would pass a point value of (-20, -30). Essentially, the map’s center moves up and to the left, revealing more area to the bottom and to the right. Using this method, you can have the map pan over to center on other elements added to the map application. These can be design elements added programmatically or via the visual authoring methods you
103
Chapter 10 learned in the last chapter. This method can be used with markers. Examples later in the chapter will explore this possibility. The point parameter of this method works much as the latlon parameter related to the Latlon object in setCenterByLatLon() and setCenterByAddressAndZoom(). The point is not a number or Latlon object, but a Point object. To properly pass this value, you must call in the Point class, which is part of the JS-Flash class library you have already imported. Here is how to properly call the setCenterByPointDelta() method by creating an instance of a Point first: var point = new Point (100, 100); var duration:Number = 3000; myMap.setCenterByPointDelta(point, duration);
The first line creates a Point object by calling in the Point class. Duration is set and finally the method is called.
move The move event is dispatched whenever the map moves by changing location. Here is how to listen for the move event: //Listen for the move event mapInstance.addEventListener(Map. EVENT_MOVE, onMapMove);
Once the events are picked up, the JavaScript function specified will be called to carry out the event. The function shown here will display the x and y properties of the eventData passed with the move event. This reflects the map’s new position. //Display the map location function onMapMove(eventData) { alert(eventData.center.x + “ “ + eventData.center.y); }
getCenter() getCenter() returns the pixel coordinate the map is centered on as a Point coordinate. Remember that
this value looks like a latitude/longitude coordinate, but is actually an x/y coordinate. mapInstance.getCenter() : Point;
This sample verifies that the map, by default, is centered on the point -99.84375, 39.232253: var currentCenter :Object = new mx.graphics.Point(); currentCenter = myMap.getCenter(); trace(currentCenter); // Outputs: point(-99.84375, 39.232253)
104
JS-Flash API Basics Try It Out
Change the Address
In this exercise you will build a form that lets your users change the address of a map and display the new latitude and longitude after the map recenters. Another control will allow the user to pan to a specific location on the map.
1. 2.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse.
3.
Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
You can leverage the file you created in the last example or start from scratch. Open the file jsflash_mashup.htm and save it as jsflash_mashup_controlMap.htm.
Yahoo! Maps Mashups, JS-Flash API controlMap example #mapContainer { width: 800px; height: 350px; } New Address: Event Output: // Create a map object with satellite tiles by default var map = new Map(“mapContainer”, “WroxBook”, “Lisbon”, 12, “satellite”); // Changes address based on value entered in forms function drawMap() { map.setCenterByAddress(document.apiForm.newAddress.value, 500); } // Captures move event and calls onMapMove map.addEventListener(Map.EVENT_MOVE, onMapMove); // Display new map center function onMapMove(eventData) { document.apiForm.eventDisplay.value = “The center latlon is: “ + eventData.center.x + “ “ + eventData.center.y; }
105
Chapter 10
4.
In the fifth line of code, where you are defining the Javascript source to the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. Refer to Figure 10-3.
Figure 10-3
You should see the Yahoo! Maps JS-Flash API load in your HTML document. The map should be loaded displaying satellite map tiles of Lisbon, Portugal, at a zoom level of 12 (about country level). Beneath the map are some form elements. Changing the value in the first text field and clicking Go should change the location the map displays. The text area below that, labeled “Event Output,” will display the new latitude/longitude coordinates of the center point of the map. Clicking on the map and dragging it around should actively update the text area as well.
How It Works Much like the example at the beginning of this chapter, this web page starts by importing the JS-Flash maps API library. After the style is defined and the map is positioned, a form is constructed. This form features a text input field labeled “New Address” paired with a button marked Go. Also part of the form is a text area for displaying event data as it occurs.
106
JS-Flash API Basics The JavaScript handles the population of the map. Note that the satellite tile definition is included in the constructor of the map instance itself. Once the map instance is created, the initial position of the map is set to Lisbon, Portugal, using the setCenterByAddress method. The setCenterByAddress() method appears again, inside the drawMap() function. This function is called when the Go button within the form is clicked, instructing the map to redraw itself to a location the user defines. While this method supports changing the zoom level as well, this exercise does not include support for that functionality. You could combine elements from the first exercise in this chapter to change the zoom level or use setCenterByAddressAndZoom. Once the map recenters, the move event is fired. An addListener is placed to listen for that event and call for onMapMove. This function populates the text area in the form with the new center latitude/longitude.
Summar y This chapter introduced you to several of the basic methods available in the JS-Flash API. Here is a summary of what was covered in this very significant chapter: ❑
set methods are responsible for defining and changing different elements of the map.
❑
get methods can be called to retrieve specific properties of the map instance.
❑
HTML form elements, working with the JS-Flash API, can let users control and change most aspects of the map’s functionality.
107
11 JS-Flash API Advanced Features In the more advanced features of the JavaScript-Flash (JS-Flash) API, you will begin to see how radically different and uniquely capable the Flash-generated map APIs are. Once again, you will benefit from having worked with JavaScript and HTML after completing the Ajax API chapters. Combine that advantage with the solid foundation of API basics you learned in the last chapter and you are ready to dive into the advanced features. This chapter discusses ❑
Adding various types of markers to your map, including the CustomSWFMarker
❑
Adding tools to your map to let the user zoom, pan and change map type
❑
Coding and adding overlays to the map that can connect lines from point to point as well as generate common geoRSS feeds
❑
Working with the built-in mashup overlay classes that hook into live traffic and Yahoo! Local searches
Working with Markers You can’t really make a mashup without adding markers. Markers are the indicators of important locations on your map. They are added with precision by address or latitude/longitude. In addition to methods, you have ways to remove markers programmatically based on user interaction. Marker classes enable you to define the type of marker you add, be it standard markers or markers you can design and develop from scratch. Markers can be added one by one as well as by means of loading certain overlays. If you have a database, XML file, web service response or other data source with many addresses or lat/lon coordinates, you will likely use a looping method in JavaScript.
Chapter 11
Marker Methods and Classes This small set of methods represents the most used functions featured in mashups: adding markers. Each method enables you to ultimately control the location and appearance of every marker you add on the map.
addMarkerByAddress() This method lets you add markers to a location using an address: mapInstance.addMarkerByAddress(markerClass, address, data);
The markerClass parameter defines what type of marker you are adding. To successfully add a marker you must import the class of the type of marker you reference in this parameter. The various markers, reviewed in the following sections, carry unique functionality and presentation attributes. An address variable must be passed in order for the marker to be added with this method. The address will need to be geo-coded, so this method does not process as quickly as its latlon counterpart. If you intend the marker to appear in the center of the map, you may want to call setCenterByAddress() with the same address. Finally, the properties of the markerClass you choose must be defined in the last parameter. As you see in the following sections, each marker class carries with it different properties that are defined when this data object is cast.
addMarkerByLatLon() This method lets you add markers to a location using a latitude/longitude coordinate: mapInstance. addMarkerByLatLon (markerClass, latlon, data);
Working in the same way as addMarkerByAddress(), the markerClass parameter is the type of marker you are adding. The types can vary within the same mashup but require their respective classes to be imported. The second parameter defines the location at which the marker will be added. The LatLon class must be imported or referenced in order to properly cast the latitude/longitude coordinates into a LatLon object. Once again, the properties of the markerClass you choose must be defined in the last parameter. These properties will be discussed with each marker class in the following sections.
CustomPOIMarker POI stands for point of interest. This class lets you add a marker with the custom properties of index, title, description, marker color and stroke color. The two color properties reflect the body of the marker and its border respectively. These properties let you make the marker look the way you want without having to create a completely new marker. Although that feature is available with the JS-Flash API, as you will see later in the chapter, this marker class is an efficient means of customizing. Another feature of this marker class is expandability. This replicates a feature offered by standard markers, in that as the user rolls over the marker, it expands to reveal more detail. As part of this feature, this
110
JS-Flash API Advanced Features class includes open() and close() functions that let you control the marker with other code based on user interaction.
WaypointMarker A waypoint is a reference on the map, often used in navigation to plot points along a route. This class lets you plot waypoints as markers. It is a very simple class, with almost no customization other than the ability to define an index. If you are familiar with the consumer offering of Yahoo! Maps, you will recognize the waypoint marker as the same indicator used to plot points along driving routes. Because the API does not support driving directions, you will find other very useful ways to use the WaypointMarker class. These include plotting points along cruises, flights, running paths, bike races and walking trails. The class has two methods that let you modify the marker after it has been added. The setWaypoint Index() lets you change the index displayed in the marker. The getWaypointIndex() returns the string representing the index currently set to the marker. As mentioned, the index is initially set when the marker is added, so the getWaypointIndex() can be called once the marker is added.
CustomImageMarker This class lets you add an image or SWF anywhere on the map as a marker. This is a slightly more custom approach than the CustomPOIMarker discussed earlier, in that an image or SWF that you create becomes the marker. Since the marker you add is completely of your own design, the only property of this class is the url of the image (JPEG) or SWF you create. Also unlike with the CustomPOIMarker, this class does not inherently have the feature of expandability or the open/close functions. This may confuse users familiar with the common functionality of a marker. On the other hand, depending on the focus of your mashup, users may find an image or rich-contentdriven SWF to be much more useful in your application. When the map API adds a marker, it actually creates an empty movie clip at that location. The image or SWF mapped in the url property is loaded into that space, thus appearing at the precise marker location. The benefit of creating an SWF as a customImageMarker instead of a JPEG is that JPEG images do not support transparency. While you can add interactivity if your CustomImageMarker is an SWF, I recommend that you instead leverage the CustomSWFMarker class coming up next.
CustomSWFMarker This class provides one of the key capabilities of the Flash APIs, as it lets you develop and design your own interactive marker in the form of an SWF. Once the marker is added to the map instance, this class lets you call a method, callCustomMethod, against the marker itself. This means you have control over the marker after you have added it. When adding a customSWFMarker, you need to pass some additional properties. An object at the end of the addMarkerByLatLon or addMarkerByAddress method must include the URL of the customSWFMarker you are adding. An additional property called ref can also be passed. This enables you to sync up the marker with other data later in your code. mapInstance.addMarkerByAddress(CustomSWFMarker, address, {url, ref});
111
Chapter 11 This class caused some confusion when it was first introduced, because of when the marker is actually added. Usually, once the addMarker method is called, the marker is available for further reference by the code. This is because the code for the other marker classes is prepackaged with the API. In the case of the customSWFMarker, the marker has not completely loaded until the SWF itself is loaded into the application. Depending on the availability of the SWF, be it on a local URL or a site elsewhere, as well as the size of the SWF being loaded, it is almost certainly not loaded instantaneously. To solve this problem, a new event called EVENT_CUSTOM_MARKER_LOADED was added. This isn’t fired until the custom SWF has been completely loaded. The data dispatched with this event are even more important. The properties of the data object are marker and ref. The first is the full path of the marker. This enables you to call the callCustomMethod and engage the customSWF you have added. The ref property is the ID you passed when you added the marker. This enables you to reference the event to a specific marker, letting you further coordinate the markers that have been added. It basically helps you identify which marker is which. mapInstance.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_CUSTOM_MARKER_ LOADED, onMarkerLoaded); function onMarkerLoaded( eventData ) { eventData.marker.callCustomMethod(“methodOnMarker”); alert(eventData.ref); //Outputs reference id passed when marker instance was created } CustomSWFMarker can be used in limitless ways, from displaying dynamic data to streaming video content. Because this marker requires a bit of Flash development and design, it will be covered in more detail in Chapters 13–17, which discuss the ActionScript-Flash (AS-Flash) API.
removeMarker(marker) To remove a specific marker, you can call removeMarker() against the marker instance you have added: mapInstance.removeMarker(marker);
removeAllMarkers() removeAllMarkers() will clear out all markers that have been loaded to the map instance. Since this
method does not affect one single marker, but instead all markers, it does need a parameter. mapInstance. removeAllMarkers();
In the upcoming exercise, you will put all this knowledge together and create a marker on the map featuring an image.
Try It Out
Add a Variety of Markers to the Map
This exercise will help you display markers for a castle in Austria.
1. 112
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse.
JS-Flash API Advanced Features 2. 3.
Open the file jsflash_mashup.htm and save it as jsflash_mashup_addMarkers.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
Yahoo! Maps Mashups, JS-Flash API addMarkers example #mapContainer { width: 800px; height: 350px; } // Create a map object var map = new Map(“mapContainer”, “WroxBook”, “Austria”, 12); // Listen for the map initialize event map.addEventListener(Map.EVENT_INITIALIZE, onInitialize); // Function to handle initialize event function onInitialize( eventData ) { // Create a Custom POI marker object marker1 = new CustomPOIMarker( ‘Castle’, ‘Anif’, ‘This castle is located in Salzburg, Austria’, ‘0x000000’, ‘0xFFFFFF’); // Add the CustomPOIMarker instance to the map map.addMarkerByAddress( marker1, “Salzburg, Austria”); // Create an Custom Image marker object marker2 = new CustomImageMarker( ‘http://www.mashupexperts.com/yahoomapsmashups/source/media/Castlesorg_Anif.jpg’); // Add the CustomImageMarker instance to the map map.addMarkerByAddress( marker2, “Salzburg, Austria”); }
4.
In the fifth line of code, where you are defining the JavaScript source for the JS-Flash API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. Figure 11-1 shows the map loaded displaying regular map tiles of Austria, at a zoom level of 12.
113
Chapter 11
Figure 11-1
Two markers should appear close to the center of the map near Salzburg. The top marker is a customPOIMarker displaying “Castle Anif.” When clicked, this marker should expand to reveal more information on that location. The other marker is a customImageMarker, displaying a static image of the castle.
How It Works The API’s class library is imported, exposing all the methods and classes to your HTML and JavaScript. Using CSS, the mapContainer style is defined and then implemented with the div a few lines later. The map object is created, passing in the mapContainer for placement, as well as the initial location and zoom level. A listener is added to the map instance using addEventListener. This method will listen for the map’s initialize event and then call the onInitialize function when it is heard. Within the onInitialize function, two markers are added to the map using the addMarkerByAddress method. In order for the marker to be added, an instance of that marker must be created consisting of the necessary parameters. For the CustomPOIMarker, parameters including marker title, marker rollover text, marker description, outline color and background color must be defined. The marker description will appear when the marker is clicked. The second marker type added is an instance of the CustomImageMarker class. This instance requires just one parameter, the URL of the image to load.
114
JS-Flash API Advanced Features
Working with Tools Tools are features of the map that leverage mouse interaction. Two tool classes are included with the JS-Flash API. The pan tool enables the drag-panning feature that has become standard in the current generation of richer map applications. This functionality is not available by default and needs to be added. The other tool class is CustomSWFTool, which enables you to create your own tool so your users can better engage with the map.
The terminology for the Ajax and Flash APIs differs here with the definition of tool. In the Flash APIs, a tool is a mechanism of the API that is developed based on mouse interaction. The Flash API widget is close to the Ajax definition of a tool, a cluster of user interface elements and code that allows control of the map.
Tool Methods and Classes The tools are available with the map class that is loaded by default when the map instance is created. They are responsible for adding, removing and activating the tools you make available to your users. There is a special widget, discussed later in this chapter, that adds a menu for tools to your map application. This is called the ToolBarWidget and its contents rely on the results of these methods.
addTool() addTool() is a simple method that lets you add instances of tools to the map. This method must be called after the map instance initializes, and is usually placed within onInitMap. mapInstance.addTool(tool, isActive);
In order to add a tool, you must first import that tool’s class and create an instance of it. That instance is the first parameter of this method. The second parameter is isActive. When set to true, the tool will be added and become active to your users right away.
setActiveTool(tool) Should you add a tool with isActive set to false, you will need to run this method later in your code. This method accepts just one parameter, and that is the instance of the tool you want to activate. mapInstance.setActiveTool(tool);
removeTool(tool) removeTool() is used to remove a tool, thus reactivating it from the map instance. Its only parameter is the instance of the tool it is called to remove. mapInstance.removeTool(tool);
PanTool This tool adds the all-important feature of letting the user drag the map and pan it. Since the tool activates a feature within the map instance itself, some events are associated that work with the map events
115
Chapter 11 discussed earlier in the chapter. EVENT_DRAG_STOP and EVENT_DRAG_START track the map dragging and are not to be confused with EVENT_PAN_START and EVENT_PAN_STOP. To effectively listen for these events, you must listen to the tool instance directly.
Try It Out Turn PanTool On and Off 1. Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. 2. Open the file jsflash_mashup.htm and save it as jsflash_mashup_PanTool.htm. 3. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view): Yahoo! Maps Mashups, JS-Flash API panTool Toggle example #mapContainer { width: 800px; height: 350px; } PanTool on: PanTool off: Event Output: // Create a map object with satellite tiles by default var map = new Map(“mapContainer”, “WroxBook”, “Cairo, Egypt”, 10); var panTool = new PanTool(); // Toggle PanTool based on value entered in forms function togglePan(toolAction) { if (toolAction == ‘add’) { // Add PanTool to map map.addTool( panTool, true ); } else { // Remove PanTool from map map.removeTool( panTool ); }
116
JS-Flash API Advanced Features } // Captures toolAdded event and calls onToolAdded map.addEventListener(Map.EVENT_TOOL_ADDED, onToolAdded); // Captures toolRemoved event and calls onToolRemoved map.addEventListener(Map.EVENT_TOOL_REMOVED, onToolRemoved); // Display tool added status function onToolAdded(eventData) { document.apiForm.eventDisplay.value = eventData.tool.toolType + “ has been added to the map”; } // Display tool removed status function onToolRemoved(eventData) { document.apiForm.eventDisplay.value = eventData.tool.toolType + “ has been removed from the map”; }
4.
In the fifth line of code, where you are defining the JavaScript source for the JS-Flash API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. The map should be loaded displaying regular map tiles of Cairo, Egypt, at a zoom level of 10 (see Figure 11-2).
Figure 11-2
117
Chapter 11 Below the map should be a form consisting of two radio buttons and a text area. The radio button labeled “PanTool on” is selected, indicating that this feature is not active.
How It Works After importing the JS-Flash API library, the classes become available to your JavaScript and HTML. The mapContainer style defines the size and placement of the map. The div tags will display the map as it is rendered and inherit the style-sheet properties of the mapContainer class. The apiForm is written in HTML and will do two things. First, the form contains a pair of radio buttons labeled “PanTool on” and “PanTool off.” The map loads without the PanTool loaded, so the latter of the two radio buttons is selected by default. Each radio button has an onClick event handler set to call a togglePan function. The map instance is created by creating a new map, including the parameters to set default location and zoom level. After that, an instance of the PanTool is created. Creating the PanTool instance does not add the tool to the map. This will be performed within the TogglePan function. Clicking either radio button calls the togglePan function, passing it a toolAction parameter. This determines, based on a conditional (an if/then statement) within the togglePan function, whether the PanTool will be added or removed. The API methods addTool and removeTool, with the PanTool instance as their parameter, accomplish these tasks. You use the addEventListener method to listen for the toolAdded and toolRemoved events. Those events are fired from the map when the tool is added or removed. Each event listener calls a corresponding function to carry out the event. This ultimately displays the added or removed status, as well as the tool that has been affected, using the event data object’s tool.toolType property. This exercise, like most in the book, is intended to be flexible and should enable you to try out adding and removing the other tools and widgets featured in the JS-Flash API.
CustomSWFTool CustomSWFTool enables you to extend the interactivity of the map into more engaging tools. Like the PanTool, this class relies on mouse interaction to engage the user. As with other customSWF classes discussed in this chapter (CustomSWFMarker and CustomSWFOverlay), to take advantage of this feature
you will need to build your own SWF and add it to the map using the methods local to this class. Through a series of events, your customSWFTool will be able to listen for mouse events. Various developers have used the customSWFTool to create drawing utilities, advanced zooming interfaces and unique navigation controls. In addition to the tool, you can create an icon for that tool. The icon should be an SWF measuring 26 by 26 pixels. It should offer a simple icon representing what the tool will do. For example, the icon that comes prepackaged with the PanTool resembles a hand. Both the tool and the icon can be passed when the CustomSWFTool is created.
118
JS-Flash API Advanced Features var customInstance = new CustomSWFTool(customSWFToolPath, customSWFToolIconPath); mapInstance.addTool(customInstance, false);
As you will see in the following example, when two or more tools are added to the map, the ToolBar Widget (discussed earlier in this chapter) becomes essential in enabling your users to manage the tools they use.
Working with Widgets Widgets are the prepackaged sets of user interfaces that ship with the map API. They reflect some of the most-used technology on consumer map applications like Yahoo! Maps. Adding existing widgets can save you time over having to replicate the functionality with your own UI. Applying this knowledge to your existing asFlashAPI, MapConnector and Flex2Maps classes requires little modification.
Widget Methods The simple methods available for widgets are part of the map class. These methods are available when the map instance is initialized. However, unless you import the class of the widget you want to add, you cannot use these methods. These classes included with the API come with all you need to turn on each of their compact functionalities to your users. Each class must be imported and it is suggested that you create an instance of the widget before adding it to the map. This lets you reference that instance throughout your code, letting you remove it and add event listeners to it more easily.
addWidget() This simply adds a widget to your map instance. In most cases, you will want to create an instance of the widget first and then plug that instance name into the method as its lone parameter. mapInstance.addWidget(widget);
removeWidget() Like the tool methods, this widget removes the widget, effectively deactivating its functionality to the user. It accepts just one parameter, the instance name of the widget it is removing. mapInstance.removeWidget(widget);
NavigatorWidget This is the most functional out-of-the-box feature that comes with the API. While it is not customizable in appearance, adding the navigator widget provides several functionalities with very little code. Many of the methods you learned in the last chapter let you programmatically center the map, pan the map and change its zoom level. The navigator, with its mini-map combined with the zoombar, lets the user do all that in one space.
119
Chapter 11 The first piece of the navigator is a small map inside a square. The map displayed here will always display map view tiles and correspond to the location and zoom level of the main map. The perspective here is supposed to give the user a bird’s-eye view of the main map itself, so the zoom level is actually several levels higher. On top of this minimap is a small gray square that, when dragged and released, will control both the main map and the minimap. This lets users control the position of the map with loose precision in a natural manner. When this square is dragged and held in either direction, the map will respond by panning to reveal more of the map in that same direction. The other piece of the map is a zoombar. This is a combination of several elements that when put together create an easy tool with which your users can zoom in and out of the map. The main elements are a plus button, a minus button and a slider. Each button, when clicked, zooms the map in or out. Using the richness of Flash, zooming in or out with this tool forces the map to transition between tile layers. The effect is a gradual expansion of the existing tiles and then a fade in to the new tile layer loaded beneath it. The feature achieves the feeling of users moving closer to the earth when they zoom in and the reverse when they zoom out. The slider adds a somewhat more organic feel to the zoombar and, like the dragability of the square in the minimap, allows for a more natural control. The NavigatorWidget has the ability to appear open (expanded) or closed (collapsed). Two methods, open() and close(), are included in the class. They can be called against the widget’s instance to change its state after it has been added.
SatelliteControlWidget The satelliteControlWidget class attaches three predesigned buttons to the map that allow users to toggle among the map view types. Once again, this is a great alternative to creating and coding your own buttons if time is important. These buttons are set to detect the existing map view type and will reflect it by selecting the corresponding type’s button in the widget.
ToolBarWidget This widget adds a menu of icons to the top-left corner of your map. It acts as a start menu, like the one found at the base of your operating system. Its contents are a row of icons representing each tool that you have added to the map. Having learned about tools earlier in the chapter, you know their limitless possibilities. You also know that the main tool, the PanTool, will likely be added to most of your mashups as core map functionality. If that is all you add, then you will likely not need this widget. If, however, you develop and add several tools of advanced functionality, it will be very useful to your users to have a menu with which to activate and/or use those tools. That is where this widget becomes very valuable. The map is intended to have only one tool active at a time.
Working with Overlays An overlay adds a new layer over the existing map layer. It moves along with the map as it is panned. Overlays are generally used as containers for sets of markers representing related data, such as local search results and traffic.
120
JS-Flash API Advanced Features As you will see, the overlays have the incredible ability of acting as their own mashups. Adding some of the overlay classes will actually request data, parse the response and add markers all by itself. It is good to test out each overlay, as it may save you some time as well as enable you to add even more functionality to what you will ultimately build.
Overlay Methods and Classes Just like widgets, tools and markers, overlays can be added and removed with a simple pair of methods. It is good practice, after importing the overlay class, to create an instance variable for that new overlay. Overlay classes act as built-in mashups. With the LocalSearchOverlay and TrafficOverlay classes, your application will be directly connected to the popular local search and traffic data. These two classes in particular enable you to replicate functionality featured on the Yahoo! Maps consumer application. Also available is the GeoRSSOverlay class. This class, when imported and instantiated, is capable of picking out locations from geoRSS feeds and displaying markers respective to those locations. GeoRSS is a special standard that represents standard RSS data with location data objects embedded within each item.
addOverlay(overlay) Once the map instance is initialized, the overlay instance can be added using addOverlay(). addOverlay() accepts one parameter, the overlay instance you are adding to the map. mapInstance.addOverlay(overlay);
removeOverlay(overlay) removeOverlay() will remove the specified overlay instance from the map: mapInstance. removeOverlay(overlay);
LocalSearchOverlay LocalSearchOverlay adds a feature that taps the power of Yahoo!’s local search database. The func-
tionality lets you call a keyword search and display results in the form of markers. This feature closely resembles that of the Find on Map feature on the Yahoo! Maps consumer application. The markers are enriched with some very useful data for any user, including business name, address and, where available, business rating. The overlay class features a method called search() that sends a service call through the API to generate results. It is often used for finding businesses such as restaurants, and its search criteria work simply on a keyword. The method accepts several other parameters that let you manage the results in several ways. localSearchOverlayInstance.search(searchTerms, latlon, startIndex, results, radius, categoryFilter, ratingFilter);
You will notice that as with the widgets, this method is called against the overlay instance. The search() method requires only the first two parameters to work. To let your users make the most of this method, you will likely want to collect the searchTerms from a value entered into a text input field or component.
121
Chapter 11 The other parameter can be obtained at any time using the getCenter() method on the map instance. The additional parameters provide various ways to manage the results. startIndex and results let you create pagination from one set of results to the next. radius, categoryFilter and ratingFilter offer ways to narrow search results. Two main events are tied to the search method within LocalSearchOverlay. EVENT_SEARCH_SUCCESS and EVENT_SEARCH_ERROR are fired based on the success or failure of a search. Success offers some structural data within the object passed that help facilitate a narrower search. localSearchOverlayInstance.addEventListener(com.yahoo.maps.overlays.LocalSearchOver lay.EVENT_SEARCH_SUCCESS, onSearchSuccess); localSearchOverlayInstance.addEventListener(com.yahoo.maps.overlays.LocalSearchOver lay.EVENT_SEARCH_ERROR, onSearchError);
Once again, you will see that the event listeners are added to the overlay instance rather than the map instance. You will also notice that the event path references the overlay path instead of the map class path. Both events call functions to carry out their respective dispatches. With that are the data objects. You should always explore the data object returned from an event using the for/in method.
TrafficOverlay TrafficOverlay is another overlay class that replicates the power of a very popular and useful feature
of the Yahoo! consumer application. Real-time traffic incident information can add a desirable functionality to your application, giving it an extra edge. A benefit to this overlay class is that it has no methods, because all the functionality is built in. The overlay class requests traffic information for the area the map is currently centered on. It takes the data returned and displays each item as a CustomPOIMarker, complete with incident information. The markers created reflect traffic incidents ranging from accidents to road construction to medical emergencies. Each incident is represented with a different color and universal symbol.
Try It Out Add the Traffic Overlay 1. Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. 2. Open the file jsflash_mashup.htm and save it as jsflash_mashup_TrafficOverlay.htm. 3. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view): Yahoo! Maps Mashups, JS-Flash API TrafficOverlay example #mapContainer { width: 800px; height: 350px; }
122
JS-Flash API Advanced Features // Create a map object var map = new Map(“mapContainer”, “WroxBook”, “Phoenix, Arizona”, 5); // Listen for the map initialize event map.addEventListener(Map.EVENT_INITIALIZE, onInitialize); // Function to handle initialize event function onInitialize( eventData ) { // Add an instance of the PanTool map.addTool( new PanTool(), true ); // Create an overlay object var overlay = new TrafficOverlay(); // Add the traffic overlay to the map map.addOverlay(overlay); }
4.
In the fifth line of code, where you are defining the JavaScript source for the JS-Flash API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. You should see the Yahoo! Maps JS-Flash API load in your HTML document, looking like Figure 11-3.
Figure 11-3
123
Chapter 11 The map should be loaded displaying regular map tiles of Phoenix, Arizona, at a zoom level of 5. Depending on the time of day and current traffic conditions, various traffic indicator markers should appear on the map near downtown Phoenix.
How It Works After the API’s class libraries are imported, the container that the map will be displayed in is defined. The common steps to create a map object are completed, the familiar parameters for initial location and zoom level being passed. A listener for the map’s initialize event is added. Using addEventListener, the function called onInitialize will be called when the event is heard. Within the event, several key elements are executed. First, the PanTool is added, making the map draggable. Next, an instance of the TrafficOverlay is created. Using addOverlay, the overlay instance is added to the map and enables the features of the TrafficOverlay to appear. Like the LocalSearchOverlay, the TrafficOverlay acts as a built-in mashup. Executed in the code of the TrafficOverlay is a request to Yahoo!’s real-time traffic server for traffic incidents. The parameter of this request, which remains invisible to you and the user, is the center latitude/longitude of the map being displayed. The incidents are returned, parsed through and displayed as customPOIMarkers all over the map.
GeoRSSOverlay This class and type of overlay lets you populate the map with markers defined from a geo-coded RSS feed. This special version of RSS XML contains geo-coded objects. A geoRSS feed adds extra data like latitude/longitude or address in addition to location information. The following is a sample of a geoRSS feed: ... Title to appear in Marker Link to appear in Marker Address where Marker will locate on map Address where Marker will locate on map Phone Number to appear in Marker ...
The geoRSSOverlay is fed this XML as a URL. The parameter is set when the overlay instance is created. The file should reside remotely. //Create geoRSS instance var georss = new GeoRSSOverlay(‘http://urlToGeoRSS.xml’, true); //Add overlay instance to map mapInstance.addOverlay(georss);
124
JS-Flash API Advanced Features CustomSWFOverlay The customSWFOverlay combines the flexibility of the geoRSSOverlay with the potential of the customSWFMarker. Essentially, instead of your geoRSS feed loading images as markers, it can load SWFs. In addition, you can call methods against those marker SWFs through the callCustomMethod method, which is reviewed in much more detail with the CustomSWFMarker class example in Chapter 16.
Summar y This chapter explored the advanced features of the JS-Flash API, rounding out the roster of methods, events and classes available with the API. After reading this chapter, you are now able to ❑
Add a series of markers displaying different details and an image representing a single location
❑
Add widgets that will enhance the usability of your map application while saving you loads of development time
❑
Implement the essential pan tool, add it and remove it from the map
❑
Work with the API’s built-in mashup engines called overlays, adding features like local search results and real-time traffic information to your map
125
12 The JS-Flash Mashup The goal of this chapter is for you to build a JavaScript-Flash (JS-Flash) maps mashup using the JS-Flash API and Yahoo! Travel. To achieve this, you will also accomplish the following: ❑
Establish an idea for your mashup and plan out the details and development approach
❑
Learn how to retrieve external data from the Yahoo! Travel API and display it on the map
❑
Create links that center the map on a trip plan stored in Yahoo! Travel
Time to Mash Up Now that you have learned all the methods and classes of the JS-Flash API, it’s time to build a mashup. As with the other APIs featured in this book, this chapter will guide you through building a mashup with a data source and the map API.
The Big Idea Yahoo! Travel is a property of Yahoo! that lets users book airline tickets, hotel reservations and car rentals. Their new trip planner lets users plan out trips they are looking to take as well as to log trips that they have taken. Trips are naturally compatible with maps since every trip has a location. While maps themselves are sufficient stand-alone applications, displaying trip data on top of a map is even more useful. In this chapter you will build a mashup between Yahoo! Maps and Yahoo! Travel from the trip planner. Upon completion, you will see and be able to show your users trips that have been or will be taken across Europe. Each trip will be marked by a thumbnail of a photo taken at that location. You will add functionality so that clicking the marker will send your users to the trip planner site to view more details of that trip. This highly scalable and adaptable project will introduce you to common functionality that you can apply with several other APIs and web services.
Chapter 12
Planning and Approach As with any application, planning and approach are important. It helps to know the APIs and web services you are working with very well. Having completed the previous chapters on the JS-Flash API, you should have all you need to work with the map. If you completed Chapter 7, “The Ajax Mashup,” you will also know much about working with JSON. Later in this chapter you will examine the Yahoo! Travel API, how the request is constructed and what data to expect returned upon a successful request. Before coding, it is always good to lay out your objectives and then determine how best you will achieve those tasks. Begin with thinking out what your application should achieve. Through the rest of the chapter, you will see how these steps are developed into the mashup. ❑
Display the map initially.
❑
Position the map and set its view type accordingly.
❑
Call the external API and retrieve the data.
❑
Give the user the ability to navigate through the data.
❑
Display the data as markers on the map based on user selection.
What you see listed here is a simple flow, and this pattern of user interaction should be easily replicated with other APIs and web services.
The Yahoo! Travel API Yahoo! Travel’s API enables developers to search trips posted on the trip planner based on some very simple parameters. It also lets you access details on specific trips based on more specific criteria. Since Yahoo! Travel is obviously a property of Yahoo!, the support for its API is similar to that for the Yahoo! Maps APIs. Like Maps, the Yahoo! Travel API and its documentation are supported by the Yahoo! Developer Network (YDN). To check out the web service firsthand, visit http://developer.yahoo .com/travel/ for the most up-to-date documentation and news on the API.
How Travel Content Contains Location Yahoo! Travel’s trip planner uses a form-based interface to collect initial details about a user’s trip. After entering a trip title, the dates the trip occurred or will occur and personal identification information, the user is presented with a console to enter further detail. The schedule view lets users enter popular locations visited on the trip based on the initial location entered. With each entry, the user can add details about that location or the overall trip. As cataloged locations like hotels, restaurants and amusement parks are entered, their respective address information is also saved. Moving on to the map view, Travel displays an internal mashup of its own that leverages the Ajax API to display all locations entered from the previous view (see Figure 7-1 in Chapter 7). This is a prime usage
128
The JS-Flash Mashup of the Yahoo! Maps API and acts as confirmation of all the locations entered thus far. Looking at this interface, you can already see just how well trip data works with maps. Finally, the trip journal lets you add photos to a trip album. Users can upload their photos or link photos right from their Flickr accounts. It is a simple and powerful interface designed to encourage as much data entry as possible. Using photos to tell the story of a trip helps in documenting it. This last feature adds a lot of value to the Travel API, since better photos mean better markers for you to display in your mashup. See Figure 12-1.
Figure 12-1
API Authentication Conveniently, Yahoo! Travel APIs use the same authentication as Yahoo! Maps. This means that the same AppID you received in earlier API chapters of this book, will work with this API. In the steps ahead that will guide you through building the mashup, you will be prompted when necessary to enter your personal AppID. However, as the API is broken down in the following sections, this variable will indicate where your AppID will go: {your_YDN_appID}
129
Chapter 12
API Methods Not to say the Travel APIs are limited, but thankfully it offers only two methods for interaction. It is not a reflection of the quality of the API or the data available. It is more a concentration of function that the service is currently designed to provide. Yahoo! Travel supports its API calls through a Yahoo! Developer Network site similar to that for Maps. By default, the documentation crafts the method call as a REST request and returns very readable XML.
tripSearch This method lets you search for user-entered trips based on loose criteria. It also enables you to search for trips posted by a specific user. To search for posted trip plans, you will need to pass a query parameter in addition to the required AppID parameter. This is a keyword such as “New York” or “Europe.” Using the parameter, the method will return all trips tagged with the query value. The fully constructed tripSearch REST call looks like this: http://travel.yahooapis.com/TripService/V1/tripSearch?appid={your_YDN_appID}&query= europe
You can see where to plug in your AppID. The query value of europe instructs the search to return trips tagged with this word. Additional parameters for this method include results, a value that quantifies the number of results returned and can take a value from 10 to 50, and start, a value that determines what value will be returned initially. The latter is helpful for paging through results. Copying and pasting this code into your browser will return XML that an application can parse. An excerpt of such a response for this method call looks like this: 41.889999 12.5 http://us.i1.yimg.com/us.yimg.com/i/travel/tg/lp/8b/100x100_8bf3484c27330a18a0 ed56c8f7a20055.jpg 100 65 Europe
130
The JS-Flash Mashup 46 Rome, Paris, Munich, Florence, Cologne, Berlin, Dusseldorf, ... Sun, 07 May 2006 01:00:31 GMT Six weeks in Europe http://travel.yahoo.com/trip?pid=585440&action=view ... 585440 ... 2699 0 10
Among the attributes of this actual trip planned in Yahoo! Travel, you can see that the latitude and longitude are specified. As you will see in the mashup later in this chapter, parameters from a call like this one will be used to place a marker on the map with these coordinates.
getTrip As you can tell by the get in its name, this call is positioned to return certain values based on given parameters. The getTrip method will return a specific trip and its details based on a trip ID being passed as a parameter. This call requires two parameters, the AppID and the trip ID you want to look up. It is ideal for requesting your own trip, and so the trip ID that you define will likely be one you entered. http://travel.yahooapis.com/TripService/V1/getTrip?appid={your_YDN_appID}&id=585440
The XML data returned by this call, after you substitute the necessary values, will be similar to those of the getTrip call. While this call returns no latitude/longitude points, it could be helpful for your application in displaying more detail about a specific trip.
Understanding JSON This section is similar to the one covered in Chapter 3, “The Ajax API.” However, there are some differences between the Flickr API and the Yahoo! Travel API that are worth noting.
JSON stands for JavaScript Object Notation and is a simplified version of XML. It was developed to be a much more lightweight and thus faster way to pump data into JavaScript. Its popularity has grown with the increase of web pages built with Ajax. As with XML, data in JSON is organized easily and is humanreadable, meaning it can be understood on-screen without code interpretation. Favorable articles on JSON say that it “cuts the fat” out of XML by removing the cumbersome tag syntax. An equal benefit is its ability to be loaded directly into JavaScript. As you will see in the example in the next section, JSON has a callback ability, which lets it virtually parse itself by calling a defined function in JavaScript when it is returned.
131
Chapter 12 Making a JSON Request A JSON request is constructed much like a typical REST request. It is important to note that an API needs to provide specific support for JSON, but unfortunately most still do not. Yahoo! Travel supports JSON, making map mashups easier and more accessible. Using a familiar REST response URL, adding the parameter &output=json will instruct the API to respond with JSON. http://travel.yahooapis.com/TripService/V1/tripSearch?appid={your_YDN_appID}&query= europe &output=json
In JavaScript, for the request to be made, the URL must be embedded in a JavaScript src tag, much as you load the classes of the Ajax map API.
Instead of XML, this request will return a string of text looking like this: {“ResultSet”:{“Result”:[ {“Geocode”:{“Latitude”:”41.889999”,”Longitude”:”12.5”},”Image”:{“Url”:”http:\/\/us. i1.yimg.com\/us.yimg.com\/i\/travel\/tg\/lp\/8b\/100x100_8bf3484c27330a18a0ed56c8f7 a20055.jpg”,”Height”:”100”,”Width”:”65”},”Title”:”Europe”,”Duration”:”46”,” Destinations”:”Rome, Paris, Munich, Florence, Cologne, Berlin, Dusseldorf, ...”,”CreateDate”:”Sun, 07 May 2006 01:00:31 GMT”,”Summary”:”Six weeks in Europe”,”Url”:”http:\/\/travel.yahoo.com\/trip?pid=585440&action=view”, ”YahooID”:”...”,”id”:”585440”,”_attributes”:{“id”:”585440”},”Attribution”:”...”}],” totalResultsAvailable”:”2699”,”_attributes”:{“totalResultsAvailable”:”2699”,”xmlns: xsi”:”http:\/\/www.w3.org\/2001\/XMLSchemainstance”,”xmlns”:”urn:yahoo:travel”,”xsi:schemaLocation”:”urn:yahoo:travel http:\/\/api.travel.yahoo.com\/TripService\/V1\/TripSearchResponse.xsd”,”firstResul tPosition”:0,”totalResultsReturned”:10},”firstResultPosition”:0,”totalResultsReturn ed”:10}}
As you can see, indeed, most of the XML “fat” is removed. This returned data is still easy to read and, even better, in a format similar to a JavaScript array, can be parsed much more smoothly.
Using the JSON Callback To use JSON with the Travel API, you will need to specify a callback method. Unlike with the Flickr API, no JSON callback method is given. Using the callback parameter, you can create a request that would look like this:
To properly handle a JSON response, you will need to code a function, matching the callback method, to receive the response data. Using jsonTravelApi, here is how that function may look in your code:
132
The JS-Flash Mashup function jsonTravelApi (rsp){ alert(rsp.ResultSet.Result.length); }
This function will execute when the JSON is returned. The response data will be passed to jsonTravelApi as the object rsp. Within the function, the JavaScript will execute an alert with the number of trips in the response. You can see how rsp, the data from the JSON response, is handled as an array. This means that JSON results can be looped through easily as well.
Build the Mashup Now it’s time to add this knowledge to your expertise of the JS-Flash API and build your mashup. You will first code the application and then review each section of the code to learn, in greater detail, how it works.
Code the Mashup This mashup will let you display your photos on a map. You will also supply navigation so your users can zoom in on each photo you display.
1. 2. 3.
Open Notepad or your favorite coding IDE, such as Dreamweaver or Eclipse. Open the file jsflash_mashup.htm and save it as jsflash_travel_mashup.htm. Enter the following code at the first line (depending on which IDE you are in, you may need to switch to code view):
Yahoo! Maps Mashups, JavaScript-Flash Yahoo! Travel Mashup #mapContainer { width: 700px; height: 400px; float:right; } function jsonTravelApi(rsp){
133
Chapter 12 rspData = rsp; for (var i=0; i 1 && lon > 1 && imgUrl != “”) { document.write(“”); } } // Create a map object myMap = new Map(“mapContainer”, “WroxBook”, “Austria”, 13); // Listen for the map initialize event myMap.addEventListener(Map.EVENT_INITIALIZE, onInitialize); } // Function to handle initialize event function onInitialize ( eventData) { // Add pan tool to map myMap.addTool(new PanTool(), true); rsp = rspData for (var i=0; i 1 && lon > 1 && imgUrl != “”) { var tripUrl = travelPlan.Url; addMarker(lat,lon,imgUrl,tripUrl); } }
134
The JS-Flash Mashup } function addMarker(lat,lon,imgUrl,tripUrl){ var poiSource = “”; // Create a Custom POI marker object marker = new CustomPOIMarker( ‘Trip’, ‘Yahoo! Travel Trip Plan’, poiSource, ‘0x000000’, ‘0xFFFFFF’); // Create a lat/lon object for positioning marker var latlon = new LatLon(Number(lat),Number(lon)); // Add the CustomPOIMarker instance to the map myMap.addMarkerByLatLon( marker, latlon); } function centerMap(lat,lon) { // Create a lat/lon object for re-positioning the map var latlon = new LatLon(lat,lon); // re-position the map myMap.setCenterByLatLonAndZoom(new LatLon(lat,lon), 13, 500); }
4.
In the sixth line of code, where you are defining the JavaScript source for the Ajax API library, replace the WroxBook AppID parameter with your own YDN AppID.
5.
In the third-to-last line of code, where you are defining the JavaScript source for the Yahoo! Travel API, replace the WroxBook AppID parameter with your own YDN AppID.
6.
Save the file and load it into your browser. You can also upload it to your web server at this time to view it. See Figure 12-2.
You should see the Yahoo! Maps JS-Flash API load in your HTML document. The map should load displaying regular tiles of most of Europe. Depending on the available trip plans entered in Yahoo! Travel, several markers will display representing user-entered trips. Along the left side of the map, you should see an array of thumbnails representing photos taken on the various trips.
135
Chapter 12
Figure 12-2
How It Works The first steps of this mashup are to import the map classes and methods into JavaScript as well as to define the space the map will be displayed in. The code is much the same as that which you have used repeatedly throughout the last few chapters: Yahoo! Maps Mashups, JS-Flash Yahoo! Travel Mashup #mapContainer { width: 700px; height: 400px; float:right; }
136
The JS-Flash Mashup After closing the head tag and opening the body tag of the HTML, it is time to carve out the display area of the map:
The div tags will create the space for the map instance and use the style-sheet definition mapContainer for height and width. The logical next step would be to create the map object. However, the code executes much better if you process the JSON request first. Once you have saved the data response for the API request, you can then move forward and create the map object. In the next batch of code, you will write the JSON callback function, save the data response and add some navigation items. As the data are returned, each trip in the data will generate a thumbnail image that will appear alongside the map. Finally, when the loop through the data is complete, you will create the map object. function jsonTravelApi(rsp){ rspData = rsp; for (var i=0; i Boston College 140 Commonwealth Ave Chestnut Hill, MA (617) 552-8000 MIT 200 Technology Sq Cambridge, MA (617) 452-1100 Harvard University University Hall Cambridge, MA
Looking closer at the actual XML used in the example, you can see how each item represents a marker. What appears in the title fields is what appears at the top of the inside of the marker when the logo is clicked. The link fields appear at the bottom of the marker and load the URL in another window. The address and cityState fields are used to geo-code the location of the marker. They are also displayed, with phone number and description, inside the marker. Finally, the baseIcon field represents the URL of the image loaded as the marker. If there is no image, or the image cannot be loaded, a default marker will be displayed. The geoRSSOverlay instance is capable of dispatching two events, OVERLAY_GEOCODE_ERROR and OVERLAY_GEOCODE_ERROR, which are added. Both return the URL that was submitted to load in the url property of the event’s object.
221
Chapter 16 CustomSWFOverlay The customSWFOverlay combines the flexibility of the geoRSSOverlay with the potential of the customSWFMarker. Essentially, instead of your geoRSS feed loading images as markers, it can load SWFs. In addition, you can call methods against those marker SWFs through the callCustomMethod method, reviewed in detail with the CustomSWFMarker class example in this chapter. Since few geoRSS feeds load SWFs, particularly ones that have exposed methods, this is not a very frequently featured class in AS-Flash-based mashups.
Summar y This chapter explored the advanced features of the AS-Flash API, rounding out the roster of methods, events and classes available with the API. After reading this chapter, you are now able to ❑
Listen for various panning and zooming events and program timely functions against them
❑
Add widgets that will enhance the usability of your map application while saving you loads of development time
❑
Implement the essential pan tool as well as create your own mouse interaction–based customSWFTool
222
❑
Add several types of markers, both prepackaged and custom-based on your own creativity, by latitude/longitude and address
❑
Work with the API’s built-in mashup engines, called overlays, adding features like local search results and real-time traffic to your map
17 The AS-Flash Mashup The goal of this chapter is for you to build your first Yahoo! Maps ActionScript-Flash (AS-Flash)–based mashup. To achieve this, you will also accomplish the following: ❑
Establish an idea for your mashup and plan out the key details and development approach
❑
Successfully lay out an easy interface using the Flash IDE’s visual authoring capabilities
❑
Learn how the HotJobs web service will work with the maps API
❑
Create a new class to handle the web service request and parse the response XML data
❑
Code the user interaction to formulate a request and display the results as markers on the map
Time to Mash Up Now that you have learned all the methods and classes of the AS-Flash API, it’s time to build a solid mashup. As with the other APIs featured in this book, this chapter will guide you through building a mashup with a data source and the map API. These aren’t the only ingredients you need. Your creativity is the third ingredient. Because this is the AS-Flash API, you will find that you have a lot of opportunities to put that creativity to use. As you have learned, the AS-Flash API benefits from the Flash IDE’s visual authoring abilities. This means that you will be laying out the map and other interface elements by physically dragging and dropping them. Instead of by laying out elements programmatically, as required by the AJAX, JavaScript-Flash (JS-Flash) and Flex APIs, this API lets you drag and drop elements freely with precision. This approach may take a little longer. In the end, the time could be well worth it, as you will create one-of-a-kind elements that only your mashup will feature. Because not everyone is an artist, this chapter will guide you in setting up a simple layout first. More advanced visual elements will be suggested at the end of the chapter.
Chapter 17
The Big Idea As I mentioned earlier, Yahoo! Maps APIs are true “gateway” APIs. Once you start using the map API, you will be looking for another API or web service to mash it up with. So much is available that it can be difficult to choose a starting point. Once you get your first data source mashed up, it will be much easier to add the next one. For this mashup, you will combine the AS-Flash API with the Hot Jobs web service. HotJobs is Yahoo!’s job listing site. Its web service makes available a comprehensive list of job listings from around the world. What makes the HotJobs data so easy to mash up is that every job has a location. In other words, HotJobs data are location based, making them easy to integrate with the map API with no additional data. With job data and a map, you will create a mashup that lets users enter in a job keyword. The results of the search will be converted into several location-based job listings. These listings can be displayed on the map as individual markers with job title and additional details. If it sounds easy, that’s because it is. In determining your mashup idea, it is good to pick something that will be useful and attractive to the user. Putting data on a map lets you generate a unique perspective. If you are working with job descriptions, it makes for in interesting opportunity to show where in the country you can find the largest offerings of a particular type of job. Seeing markers representing individual jobs clustered together should convey just where in the country you can find a concentration of opportunities in a specific field.
Planning and Approach As with any application, planning and approach are important. It helps to know the APIs and web services you are working with very well. Having completed the previous chapters on the AS-Flash API, you should have all you need to work with the map. Later in this chapter, you will examine the HotJobs web service, how the request is constructed and what data to expect returned upon a successful request. Before coding, it is always good to lay out your objectives and then determine how best you will achieve them. Begin with thinking out what your application should achieve. Through the rest of the chapter, you will see how these steps are developed into the mashup.
1. 2. 3. 4. 5.
Display the map initially. Let the user enter search criteria. Request the data when the user submits his or her criteria. Receive the data. Display the data as markers on the map.
What you see listed here is a simple flow and this pattern of user interaction should be easily replicated with other APIs and web services. The mashup in this chapter will work with job data, so the criterion will be a keyword for job title or description. With another web service that criterion could easily change to a keyword for travel destination, weather report or concert lookup.
224
The AS-Flash Mashup
Setting the Stage This part of the chapter will guide you through laying out the visual elements of the mashup based on this list of actions you established above. Once again, you will use the Flash IDE to your advantage at first. Having many of the elements available to drag and drop will save initial time in getting the mashup up and running.
The Layout First, you need to itemize each interface element you will need to provide the user so he or she can interact with your mashup. Taking advantage of the pre-built V2 components that come with the Flash IDE, you will need to identify which components to use: ❑
The Yahoo! Maps API component to display the map
❑
Tools and widgets for the map API that will let the user interact with the map
❑
A Label component to prompt the user where to enter the keyword
❑
A TextInput component where the user will type in the keyword
❑
A button component that the user will click to submit the keyword
It is now time to add each of these items to the stage in Flash and begin to see the mashup take shape.
Add the Map Instance Creating the map instance requires you to compile the AS-Flash API in the Flash IDE. The resulting SWF will ultimately be connected to the Flex 2 application.
1. 2. 3. 4. 5. 6. 7. 8. 9.
Create a new .fla file and save it as as_mashup_scrolling.fla. In the properties panel, change the size of the stage to W:750, H:550. In the timeline panel, rename Layer 1 as myMap. Drag the Yahoo! Maps component from the components panel to the stage. Enter an instance name of myMap. Change the x/y coordinates of myMap to x:0, y:75. Change the width and height of myMap to W:750, H:400. Click the parameters tab, and in the table enter your appID. Enter an address of “Topeka, KS” (as shown in Figure 17-1).
225
Chapter 17
Figure 17-1
Add a User Toolbar Next you will add the user toolbar to the application. This will allow user input to control the data in your mashup.
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 226
Right-click the myMap layer and choose Insert Layer. Rename Layer 2 as Toolbar. Drag the Label component from the components panel to the stage. Enter an instance name of keywordLabel. Change the x/y coordinates of myMap to x:25, y:20. Change the width and height of myMap to W:100, H:22. Click the parameters tab and in the table enter “Enter Keyword:” in the text field. The stage should now look like Figure 17-2. Drag the TextInput component from the components panel to the stage. Enter an instance name of keywordInput. Change the x/y coordinates of myMap to x:110, y:18. Change the width and height of myMap to W:100, H:22. Click the parameters tab, and in the table enter “enter a keyword” in the text field (as shown in Figure 17-3).
The AS-Flash Mashup
Figure 17-2
Figure 17-3
227
Chapter 17 13. 14. 15. 16. 17.
Drag the Button component from the components panel to the stage. Enter an instance name of submit. Change the x/y coordinates of myMap to x:230, y:18. Change the width and height of myMap to W:100, H:22. Click the parameters tab, and in the table enter “Submit” in the label field (as shown in Figure 17-4).
Figure 17-4
18.
Save the file (Ctrl + S).
Coding the Mashup Finally, it is time to code and further develop the mashup. You will now learn how to use the HotJobs web server as well as review all the code necessary to make this mashup work. A great thing about map mashups is that once you build one application and mash it up with other data, it is easy to replicate the code. Swapping out one web service for another becomes easier each time you develop a mashup. The steps to discovering the web service and coding this mashup are simple and should serve as an effective template for further development with the AS-Flash API and other web services.
228
The AS-Flash Mashup
Exploring the HotJobs Web Service Since HotJobs is a property of Yahoo!, the support for the HotJobs web service is similar to that for the Yahoo! Maps APIs. Like maps, the HotJobs web service and its documentation are supported by the Yahoo! Developer Network (YDN). To check out the web service firsthand, visit http://developer .yahoo.com/hotjobs/index.html for the most up-to-date documentation and news. While you do not need an application ID for the HotJobs web service, you must agree to the terms and conditions of it as well as the usage terms of YDN. Please review the terms here at http://developer .yahoo.com/usagePolicy/ before proceeding with this mashup. The Hot Jobs web service, like most data APIs and web services within the YDN family, is not distributed via a component like the AS-Flash maps API. You retrieve data by making a request via URL and receiving a response in the RSS/XML standardized format. Flash works with XML very well and features an efficient, built-in XML class with a set of very simple methods. The benefit of using the HotJobs web service with this mashup is that it is very similar to several other YDN support APIs. While you are creating a solid mashup in this chapter, learning the HotJobs web service should set you up to easily adopt and mash up other similar APIs and web services.
HotJobs RSS Request Constructing the HotJobs RSS request is very simple. It is basically one URL that can have many variations. The principal request URL looks like this: http://hotjobs.yahoo.com/rss/version/country/state/ city/category/keywords
Like a method in the maps API, the HotJobs web service requires parameters to be passed. In this case, the parameters are actually placed within the context of the RSS request URL. Those parameters are Parameter
Type
Description
version
0
The version of the web service. Its value is 0 at the time of this writing.
country
String
A three-letter country code. Examples: USA, PHL (Philippines).*
state
String
A two-letter state code. Examples: MA, CA, FL.
city
String
City names with spaces need to be separated with plus signs.
category
String
A three-letter category code. Examples: MIS: Technology.*
keywords
String
Keywords with spaces need to be separated with plus signs.
* Visit the YDN documentation for full listings at http://developer.yahoo.com/hotjobs/index.html.
The following URL will retrieve all “Flash developer” job listings in the USA: http://hotjobs.yahoo.com/rss/0/USA/-/-/-/Flash+Developer
The following URL will retrieve all “mail room” job listings in New York, NY: http://hotjobs.yahoo.com/rss/0/USA/NY/New+York/-/mail+room
229
Chapter 17 Both URLs are identical up to the country code. The first example does not include a state, city or category. This unspecific search will return results based on keyword and country only. This is the format that will be used in this chapter so that data can be displayed for the entire USA. The second URL example is a little more specific and excludes only the category parameter. You can see with both URLs that multiple words in the keyword parameter need to be separated by a plus sign. You will see this again within the code you deploy later in this chapter.
HotJobs RSS Response The HotJobs RSS response comes back as XML in RSS-standardized format. Based on the URL and its parameters, the HotJobs web service will query its database and build and XML stream to return to you. The following is a sample request: http://hotjobs.yahoo.com/rss/0/USA/CA/Miramar/-/flight+instructor
And this is the XML response returned from the HotJobs web service: Yahoo! HotJobs: Flight Instructor http://hotjobs.yahoo.com/jobs/USA/All/All-jobs Top HotJobs results for jobs matching: flight instructor
[email protected] en-us Copyright (c) 2006 Yahoo! Inc. All rights reserved. Sun, 01 Jan 2006 00:00:01 -0700 100 http://us.i1.yimg.com/us.yimg.com/i/us/hj/hj-logo-yp-144.gif HotJobs.com weblogs http://hotjobs.yahoo.com/jobs/USA/All/All-jobs 144 22 Flight Instructor - Top Gun Flight School - Miramar, CA USA http:///hotjobs.yahoo.com/jobseeker/jobsearch/job_detail.html?job_id=abCDEFG< /link> Be the Best of the Best! Civilians are not saluted. 12345678 Fri, 16 May
Starting at the top of the XML is the xml header that tells your browser how to display the data. Within the rss and channel nodes is where the key data resides. The title, link and description detail the entire feed. Additional general information includes copyright information, the build record of the
230
The AS-Flash Mashup feed. Lastly, the ttl field communicates the “time to live” value of the feed. This is the time in minutes that the field should be cached. This gives you the option to set a timer for this value and recycle the field at certain intervals. Within the image node are data that support displaying the HotJobs logo with the data you display. You can see the path to the image, a title, a link to add to the image when it is clicked as well as the width and height properties of the logo. Adding the web service or API logo to display in your mashup is usually a requirement of the user terms. The item node is where the individual job data come from. Usually, this node will be repeated up to 50 times in a single response, detailing 50 separate job listings. It is from here that you will ultimately create a marker to display the information within. The HotJobs web service response is not a geoRSS feed, and so the location is not separated in its own set of nodes. Instead, every job listing title ends with the city, state and country of the job listing. Additional data available are a link to link back to the listing, description and the publisher data, pubDate. The guid field is the unique ID of the HotJobs listing.
Architecting the Mashup A very helpful step is to lay out the plan for your mashup. Often reserved for much bigger applications, this step really helps with coding and will let you program much more effectively and efficiently. Based on the known user behaviors of the application as well as what you know about the Yahoo! Maps ASFlash and HotJobs web services, you should be able to create a blueprint for what code will be needed.
1. 2. 3.
Import all classes that the map will need. Add an event handler when the button component is clicked. Add a conditional that checks for valid data in the TextInput component. This will prevent a request going through without user entry.
4.
Construct the URL for the HotJobs web service, including the value of the TextInput component as the job type parameter.
5. 6. 7.
Build a function that submits the request and loads the response into an XML object.
8.
Iterate through the array, adding a marker on the map based on the job location. Populate the marker with the job title and description.
Build a function to parse the successfully loaded XML into a well-organized object. Parse the object into relevant data and store each job title, job description and job location into an array.
Loading the XML You will now build the ActionScript class that will get the data from the web service for this mashup. This will be a separate, stand-alone file from the .fla file you’ve been working with.
1.
Using Flash (or another IDE like Eclipse, PrimalScript or SEPY), create a new ActionScript class file. Go to File ➪ New (Ctrl + N) and select ActionScript File.
2.
Save the file as getData.as in the same place as as_mashup_scrolling.fla.
231
Chapter 17 3.
Enter the following code to populate the class file:
//Import the Delegate class import mx.utils.Delegate; //Import the EventDispatcher class import mx.events.EventDispatcher; //Create the RSSData class class RSSData { //Declare the hjData Object private var hjData:Object; //Declare the dataXML XML Object private var dataXML:XML; //Declare the addEventListener Function public var addEventListener:Function; //Declare the addEventListener Function public var removeEventListener:Function; //Declare the dispatchEvent Function public var dispatchEvent:Function; //The constructor function for this class function RSSData() { //Initialize the EventDispatcher class EventDispatcher.initialize(this); } //Function to make the web service call public function getData (url:String) { //Create the dataXML instance dataXML = new XML(); //Ignore whitespace of returned data dataXML.ignoreWhite = true; //Set onload event when data is returned dataXML.onLoad = Delegate.create(this, parseXML); //Load web service url dataXML.load(url); }
4.
232
Save the file (Ctrl + S).
The AS-Flash Mashup The first step, just as you determined in the architecting step earlier, was importing the necessary classes. Here the Delegate class is imported. This class enables you to call other methods in your code based on inline events. Since events cannot call methods directly, using this class’s create method lets the method call retain scope relative to the class and not the event. Also imported is the EventDispatcher class. In previous chapters, you learned the thorough inventory of events the maps API dispatches. This class will enable your code to execute the same dispatch events with event data objects when certain things occur. This class allows for events and data to be “bubbled up,” a phrase given to the physical surfacing of events, to other classes in your mashup application. This section of the code is being written as a class. After declaring the class and its name, you need to declare all the class variables you will use. These include the hjData (HotJobs data) object and the dataXML object. Both will help store and parse data when it is returned. //Declare the addEventListener Function public var addEventListener:Function; //Declare the addEventListener Function public var removeEventListener:Function; //Declare the dispatchEvent Function public var dispatchEvent:Function;
The next set of variables (extracted in the previous code) declare the functions of the DispatchEvent class. They are declared as public, making these functions available to other classes, as you will see later in this chapter. Because the function’s code is already set up in the EventDispatcher class, you do not need to build it. Next, you build the constructor function for the class. This is the function that is called when this class is instantiated. Within the function, you are initializing the EventDispatcher class by calling its initialize method. You will recall the initialize event that occurs when the map component is added to the stage and compiled. Components initialize when they are added as opposed to stand-alone classes, which must be initialized or instantiated with code. The next function, getData, will be called by the application when it needs to make a request to the HotJobs web service. It is declared as public so it can be accessed by other classes. Accepting one parameter, url, as a string, this function will make a request based on that URL. //Create the dataXML instance dataXML = new XML(); //Ignore whitespace of returned data dataXML.ignoreWhite = true; //Set onload event when data is returned dataXML.onLoad = Delegate.create(this, parseXML); //Load web service url dataXML.load(url);
233
Chapter 17 dataXML is the new instance of the XML object. The XML class is built into Flash, so no class needs to be
imported for this. As with any class, once you create an instance of it, you then have methods that can be called against the instance object. IgnoreWhite is a method of the XML class that helps ill-formatted XML responses to be properly interpreted by your code. This method pulls together the incoming XML stream so it is cleaner for your code to work with. onLoad is an event handler method of the XML class. Like other events, it is fired when a certain code execution occurs. In this case, onLoad is called when the XML has successfully loaded. As you have learned, events need to be carried forth by a function, and onLoad is no different. Using Delgate .create, you can define another function in the class to carry on the event’s message, including any data it contains. Here, you will call the parseXML function. (This will be discussed in the next section.)
The load method requires the path of the XML that you want to load. Since the HotJobs web service URL will return XML in its response, the URL for that web service is an acceptable parameter. It may seem out of order, establishing what the XML object should do with its loaded data before loading the data itself. The onLoad event is usually coded before the load method in case the XML is available instantaneously. If this should happen, the XML object will already know how to handle the loaded data. Although this mostly happens when you are working with a local XML file, it is good to abide by this practice.
Parsing the XML You will now complete the RSSData class by adding a function to parse the data.
1.
With getData.as open, paste the following code at the bottom: //Function to parse the XML returned function parseXML(success:Boolean) { //Only parse if data is returned if (success) {
//Create nodes array to temporarily store XML var nodes:Array = dataXML.firstChild.firstChild.childNodes; //Instantiate hjData object hjData = new Object(); //Create hjItems array to store items within Object var hjItems:Array = new Array(); //Create item_arr array var item_arr:Array = Array(); //For each loops through nodes array for (var i=0;i {mapViews}
6.
Save the file and run the application (in the toolbar, click the green circle with white arrow, or press Crtl+F11). The Yahoo! Maps AS-Flash API will load within the Flex 2 application (shown in Figure 19-5).
Along the top of the centered map should be a label touting “Flex 2 + AS-Flash API Y! Maps Mashup.” You should also see a TabBar with tabs representing each of the map views and an hSlider ranging from 1 to 16. This represents the zoom level range of the map.
265
Chapter 19
Figure 19-5
After you defined the XML header and application container tag, the first thing you added was the MapConnector namespace. This established the instance of the local connection and enabled it to be
referenced throughout the MXML. The ActionScript embedded in the mx:Script container handles events fired from user interaction elements from within the Flex application. When the TabBar is clicked, the clickEVT function will be called and will pass the new map view type in setMapviewType. This request is sent through the local connection where it will be picked up on the Flash client side and called against the map instance. Similar activity happens when the hSlider is engaged. In this case, it is ultimately setZoomLevel with the new zoom level value that will be called against the map instance. The next two chapters will feature several examples of methods available in the AS-Flash API. You will be reusing what you have established in this chapter to code and test a wider array of methods using this solution.
Summar y In this chapter, you faced your toughest challenge yet. However, you now have created a solid base application for whatever Flex 2 Yahoo! Maps applications you choose to make.
266
Get Started with Yahoo! Maps and Flex 2 From here on in, consider yourself in elite company, having completed the following: ❑
Acquiring an AppID and setting up the AS-Flash API component in the Flash IDE.
❑
Compiling the asFlashAPI.swf that will connect to and receive requests from the local connection.
❑
Coding the MapConnector class to enable communication between the Flash and Flex clients. This class sends and receives method calls, passing their data as objects. It also registers both clients.
❑
Finally, you created your first MXML file and Flex 2 application. This application and its code will not go to waste, as it is now the foundation for you to implement many new API methods over the next two chapters. This will lead to developing an exciting Flex 2 Yahoo! Maps mashup in the final chapter.
267
20 Basic Methods: Flex 2 Using the AS-Flash API In the last chapter you learned steps to begin developing Yahoo! Maps applications with Flex 2 and the ActionScript-Flash (AS-Flash) API. You built the base application that you will now put to further use. In this chapter you will learn how to adapt the base application to include many of the basic methods available in the AS-Flash API. By easily modifying the Flash client, MapConnector class and Flex client parts of the application, you will accomplish the following: ❑
Control different map aspects with setZoomLevel, setCenterByAddress and setCenterByLatLonAndZoom
❑
Learn to use the property’s get methods and how they can be used to further your application
❑
Use Flex 2 components to control the map
Basic API Methods Having completed the JavaScript-Flash (JS-Flash) API and the AS-Flash API, you will likely be familiar with many of the basic API calls. As you go through this chapter, keep in mind that using Flex 2 and the AS-Flash API requires its own unique code and approach. What you learned in previous chapters will help, but you should pay special attention to the naming conventions and parameters passed to each method. The sample code and examples in this chapter will feature one method from each set of similar methods available in the AS-Flash API. You will see that these code samples and examples will be a bit lengthier than others as they walk you through modifying the Flash client, MapConnector class and Flex client parts of the application.
Chapter 20
Map Set Methods These basic methods are responsible for changing properties of the map. You will recognize quickly that the naming convention of these methods reflects exactly what each method does. This is to make it easier to code with them as well as for other developers to identify their purpose in your application.
setCenterByAddress() The setCenterByAddress() method accepts two parameters, address and duration. A successful address is a full street address with city, state and ZIP. (Certain major metropolitan areas will work as well.) The address is converted by the API geo-coder into a latitude and longitude, and the map reloads its tiles and centers on that value. To handle this transition smoothly, you can use the duration parameter to tell the API how long it should take to pan from its current position to the new one you have defined. The duration parameter is the number of milliseconds the map will take to pan. mapInstance.setCenterByAddress(address:String, duration:Number);
This example shows what the code would be like to change the address to San Francisco and pan from its current location for 300 milliseconds: For the Flex client: var address:String = “San Francisco” var duration:Number = 300; mapConnector.setCenterByAddress(address, duration);
For the MapConnector class: public function setCenterByAddress (address:Number, duration:Number):void { send(“_flashClient”,” setCenterByAddress “, { address:address, duration:duration}); }
For the Flash client: myMap. setCenterByAddress(address, duration);
Some useful events are fired when setCenterByAddress() is called. EVENT_MAP_GEOCODE_SUCCESS is dispatched when the API has successfully geo-coded the address passed in and has resolved it as a latitude/longitude coordinate. If the address entered cannot be geo-coded, then the EVENT_MAP_ GEOCODE_ERROR is broadcast. If this should happen, an array of suggested addresses will be sent as a data object with this event along with the originalAddress. You can use the message attribute returned with this event to alert users to try a new address or select a suggested one. Because international geo-coding recognizes so many variations of city names, it is difficult to generate a geo-coded error event.
270
Basic Methods: Flex 2 Using the AS-Flash API setCenterByAddressAndZoom() Developers looking to change the map location and zoom level in one shot have some options. setCenterByAddressAndZoom() is a very capable method and combines the power of setCenterByAddress() with setZoomLevel(). The order of operation for this method is as follows:
1.
The method is called:
mapInstance.setCenterByAddressAndZoom(address:String, zoomLevel:Number, duration:Number);
2.
The address is geo-coded firing either EVENT_MAP_GEOCODE_SUCCESS or EVENT_MAP_ GEOCODE_ERROR.
3. 4. 5.
The map pans based on the duration, in milliseconds, defined in the duration parameter. The map centers on the resolved latitude/longitude coordinate. The map zooms in to the level defined in the zoomLevel parameter.
Now it’s time to try this out in an example using Flex 2 and the AS-Flash API approach to building Yahoo! Maps API applications in Flex. In this example, you will adapt the base application (from the last chapter) to receive an address from the user and display that address on the map.
Try It Out
Let Your Users View a Location by Address
In this example, you will need to modify each of the three application parts you created in the last chapter. Start with the Flex client first by modifying the MXML in Flex Builder 2.
1. 2. 3.
Open the Flash document asFlashAPI.fla.
4. 5.
Go to Window ➪ Development Panels ➪ Actions and select it (or press F9).
Save it as asFlashAPI_address.fla. Select the first frame in the timeline. If the timeline is not visible, go to Window ➪ Timeline (Crtl + Alt + T).
Replace the contents of the actions panel with the following code:
//Create local connection object var connectedMap:LocalConnection = new LocalConnection(); //Import PanTool class import com.yahoo.maps.tools.PanTool; //Add Initialize Event Listener to map instance myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap); //Function that executes when initialize event is fired function onInitMap(eventData) { //Add the PanTool to the map instance
271
Chapter 20 myMap.addTool(new PanTool(), true); //Send event via local connection connectedMap.send(“_flexClient”,”mapInitialized”); } //Listen for setCenterByAddress from local connection connectedMap.setCenterByAddressAndZoom = function (connectionData:Object):Void { //Change map address and zoom level myMap. setCenterByAddressAndZoom (connectionData.address, connectionData.zoomLevel); } //Connect to local connection as _flashClient connectedMap.connect(“_flashClient”);
6.
Save the file (Ctrl + S) and compile the movie.
Even though this is not your final product, it is necessary to compile the .fla in order to create the SWF as well as to ensure that the map API component is resolving properly. In this part of the example, you have added the setCenterByAddressAndZoom ability to the Flash client. This enables this part of the application to listen for this call, which will be passed through the local connection. You will now add the ability for the local connection to communicate this call by modifying the MapConnector class. This part will receive the call from the Flex client and pass the call and its data in an object to the Flash client.
1. 2. 3.
In the IDE of your choice, open MapConnector.as. Save it as MapConnector_address.as. Enter the following code to populate the file:
package { //Import the local Connection class import flash.net.LocalConnection; //Declare the class MapConnector extending the LocalConnection class public class MapConnector_address extends LocalConnection { //Declare the isInitialized variable private var isInitialized:Boolean; //Declare the mapConnector constructor public function MapConnector_address (server:String = “_flexClient”) { //Try to connect to Flex Client and see if error occurs
272
Basic Methods: Flex 2 Using the AS-Flash API try { connect(server); } catch (error:ArgumentError) { // server already created/connected } //Instantiate the extended Local Connection class super(); } //Function called when map is initialized by Flash client public function mapInitialized():void { isInitialized = true; } //Function called when Flex client calls for map center and zoom level to change public function setCenterByAddressAndZoom (address:String, zoomLevel:Number):void { //Conditional to make sure map is initialized for attempting map control if(isInitialized) send(“_flashClient”,” setCenterByAddressAndZoom”, { address:address, zoomLevel:zoomLevel }); } } }
4.
Save the file. Make sure it stays in the same directory as the SWF and the MXML you are working with.
With this part of the example, you have now coded the MapConnector class (now MapConnector_ address) to accept the setCenterByAddressAndZoom and pass it and its data along to the Flash client. Note that best practice would be not to modify the MapConnector class name. As you work through the book, though, you may find it easier to keep all of these files relative to each other for easier reference. In order for them to co-exist, they need unique names. Finally, it is time to recode the Flex client part of the application. You will modify the interface as well, giving the user a control with which to enter an address. You will also add a button that lets the user submit both the entered address as well as the new zoom level.
1. 2.
In Flex Builder 2, open Flex2Maps.mxml. Save it as Flex2Maps_address.mxml. Remember to save it in the same directory as asFlashAPI_ address.swf and MapConnector_address.as.
273
Chapter 20 3.
Replace the existing MXML with the following:
4.
Save the file and run the application (in the toolbar click the green circle with white arrow, or press Crtl + F11). The Yahoo! Maps AS-Flash API will load within the Flex 2 application, as shown in Figure 20-1.
Along the top of the centered map should be a label instructing the user “Set Address/Zoom.” You should also see a TextInput to accept an address and an hSlider ranging from 1 to 16. This represents the zoom level range of the map. Lastly, a button labeled Refresh Map exists, and when it is pressed, the map should recenter and zoom to the values defined. Try it out by entering an address and changing the zoom level.
274
Basic Methods: Flex 2 Using the AS-Flash API
Figure 20-1
How It Works Closely based on the functionality you coded in the last chapter, this exercise should not be too much of a brain buster. Instead of the TabBar, you now have a text field and you’ve added a button. As you coded events to handle the TabBar and hSlider, you coded one here to handle the button press. When the user presses the Refresh Map button, the values from the new TextInput and hSlider controls are sent to the local connection with the call setCenterByAddressAndZoom(). The local connection instance, now instantiated by the class MapConnector_address, receives the call and data from the Flex client and passes them to the Flash client. There, the SWF you created hears the call and channels the data into the method (of the same name) against the map instance. You should use the approach in this example as you try out the rest of the methods and sample code in this chapter.
setCenterByLatLon() If you know the latitude/longitude coordinate you want to center the map on, you can use setCenter ByLatLon(). A major benefit of this method is that it executes much faster than setCenterByAddress(). This is because this method does not need to geo-code an address and resolve a latitude/longitude, since it already knows it.
275
Chapter 20 setCenterByLatLon() also accepts the duration parameter. Since there is no conversion between address and lat/lon, the panning effect will engage much more quickly: mapInstance.setCenterByLatLon (latlon:Latlon, duration:Number);
You’ll notice that the latlon variable does not belong to any of the variable types defined in the last chapter. That is because the latlon variable being passed is an instance of the map API’s Latlon object. You must pass a Latlon object as the first parameter of the setCenterByLatLon() method, and to do that, you must cast the latitude/longitude you want to pass as one. To create a Latlon object, using the coordinates 40.713696,-74.00564 for New York City, you must import or reference the Latlon class. The following code demonstrates this using the setCenterByLatLon() method: For the Flex client: var latlon:Object = new com.yahoo.maps.LatLon(40.713696,-74.00564); var duration:Number = 300; mapConnector. setCenterByLatLon (latlon, duration);
For the MapConnector class: public function setCenterByLatLon (latlon, duration:Number):void { send(“_flashClient”,” setCenterByLatLon “, { latlon:latlon, duration:duration}); }
For the Flash client: myMap.setCenterByLatLon (latlon, duration);
setCenterByLatLonAndZoom() Like setCenterByAddressAndZoom(), this method gives you access to a lot of functionality in one shot. The sequence, as reviewed before, is slightly different as no address must be converted to latitude/ longitude; if you have selected this method, you already know the latitude and longitude. As a result, this method, like its simpler counterpart setCenterByLatLon(), works a bit more efficiently, thus generating faster results. The order of operation for this method is as follows:
1.
The method is called:
mapInstance.setCenterByLatLonAndZoom (latlon:LatLon, zoomLevel:Number, duration:Number);
2. 3.
276
The map pans based on the duration, in milliseconds, defined in the duration parameter. The map centers on the resolved latitude/longitude coordinate.
Basic Methods: Flex 2 Using the AS-Flash API 4.
The map zooms in to the level defined in the zoomLevel parameter.
Common usage of this method looks like this: For the Flex client: var latlon:LatLon = new com.yahoo.maps.LatLon(40.713696,-74.00564); var zoomLevel:Number = 6; var duration:Number = 3000; mapConnector. setCenterByLatLonAndZoom (latlon, zoomLevel, duration);
For the MapConnector class: public function setCenterByLatLonAndZoom (latlon, zoomLevel:Number, duration:Number):void { send(“_flashClient”,” setCenterByLatLonAndZoom “, { latlon:latlon, zoomLevel: zoomLevel, duration:duration }); }
For the Flash client: myMap. setCenterByLatLonAndZoom (latlon, zoomLevel, duration);
setZoomLevel() setZoomLevel() sets the zoom level of the map. It accepts one parameter, a number, that is the value of the zoomLevel you want to change the map to. The zoomLevel can be set to a value between 1 and 16. mapInstance.setZoomLevel(zoomLevel:Number);
In this sample, the zoomLevel is set to 6: For the Flex client: var zoomLevel:Number = 6; mapConnector. setZoomLevel (zoomLevel);
For the MapConnector class: public function zoomLevel (zoomLevel:Number):void { send(“_flashClient”,” setZoomLevel “, { zoomLevel: zoomLevel }); }
For the Flash client: myMap. setZoomLevel (zoomLevel);
277
Chapter 20 Two events are broadcast when the zooming is engaged in the API. EVENT_ZOOM_START is fired when the API starts zooming and EVENT_ZOOM_STOP is sent when the API has completed zooming. You can set the zoomLevel with user interaction. You can design buttons to increase or decrease the zoom level of the map. You can combine those buttons with a slider, ranging in value from 1 to 16, to create a zoombar. In Chapter 16, “AS-Flash API Advanced Features,” you learned how to use the NavigatorWidget, an interface that combines a zoombar with other useful tools to help users navigate your map. Refer to the base application you developed in the last chapter to see a fully integrated example of setZoomLevel.
setCenterByPointDelta(point, duration) setCenterByPointDelta() is a unique means of recentering the map that lets you use other relative points on the stage. A point is a pixel coordinate defined by an x/y position. The first parameter of this method is not a point on the map, like a latitude/longitude coordinate, but rather the total difference of points within the map tile matrix.
Keep in mind that you are not moving the map to a specific point. You are moving it the difference in x/y from its current position. In other words, if you were using this method to pan the map to the right 20 pixels and down 30 pixels, you would pass a point value of (-20, -30). Essentially, the map’s center moves up and to the left, revealing more area to the bottom and to the right. Using this method, you can have the map pan over to center on other elements added to the map application. These can be design elements added programmatically or via the visual authoring methods you learned in the last chapter. This method can be used with markers. (Examples later in the chapter will explore those possibilities.) The point parameter of this method works similarly to how the latlon parameter related to the Latlon object in setCenterByLatLon() and setCenterByAddressAndZoom(). The point is not a number or Latlon object, but a point object. To properly pass this value, you must call in the Point class. Unlike the Latlon class, which is packaged with the API, the Point class is available as part of the Flash MX package. Here is how to properly call the setCenterByPointDelta() method by creating an instance of a Point first. For the Flex client: var point:Object = new mx.graphics.Point(100, 100); var duration:Number = 3000; mapConnector. setCenterByPointDelta(point, duration);
For the MapConnector class: public function setCenterByPointDelta (point, duration:Number):void { send(“_flashClient”,” setCenterByPointDelta “, { point :point , duration:duration }); }
278
Basic Methods: Flex 2 Using the AS-Flash API For the Flash client: myMap.setCenterByPointDelta (point, duration);
setMapViewType() You learned in the last chapter that one of the default properties of the API is the map view type. The three map view types are map for map tiles, satellite for satellite tiles and hybrid for a view that features a combination of map tile elements layered on top of satellite tiles. mapInstance.setMapViewType (mapViewType:String);
The setMapViewType() accepts one parameter, the map view type you want to change the map to. However, to ensure that the map view type is always correct, you should import or reference the MapViews class. Here is how the setMapViewType() call should look. For the Flex client: var newMapViewType:String = com.yahoo.maps.MapViews.SATELLITE; myMap.setMapViewType (newMapViewType);
For the MapConnector class: public function setMapViewType (mapViewType:String):void { send(“_flashClient”,” setMapViewType “, { mapViewType:mapViewType }); }
For the Flash client: myMap.setMapViewType (mapViewType:String);
This call will change the map view type to satellite, pulling the static property represented by com.yahoo.maps.MapViews.SATELLITE as the parameter. Later in the chapter, you will see how the get methods getCurrentMapViewType() and getMapView Types() help you design your own custom set of buttons that let users toggle among map views. In the next chapter, you will discover the satelliteControlWidget, a prepackaged interface that does the same thing.
Map Get Methods Using these methods will let you retrieve map settings for use in other functions in your application. These methods are coded to return the values they correspond to. Just as with the set methods, the naming convention of these methods helps you identify what data they will return to you.
279
Chapter 20 Get methods work very efficiently in the API. Since the value is already set, most likely by you calling the set method counterparts of the get methods, all the API needs to do is return the value to you. For development, get methods are very easy to implement, as they require no parameters to operate.
As you code your application, you will find that get methods make development much easier. Rather than make sure your code “remembers” what values have been set throughout your application’s operation, you can call a get method anytime and have the latest value. The get methods also help with user interface implementation. You will need a starting point, a default value at which to position your user interface elements. The get methods will provide those data. Coding get methods for Flex 2 with the AS-Flash API is a bit challenging. It requires an additional layer of code on top of what you used to integrate set methods. The reason for this is that not only does Flex 2 send a callout, it must be set up to receive the data being returned. This means that the local connection must be set up to handle two-way communication. While the process is a bit extensive, the results are rewarding and will pay dividends overall in the performance of your mashup.
getCenter() getCenter() returns the pixel coordinate the map is centered on as a Point coordinate. Remember that
this value looks like a latitude/longitude coordinate, but is actually an x/y coordinate. mapInstance.getCenter() : Point;
Now it’s time to try this out in an example using Flex 2 and the AS-Flash API approach to building Yahoo! Maps API applications in Flex. You will once again adapt the base application (from the last chapter and used earlier in this chapter) to pass a getCenter() call and receive what it returns through the local connection.
Try It Out
Display the Map’s Center Coordinates
In this example, you will need to modify each of the three application parts you created in the last chapter. Start with the Flex client by modifying the MXML in Flex Builder 2.
1. 2. 3.
Open the Flash Document asFlashAPI.fla.
4. 5.
Go to Window ➪ Development Panels ➪ Actions and select it (or press F9).
Save it as asFlashAPI_getCenter.fla. Select the first frame in the timeline. If the timeline is not visible, go to Window ➪ Timeline (Crtl + Alt + T).
Replace the contents of the actions panel with the following code:
//Create local connection object var connectedMap:LocalConnection = new LocalConnection(); //Import PanTool class import com.yahoo.maps.tools.PanTool; //Add Initialize Event Listener to map instance myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap); //Function that executes when initialize event is fired
280
Basic Methods: Flex 2 Using the AS-Flash API function onInitMap(eventData) { //Add the PanTool to the map instance myMap.addTool(new PanTool(), true); //Send event via local connection connectedMap.send(“_flexClient”,”mapInitialized”); } //Listen for getCenter from local connection connectedMap.getCenter = function ():Void { //Save getCenter value to mapCenter variable var mapCenter = myMap.getCenter(); //Send event mapGetCenter with mapCenter value as event data connectedMap.send(“_flexClient”,”mapGetCenter”, {mapCenter:mapCenter}); } //Connect to local connection as _flashClient connectedMap.connect(“_flashClient”);
6.
Save the file (Ctrl + S) and compile the movie.
In this part of the example, you have added the getCenter ability to the Flash client. The SWF can now receive the getCenter call from the Flex 2 client through the local connection script. When the Flash client gets the call, it turns around and sends the data back to the local connection, where they will ultimately be received by the Flex client. You will now add the ability for the local connection to communicate this call by modifying the MapConnector class. This part will receive the call from the Flex client and pass the call and its data
in an object to the Flash client.
1. 2. 3.
In the IDE of your choice, open MapConnector.as. Save it as MapConnector_getCenter.as. Enter the following code to populate the file:
package { //Import the local Connection class import flash.net.LocalConnection; //Declare the class MapConnector extending the LocalConnection class public class MapConnector_getCenter extends LocalConnection { //Declare the isInitialized variable private var isInitialized:Boolean; //Declare variable to register FlexClient private var flexClient:Object;
281
Chapter 20 //Declare the mapConnector constructor public function MapConnector_getCenter(server:String = “_flexClient”) { //Try to connect to Flex Client and see if error occurs try { connect(server); } catch (error:ArgumentError) { // server already created/connected } //Instantiate the extended Local Connection class super(); } //Function called by FlexClient to register itself with the local connection public function registerClient(client:Object):void { flexClient = client; } //Function called when map is initialized by Flash client public function mapInitialized():void { isInitialized = true; } //Function called when Flex client calls for getCenter data public function getCenter():void { //Conditional to make sure map is initialized for attempting map control if(isInitialized) send(“_flashClient”,”getCenter”); } //Function called when getCenter data is returned by Flash Client public function mapGetCenter(connectionData:Object):void { //Call onGetCenter on the registered FlexClient to pass getCenter returned data flexClient.onGetCenter(connectionData); } } }
4. 282
Save the file. Make sure it stays in the same directory as the SWF and the MXML you are working with.
Basic Methods: Flex 2 Using the AS-Flash API With this part of the example, you have coded the MapConnector class (now MapConnector_getCenter) to accept the getCenter call and pass it to the Flash client. The MapConnector_getCenter class is set up to let the Flex client register itself. This enables the mapConnector instance to call a method on the Flex side when the getCenter data come back through the local connection. The Flex client side will now be re-coded to work for this example. The user interface modifications will enable you to request getCenter by clicking a button, which will display its returned data in a text field.
1. 2.
With Flex Builder 2, open Flex2Maps.mxml.
3.
Replace the existing MXML with the following:
Save it as Flex2Maps_address.mxml. Remember to save it in the same directory as asFlashAPI_address.swf and MapConnector_getCenter.as.
283
Chapter 20
4.
Save the file and run the application (in the toolbar click the green circle with the white arrow, or press Crtl + F11). The Yahoo! Maps AS-Flash API will load within the Flex 2 application (shown in Figure 20-2).
Figure 20-2
Along the top of the centered map should be a button labeled Call getCenter. When it is clicked, the request will travel through the local connection to the Flash client. The data are returned in the Flash client and travel back through the local connection, where they will ultimately be displayed in the text field.
284
Basic Methods: Flex 2 Using the AS-Flash API How It Works The button press fires an event that prompts the Flex client to call the getCenter method on Map Connecter_getcenter, representing the local connection. There the method is passed through the local connection, where it is picked up by the Flash client. In the SWF, getCenter is now called against the map API instance. The returned data from getCenter are saved and wrapped up as data that are passed in an event to the local connection. MapConnector_getCenter fields the data and passes them in a final call to the registered Flex client.
Additional Get Methods of the AS-Flash API In addition to getCenter(), you can use the following get methods to retrieve accurate data from the map instance. You can easily replicate the example you just completed for each of these get methods: ❑
getZoomLevel(): The getZoomLevel() method lets you obtain the current zoom level of the map. It can be used to adjust a custom zoombar or zooming interface that you have created. As you will see in the next chapter, knowing the current zoom level plays a key role in using overlays and other custom features of the API.
❑
getCurrentMapViewType(): You want to call getCurrentMapViewType() to determine what tiles the map is currently displaying. This is useful if you have created your own buttons that let your users toggle among map view types. You may also include some effects in your application that activate depending on what layer is currently being displayed.
❑
getMapViewTypes(): This method is most useful if you want to create your own map view buttons. Letting your users choose their map view can add a hint of customization to the application. Not to mention that being able to display satellite images of the world, from space all the way down to street level, is quite an enticing feature that will draw users to your mashup.
Summar y This chapter introduced you to several of the basic methods available in the AS-Flash API when it is used with Flex 2. The two major examples represent big steps that you have taken in creating your mashups. In the next chapter you will be reintroduced to the more advanced methods and classes of the AS-Flash API. This time, you will learn how to adapt these methods to work with the Flex client, MapConnector local connection class and Flash client.
285
21 Advanced Features: Flex 2 Using the AS-Flash API Back in Chapter 16, “AS-Flash API Advanced Features,” you learned in great detail about the advanced capabilities of the ActionScript-Flash (AS-Flash) API. This chapter will re-familiarize you with those capabilities and present some examples of implementing advanced AS-Flash API with Flex 2. While much of this chapter will be a review, you should keep the templates you developed in the last few chapters ready. Each of the classes, events and methods can be applied to the Flex 2 AS-Flash API architecture you have already been implementing. In this chapter you will ❑
Review advanced methods, classes and events of the AS-Flash API
❑
Compile AS-Flash API examples for inclusion in Flex 2
❑
Build local connection classes to allow communication in support of certain advanced methods
❑
Code Flex 2 example applications that incorporate advanced AS-Flash API methods within their functionality and integrate maps
Advanced AS-Flash API Classes Developing with the AS-Flash API for Flex 2 requires you to know as much about the API as possible. Now that you’re thinking Flex 2, it is necessary to review the advanced API classes and capabilities. Having learned the basic methods of this API and applied some of them to the Flex 2 environment, you should get familiar with the advanced methods and objects that can make your map application more complete.
Chapter 21
Reviewing Objects and Methods Having learned the basic functionalities of the AS-Flash API, it’s time to dig deeper. The following methods and objects, while not used as frequently, are very powerful in enabling advanced map application development: ❑
LatLonRect defines the boundaries (commonly referred to as the bounds or envelope) of the map being displayed. This object contains four properties that when combined can let your application determine what to display and what is being displayed.
❑
getBounds() returns a LatLonRect representing the existing boundaries of the map being displayed. This method is useful for overlaying other map data on top of the map API tiles. In other words, this information lets you sync up other data tiles. Certain data, like land parcels and school zones, are available from various services. The setBounds() method passes a LatLonRect to change the current boundaries of the map and effectively modify the map being displayed.
❑
setBounds() passes a LatLonRect to change the current boundaries of the map and effectively modify the map being displayed.
Reviewing Events As you have learned, events can be instrumental in controlling the timing of your application. While reviewing these events, keep in mind that the data fired with the event can be as important as the event type itself. It is always good to explore the data object returned with an event when you first use it. In creating your Flex 2 to AS-Flash API application, you can explore the event’s data very easily when you construct your base SWF. ❑
EVENT_MOVE is broadcast whenever the map moves, whether by panning, zooming or recentering. The detection can be user-initiated or based on code that is executed. This event comes with a lot of useful data each time it is fired. Using the for/in method, you can drill down into the event’s object and trace out the object’s properties and values.
❑
EVENT_PAN_START and EVENT_PAN_STOP are broadcast when the map starts and stops panning respectively; they are often tied to the setCenterBy methods discussed in the last chapter. The pan events do not include much data with them other than the standard target and type properties. However, they can be very useful in timing the activity of design and interface elements in your application. The benefit of the pan tool is that when it fires, you know that the location the map is centering to, whether a latitude/longitude or address, has already been resolved. The setCenterByAddress method inside the onInitMap function is responsible for making the map pan. Since the listeners have been added for pan starting and pan stopping, their respective onPanStart and onPanStop functions will carry out the event. The trace methods tell you when those events fired. You can replace them with other useful calls to perform actions throughout your application.
❑
288
EVENT_ZOOM occurs when the map zooms because of methods like setCenterByLatLon, setCenterByAddressAndZoom and setCenterByLatLonAndZoom. This event carries with it a lot of useful data that can be used to reset values throughout your application. Depending on the complexity of your map mashup, you may want to keep track of the map’s zoom level and other properties by updating variables. In addition, whenever the map changes location and zoom, it’s important to track those properties to enable precise movements of the other elements in your application.
Advanced Features: Flex 2 Using the AS-Flash API ❑
EVENT_ZOOM_STOP and EVENT_ZOOM_START pair up much like the pan events discussed earlier and are dispatched when the map begins zooming and when it ends, respectively. These work like EVENT_ZOOM, but offer even more precise timing when they are fired. These events enable you to trigger other actions in your application exactly when the map starts zooming and exactly when it stops. The data available are similar to that in EVENT_ZOOM, just without the currentZoomLevel property.
Working with Widgets Widgets are the prepackaged sets of user interfaces that ship with the map API. They reflect some of the most commonly used technology on consumer map applications like Yahoo! Maps. Adding existing widgets can save you time over having to replicate the functionality with your own UI. Applying this knowledge to your existing asFlashAPI, MapConnector and Flex2Maps classes requires little modification.
Widget Methods The simple methods available for widgets are part of the map class. These methods are available when the map instance is initialized. However, without importing the class of the widget you want to add, you cannot use these methods.
addWidget() This method simply adds a widget to your map instance. In most cases, you will want to create an instance of the widget first and then plug that instance name into the method as its lone parameter. mapInstance.addWidget(widget:Object);
removeWidget() Like the tool methods, this widget removes the widget, effectively deactivating its functionality to the user. It too accepts just one parameter, the instance name of the widget it is removing. mapInstance.removeWidget(widget:Object);
Widget Classes These classes included with the API come with all you need to turn on each of their compact functionalities for your users. Each class must be imported and you should create an instance of the widget before adding it to the map. This lets you reference that instance throughout your code, so you can remove it more easily and add event listeners to it. ❑
NavigatorWidget: The Navigator represents the most functional out-of-the-box feature that comes with the API. While not customizable in appearance, the Navigator widget provides several functionalities with very little code. The NavigatorWidget has the ability to appear open (expanded) or closed (collapsed). Two methods, open() and close(), are included in the class. They can be called against the widget’s instance to change its state after it has been added.
❑
ToolBarWidget: This widget adds a menu of icons to the top-left corner of your map. It acts as a start menu, like the one found at the base of the screen in your operating system. Its contents are a row of icons, each representing a tool that you have added to the map.
289
Chapter 21 ❑
SatelliteControlWidget: The satelliteControlWidget class attaches three predesigned buttons to the map that allow users to toggle among the map view types. Once again, this is a great alternative to creating and coding your own buttons if time is important. These buttons are set to detect the existing map view type and will reflect that by selecting the corresponding type’s button in the widget.
Working with Tools Tools are features of the map that leverage mouse interaction. Two tool classes are included with the AS-Flash API. The pan tool is what enables the drag-panning feature that has become standard in the current generation of richer map applications. This functionality is not available by default and needs to be added. The other tool class is CustomSWFTool, which enables you to create your own tool with which your users can better engage with the map.
Tool Methods The tools are available with the map class that is loaded by default when the map instance is created. They are responsible for adding, removing and activating the tools you make available to your users. A special widget, discussed later in this chapter, adds a menu of tools to your map application. This is called the ToolBarWidget and its contents depend on the results of these methods.
addTool() A simple method that lets you add instances of tools to the map. This method must be called after the map instance initializes, and is usually placed within onInitMap. mapInstance.addTool(tool:Object, isActive:Boolean);
In order to add a tool, you must first import that tool’s class and create an instance of it. That instance is the first parameter of this method. The second parameter is isActive. When it is set to true, the tool will be added and become active to your users right away.
setActiveTool(tool) Should you add a tool with isActive set to false, you will need to run this method later in your code. This method accepts just one parameter, and that is the instance of the tool you want to activate. mapInstance.setActiveTool(tool:Object);
removeTool(tool) removeTool() is used to remove and thus reactivate the tool from the map instance. Its only parameter is the instance of the tool it is called to remove. mapInstance.removeTool(tool);
290
Advanced Features: Flex 2 Using the AS-Flash API
Tool Classes Tools offer a mixed bag of functionality. On the one hand you have the pan tool, representing probably the most commonly used feature of any map application you will build. On the other hand is the CustomSWFTool, which represents what is likely the least commonly used yet most creative way to engage your users with your map application.
Overlay Classes in Review ❑
PanTool adds the all-important feature of letting the user drag the map and pan it. Because the tool activates a feature within the map instance itself, some events are associated with it that work with the map events discussed earlier in the chapter. The EVENT_DRAG_STOP and EVENT_ DRAG_START methods track the map dragging and are not to be confused with EVENT_PAN_ START and EVENT_PAN_STOP. To effectively listen to these events, you must listen to the tool instance directly.
❑
CustomSWFTool provides you with a way to extend the interactivity of the map into more engaging tools. Like the pan tool, this class relies on mouse interaction to engage the user. As with other custom SWF classes discussed in this chapter (CustomSWFMarker and CustomSWFOverlay), to take advantage of this feature, you will need to build your own SWF and add it to the map using the methods local to this class.
Working with Markers You can’t really create a mashup without adding markers. Markers are the indicators of important locations on your map. They are added with precision by address or latitude/longitude. In addition to methods, there are ways to remove markers programmatically based on user interaction. Marker classes enable you to define the type of marker you add, be they standard markers or markers you can design and develop from scratch. You can add markers one by one as well as by loading certain overlays. If you have a database, XML file, web-service response or other data source with many addresses or latlon coordinates, you will likely use a looping method like for/each to add markers.
Marker Methods This small set of methods represents the most commonly used functions in mashups: adding markers. Each method lets you ultimately control the location and appearance of every marker you add on the map.
addMarkerByAddress() This method lets you add markers to a location using an address. mapInstance.addMarkerByAddress(markerClass:Class, address:String, data:Object);
The markerClass parameter defines what type of marker you are adding. To successfully add a marker, you must import the class of the type of marker you reference in this parameter. The types of markers, reviewed in the following sections, have unique functionality and presentation attributes.
291
Chapter 21 An address variable must be passed in order for the marker to be added with this method. The address will need to be geo-coded, so this method does not process as quickly as its latlon counterpart. If you intend the marker to appear in the center of the map, you may want to call setCenterByAddress() with the same address. Finally, the properties of the markerClass you choose must be defined in the last parameter. As you learn in the following sections, each marker class carries with it different properties that are defined when this data object is cast.
addMarkerByLatLon() This method lets you add markers to a location using a latitude/longitude coordinate. mapInstance. addMarkerByLatLon (markerClass:Class, latlon:LatLon, data:Object);
As with the addMarkerByAddress(), the markerClass parameter is the type of marker you are adding. The types can vary within the same mashup but require their respective classes to be imported. The second parameter defines the location where the marker will be added. The LatLon class must be imported or referenced in order to properly cast the latitude/longitude coordinates into a LatLon object. Once again, the properties of the markerClass you choose must be defined in the last parameter. These properties will be discussed with each marker class below.
removeMarker(marker) To remove a specific marker, you can call removeMarker() against the marker instance you have added. mapInstance.removeMarker(marker:Object);
removeAllMarkers() removeAllMarkers() will clear out all markers that have been loaded to the map instance. Since this
method does not affect one single marker, but rather all markers, it does not need a parameter. mapInstance. removeAllMarkers();
Marker Classes Marker classes are packages of elements and other classes that enable you to add a variety of marker types to your map. Think of each marker class as a different marker type. A variety of markers are available in the AS-Flash API, ranging from the simple black waypoint marker to the customizable custom POI marker. You can apply your creativity and Flash design skills to developing your own custom SWF marker. The various marker classes have their own properties, each set when the marker object is created. When adding the marker to the map, you define which type of marker you are adding by passing the class and the properties you have set in the marker object.
292
Advanced Features: Flex 2 Using the AS-Flash API Overlay Classes in Review ❑
WaypointMarker: A waypoint is a reference on the map, often used in navigation to plot points along a route. This class lets you plot waypoints as markers. It is a very simple class, with almost no customization other than defining an index. If you are familiar with the consumer offering of Yahoo! Maps, you will recognize the waypoint marker as the same indicator used to plot points along driving directions routes.
❑
CustomImageMarker: This class lets you add an image or SWF anywhere on the map as a marker. This is a slightly more customized approach than the CustomPOIMarker discussed earlier in that an image or SWF that you create becomes the marker. Since the marker you add is completely of your own design, the only property of this class is the url of the image (JPEG) or SWF you create.
❑
CustomSWFMarker: This is one of the key features of the AS-Flash API, as it lets you develop and design your own interactive marker in the form of a SWF. Once the marker is added to the map instance, this class lets you call a method, callCustomMethod, against the marker itself. This means you have control over the marker after you have added it.
CustomPOIMarker POI stands for point of interest. This class lets you add a marker with the custom properties of index, title, description, marker color and stroke color. The two color properties reflect the body of the marker and its border respectively. These properties let you adapt the marker into your own visualization without having to create a completely new one. Although that feature is available with the AS-Flash API, as you will see later in the chapter, this marker class is an efficient means of achieving customization.
Try It Out
Add a CustomPOIMarker to the Map
In this example, you will need to modify each of the three application parts you created in the last chapter. Start with the Flex client by modifying the MXML in Flex Builder 2.
1. 2. 3.
Open the Flash Document as FlashAPI.fla.
4. 5.
Go to Window ➪ Development Panels ➪ Actions and select it (F9).
Save it as asFlashAPI_marker.fla. Select the first frame in the timeline. If the timeline is not visible, go to Window ➪ Timeline (Crtl + Alt + T).
Replace the contents of the actions panel with the following code:
//Create local connection object var connectedMap:LocalConnection = new LocalConnection(); //Import PanTool class import com.yahoo.maps.tools.PanTool; //Import CustomPOIMarker class import com.yahoo.maps.markers.CustomPOIMarker; //Add Initialize Event Listener to map instance
293
Chapter 21 myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap); //Function that executes when initialize event is fired function onInitMap(eventData) { //Send event via local connection connectedMap.send(“_flexClient”,”mapInitialized”); //Add the PanTool to the map instance myMap.addTool(new PanTool(), true); } //Listen for addMarker from local connection connectedMap.addMarkerByAddress = function (connectionData:Object):Void { //Create address variable to set address var address:String = connectionData.address; //Center map on an address and zoom with no panning myMap.setCenterByAddressAndZoom(address, 6, 0); //Create marker objects with CustomPOIMarker properties var marker:Object = { index:connectionData.index, title:connectionData.title, description:connectionData.description, markerColor:connectionData.markerColor, strokeColor:connectionData.strokeColor }; //Add the instance of the CustomPOIMarker to map with an address myMap.addMarkerByAddress(CustomPOIMarker, address, marker); } //Connect to local connection as _flashClient connectedMap.connect(“_flashClient”);
6.
Save the file (Ctrl + S) and compile the movie.
Even though this is not your final product, it is necessary to compile the .fla in order to create the SWF as well as ensure the map API component is resolving properly. In this part of the example, you have added the addMarkerByAddress ability to the Flash client. This enables this part of the application to listen for this call, which will be passed through the local connection. Within this method, you have added code to field the many properties supported by the CustomPOIMarker. You will now add the ability for the local connection to communicate this call by modifying the Map Connector class. This part will receive the call from the Flex client and pass the call and its data in an object to the Flash client.
294
Advanced Features: Flex 2 Using the AS-Flash API 1. 2. 3.
In the IDE of your choice, open MapConnector.as. Save it as MapConnector_marker.as. Enter the following code to populate the file:
package { //Import the local Connection class import flash.net.LocalConnection; //Declare the class MapConnector extending the LocalConnection class public class MapConnector_marker extends LocalConnection { //Declare the isInitialized variable private var isInitialized:Boolean; //Declare the mapConnector constructor public function MapConnector_marker(server:String = “_flexClient”) { //Try to connect to Flex Client and see if error occurs try { connect(server); } catch (error:ArgumentError) { // server already created/connected } //Instantiate the extended Local Connection class super(); } //Function called when map is initialized by Flash client public function mapInitialized():void { isInitialized = true; } //Function called when Flex client calls for map view type change public function addMarkerByAddress(address:String, index:String, title:String, description:String, markerColor:Number, strokeColor:Number):void { //Conditional to make sure map is initialized for attempting map control if(isInitialized) send(“_flashClient”,”addMarkerByAddress”, { address:address, index:index, title:title,
295
Chapter 21 description:description, markerColor:markerColor, strokeColor:strokeColor }); } } }
4.
Save the file. Make sure it stays in the same directory as the SWF and the MXML you are working with.
With this part of the example, you have now coded the MapConnector class (now MapConnector_ marker) to accept the addMarkerByAddress and pass it and its data along to the Flash client. Note that best practice would not be to modify the MapConnector class name. As you work through the book, you may find it easier to keep all of these files relative to each other for easier reference. In order for them to co-exist, they need unique names. Finally, it is time to re-code the Flex client part of the application. You will modify the interface as well, giving the user a control to enter an address. You will also add a button that let’s the user submit both the entered address as well as the new zoom level.
1. 2.
With Flex Builder 2, open Flex2Maps.mxml.
3.
Replace the existing MXML with the following:
Save it as Flex2Maps_marker.mxml. Remember to save it in the same directory as asFlashAPI_ marker.swf and MapConnector_marker.as.
296
Advanced Features: Flex 2 Using the AS-Flash API
4.
Save the file and run the application (in the toolbar click the green circle with white arrow). The Yahoo! Maps AS-Flash API will load within the Flex 2 application (as shown in Figure 21-1).
Along the top of the centered map are text fields allowing you to define the attributes of the Custom POIMarker. In addition, you can define the colors of the marker. Clicking the Add Marker button will reposition the map and display the added marker.
How It Works In the Flex client, the many UI elements you added support user input of the CustomPOIMarker. While you have worked with the Label and TextField controls, the ColorPicker is a new implementation. This compact control lets your users pick a color for the strokeColor and markerColor properties of the marker. Once the button is pressed in Flex, it calls the buttonPress function. This takes the values of the textFields and colorPickers and passes them forth to the mapConnector_marker class method of the same method. Once in the local connection, it will be picked by the listener inside the SWF. All properties passed along will be collected and called as the marker is added to the map. As a final step, the map will be repositioned using setCenterByAddressAndZoom using the address to which the marker is to be added. You should use this example to explore working with the other marker classes. To do this, you will need to change the properties passed from the Flex side and handled in the local connection. You will also need to import other marker classes in the SWF and handle their properties accordingly as you add them to the map instance. Explore adding a ComboBox control to the Flex client that would let the user choose what type of marker they want to add.
297
Chapter 21
Figure 21-1
Working with Overlays An Overlay adds a new layer over the existing map layer. It moves along with the map as it is panned. Overlays are most used as containers for sets of markers representing related data such as local search results and traffic. As you will see in this section, the overlays have an incredible ability of acting as their own mashups. Adding some of the overlay classes will actually request data, parse the response and add markers all by itself. It is good to test out each overlay, as it may save you some time as well as add even more functionality to what you will ultimately build.
Overlay Methods Just like widgets, tools and markers, overlays can be added and removed with a simple pair of methods. It is good practice, after importing the overlay class, to create an instance variable for that new overlay. //Import LocalSearchOverlay import com.yahoo.maps.overlays.LocalSearchOverlay; //Create localSearch instance var localSearch = new LocalSearchOverlay();
298
Advanced Features: Flex 2 Using the AS-Flash API Here, you can see that after importing the LocalSearchOverlay class, which is discussed in detail in the following sections, the localSearch variable is set to the new overlay instance.
addOverlay(overlay) Once the map instance is initialized, the overlay instance can be added using addOverlay(). addOverlay() accepts one parameter, the overlay instance you are adding to the map. mapInstance.addOverlay(overlay);
removeOverlay(overlay) removeOverlay() will remove the specified overlay instance from the map. mapInstance. removeOverlay(overlay);
Overlay Classes Overlay classes act as built-in mashups. With the LocalSearchOverlay and TrafficOverlay classes, your application will be directly connected to the popular local search and traffic data. These two classes in particular allow you to replicate functionality featured on the Yahoo! Maps consumer application. Also available is the GeoRSSOverlay class. This class, when imported and instantiated, is capable of picking out locations from geoRSS feeds and displaying markers respective to those locations. GeoRSS is a special standard that represents standard RSS data with location data objects embedded within each item.
Overlay Classes in Review ❑
The LocalSearchOverlay class adds a feature that taps the power of Yahoo!’s Local search database. The functionality lets you call a keyword search and display results in the form of markers. This feature closely resembles that of the “Find on Map” feature on the Yahoo! Maps consumer application. The markers are enriched with some very useful data for any user and consumer, including business name, address and, where available, business rating.
❑
The GeoRSSOverlay class and type of overlay lets you populate the map with markers defined from a geo-coded RSS feed. This special version of RSS XML contains geo-coded objects. A geoRSS feed adds extra data like latitude/longitude or address in addition to location information.
❑
The CustomSWFOverlay class combines the flexibility of the geoRSSOverlay with the potential of the customSWFMarker. Essentially, instead of your geoRSS feed loading images as markers, it can load SWFs. In addition, you can call methods against those marker SWFs through the callCustomMethod method, which is reviewed in detail with the CustomSWFMarker class example in this chapter.
TrafficOverlay TrafficOverlay is another overlay class that replicates the power of a very popular and useful feature
of the Yahoo! consumer application. Real-time traffic incident information can add a desirable functionality to your application, giving it an extra edge over other application capabilities. A benefit to this overlay class is that it has no methods since all the functionality is built in.
299
Chapter 21 The overlay class requests traffic information for the area the map is currently centered on. It takes the data returned and displays each item as a CustomPOIMarker, complete with incident information. The markers created reflect traffic incidents ranging from accidents to road construction to medical emergencies. Each incident is represented with a different color and universal symbol.
Try It Out
Add the TrafficOverlay to the Map
You will now build a map application that lets your users display as well as turn off the traffic overlay. In this example, adapted from one presented in Chapter 16, “AS-Flash API Advanced Features,” you will need to modify each of the three application parts you created in the previous chapter. Start with the Flex client first by modifying the MXML in Flex Builder 2.
1. 2. 3.
Open the Flash document asFlashAPI.fla.
4. 5.
Go to Window ➪ Development Panels ➪ Actions and select it (F9).
Save it as asFlashAPI_traffic.fla. Select the first frame in the timeline. If the timeline is not visible, go to Window ➪ Timeline (Crtl + Alt + T).
Replace the contents of the actions panel with the following code:
//Create local connection object var connectedMap:LocalConnection = new LocalConnection(); //Import PanTool class import com.yahoo.maps.tools.PanTool; //Import TrafficOverlay class import com.yahoo.maps.overlays.TrafficOverlay; //Add Initialize Event Listener to map instance myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap); var overlayInstance:Object = new TrafficOverlay(); //Function that executes when initialize event is fired function onInitMap(eventData) { //Add the PanTool to the map instance myMap.addTool(new PanTool(), true); //Center map on San Jose, CA myMap.setCenterByAddressAndZoom(“San Jose, CA”, 6, 0); //Send event via local connection connectedMap.send(“_flexClient”,”mapInitialized”); } //Listen for addTrafficOverlay from local connection connectedMap.addTrafficOverlay = function ():Void { //Add Traffic Overlay to map
300
Advanced Features: Flex 2 Using the AS-Flash API myMap.addOverlay(overlayInstance); } //Listen for removeTrafficOverlay from local connection connectedMap.removeTrafficOverlay = function ():Void { //Remove Traffic Overlay to map myMap.removeOverlay(overlayInstance); } //Connect to local connection as _flashClient connectedMap.connect(“_flashClient”);
6.
Save the file (Ctrl + S) and compile the Movie.
This ActionScript code looks similar to that of the original example. Here, the local connection supporting script is built in. There are new functions to support both the adding and removing of the traffic overlay functionality. You will now add the ability for the local connection to communicate this call by modifying the Map Connector Class. This part will receive the call from the Flex client and pass the call and its data in an object to the Flash client.
1. 2. 3.
In the IDE of your choice, open MapConnector.as. Save it as MapConnector_traffic.as. Enter the following code to populate the file:
package { //Import the local Connection class import flash.net.LocalConnection; //Declare the class MapConnector extending the LocalConnection class public class MapConnector_traffic extends LocalConnection { //Declare the isInitialized variable private var isInitialized:Boolean; //Declare the mapConnector constructor public function MapConnector_traffic(server:String = “_flexClient”) { //Try to connect to Flex Client and see if error occurs try { connect(server); } catch (error:ArgumentError) { // server already created/connected }
301
Chapter 21 //Instantiate the extended Local Connection class super(); } //Function called when map is initialized by Flash client public function mapInitialized():void { isInitialized = true; } //Function called when Flex client calls for traffic to be added public function addTrafficOverlay():void { //Conditional to make sure map is initialized for attempting map control if(isInitialized) send(“_flashClient”,”addTrafficOverlay”); } //Function called when Flex client calls for traffic to be removed public function removeTrafficOverlay():void { //Conditional to make sure map is initialized for attempting map control if(isInitialized) send(“_flashClient”,”removeTrafficOverlay”); } } }
4.
Save the file. Make sure it stays in the same directory as the SWF and the MXML you are working with.
With this part of the example, you have now coded the MapConnector class (now MapConnector_ traffic) to accept both the addTrafficOverlay and removeTrafficOverlay methods along with the Flash client. Finally, it is time to re-code the Flex client part of the application. You will modify the interface as well, giving the user a control to enter an address. You will also add a button that let’s the user submit both the entered address as well as the new zoom level.
1. 2.
With Flex Builder 2, open Flex2Maps.mxml.
3.
Replace the existing MXML with the following:
Save it as Flex2Maps_traffic.mxml. Remember to save it in the same directory as asFlashAPI_ traffic.swf and MapConnector_ traffic.as.
302
Advanced Features: Flex 2 Using the AS-Flash API
4.
Save the file and run the application (in the toolbar, click the green circle with white arrow). The Yahoo! Maps AS-Flash API will load within the Flex 2 application, as shown in Figure 21-2.
You will see the map centered on San Jose, California. The two buttons at the top of the interface allow you to display traffic as well as remove it from the map.
How It Works The map will load displaying the San Jose, California, area. Should any traffic incidents be occurring, you should see them represented as markers. Depending on the varying incidents in the area, you will see different colors with symbols representing the different kinds of incidents. Rolling over the marker will reveal more details, and clicking on the marker will give you a full description of the event and the time it occurred. Like the LocalSearchOverlay, this class also sends data to a web service. The API in this case is Yahoo!’s Traffic API. The data returned contains geo objects which allow the map API, using this overlay class, to add markers at those locations. TrafficOverlay refreshes as you pan the map, which is why PanTool functionality was added. This
application is an example of one-way communication using the local connection — there are no commands passed all the way back from the SWF to the Flex 2 client. To add a little more sophistication to this application, you could add a call that tells the Flex 2 client when the traffic overlay has been added or removed. Based on the overlay’s state, you could enable or disable the “Add Traffic” and “Remove Traffic” buttons accordingly.
303
Chapter 21
Figure 21-2
Summar y This chapter reviewed many of the advanced functionalities of the AS-Flash API, first introduced in Chapter 16, “AS-Flash API Advanced Features.” You were re-acquainted with the more complex line of classes, methods and events that make this API so capable. Having completed the exercises in the last few chapters, in addition to the CustomPOIMarker and TrafficOverlay exercises in this chapter, you have a solid foundation for making Flex 2 map applications using the AS-Flash API. Coming up on the next chapter, you will use what you have learned as the foundation to create your most complete Yahoo! Maps mashup yet.
304
22 The Flex 2 Mashup The goal of this chapter is for you to build a Flex 2 mashup using the ActionScript-Flash (AS-Flash) API. To achieve this, you will also accomplish the following: ❑
Establish an idea for your mashup and plan out the key details and development approach
❑
Learn how to create your own data to mash up in MXML
❑
Convert and play flash video dynamically in your mashup
❑
Establish communication between Flex and Flash to control and add markers dynamically to the map API instance
Time to Mash Up Now that you have learned all the methods and classes of the AS-Flash API, as they are used with Flex 2 and the local connection method, it’s time to build a mashup. As with the other APIs featured in this book, this chapter will guide you through building a mashup with a data source and the map API. The means you employ to use the AS-Flash API is something of a workaround due to the absence of a Flex 2–compatible maps component. Because of this, much of what you have learned through the previous chapters is very fundamental. Coding the Flex client, MapConnector class and Flash client pieces can be time-consuming and may cause you to sacrifice the creative spirit you used when working with the AS-Flash API. Having mastered many of the techniques necessary to work with Flex 2 and Yahoo! Maps, you can now explore the space freely with this mashup project.
The Big Idea Throughout the book, you have built some great mashups, combining the power of Yahoo! Maps with other data services. The mashup for this chapter will not point to outside data like a web service, RSS feed or API. This time, the mashup will be between the Yahoo! Maps API and data you will provide.
Chapter 22 The idea of using your own data in a mashup should come as no surprise. Much of the web today is built on user content. User-generated content drives numerous blogs and accounts for the amazing growth of websites in the last few years. You’ll find user content on sites that feature product reviews, comments and feedback. Maps provide a great platform for displaying your own content. Much of what you do, on the weekends for example, likely has some geographic relevance. Each event can be marked on a map, providing a unique way for you to document your weekend, thus generating a map mashup with your own content. Perhaps you took a trip over the weekend, went camping or drove into the city for a day to shop or attend a ball game. Or maybe you hit the links for a round of golf. Golf, as it turns out, is quite a mapable activity. Occurring in a defined and consistent space, each play of the game takes place on a stretch of land and is marked by each shot. On August 13, 2006, I played 18 holes at Sunol Valley Golf Club in Sunol, California. It happened to be a special occasion, my brother Nathaniel’s 26th birthday, and so I took my video camera to grab some rare clips of us swinging away. While there were no birthday hole-in-ones, we did manage to collect some decent and entertaining footage of various shots. I happened to note where some of the shots, both golf and video, were taken. The mashup you will build will have you define structured data within the application. These data will organize a series of golf shots and contain the following information: ❑
The player hitting the shot
❑
The hole the shot was taken on
❑
The latitude and longitude of the hole on the course
❑
The path to the .flv (Flash video) file of the captured shot
Your user will be able to select a golf shot, watch the video play and see where the shot was taken on a zoomed-in map featuring satellite imagery of the golf course. This highly adaptable mashup can be transformed into many things, like a recap of your vacation or video tour of your favorite city. One thing is for sure, it may be as much fun to code as it will be for your users to experience.
Planning and Approach As with any application, planning and approach are important. It helps to know the APIs and web services you are working with very well. Having completed the previous chapters on the AS-Flash API, you should have all you need to work with the map. Before coding, it is always good to lay out your objectives and then determine how best to achieve those tasks. Begin with thinking out what your application should achieve. Through the rest of the chapter, you will see how these steps are used to build the mashup.
1. 2. 3. 4.
306
Display the map initially. Position the map and set its view type accordingly. Author the data you will mash up with the map API. Give the user the ability to navigate through the data.
The Flex 2 Mashup 5. 6.
Display the data as markers on the map based on user selection. Play the video clip based on user selection.
This is a simple flow and this pattern of user interaction should be easily replicated with other APIs and web services.
The Flex Client For this project, it is best to reverse the order of construction of your application. You will recall that in previous chapters the order of completion for the Flex 2/AS-Flash API project was to build the Flash client SWF first. That was followed by the local connection MapConnector class, and then you built the Flex client to round it out. Since you will be defining your own data in this mashup, it is best to start developing the Flex client first as that is where the data you build will reside. Another reason to start with the Flex client is to code the user controls first. Since layout and user interaction are such a factor in this chapter’s mashup, you will need to establish these pieces before setting up the supporting code for the actual map. As you’ve learned in the last few chapters by using the Flex 2/AS-Flash API approach, while the map is still contained in the Flash client, user-interaction controls are written in the MXML as part of the Flex client.
Architect the MXML As you have done with previous mashups in this book, it is now time to architect the mashup. Starting with the MXML, and repeating for each of the three pieces of the application, this step will help you think out your project before coding it. Here are the ingredients for developing the Flex client MXML for this mashup:
1. 2.
Import all classes that the map will need.
3. 4. 5.
Add the interaction and display elements.
Structure the data that will be mashed up. Since you will be providing your own data, it can be hard-coded within the application code.
Code the event handler. Call the method in the local connection, passing along the necessary values.
The Data Defining your own data when building a mashup has some nice advantages. The obvious is that you do not have to gain knowledge or adapt to the data format from an external data source. This means you can skip past some of the steps necessary in building previous mashups, like exploring the data source. Another is that the data will always be there, as they load with the application. This simply means that you do not need to connect to an external data source, trusting that the connection and access information are there, to populate your mashup.
307
Chapter 22 There are downsides too, mainly the fact that you will be limited to only the data you define. Defining your own data also takes the fun out of getting familiar with other products and their APIs. Since you are still working with the AS-Flash API here, many of the mashup concepts you used in Chapter 17, “The AS-Flash Mashup,” still apply here. For this mashup, however, you will learn how to define data in MXML for Flex 2. You can add data to Flex 2 in several ways. You can write XML in an external file, include it with your application and load it as if it were a web service. Flex 2 does support an ActionScript XML object similar to that of ActionScript 2 for Flash. There is also a new, more efficient XML model called E4X that supports coding XML native format inline with the MXML. For this mashup, you will use the Model control. This control lets you declare a data model inline with the MXML. It is a common control for powering other controls and components, as each node is easily parsed, allowing referencing for individual properties. This model will unlimitedly become the data provider, the source of data, for a List control you will add later. Each node within will represent a new list item, marker location and video clip.
The label property will be displayed in the List component you will add. The lat and lon properties will become the LatLon object when the marker is added to the map. This will represent where the golf shot was hit from. Last, the URL property represents the path to the video clip of the golf shot.
The Layout Now that you have the data ready to code, it is time to consider the layout elements of the mashup. First, you need to itemize each interface element you will need to provide the user so he or she can interact with your mashup. Taking advantage of the pre-built Flex controls that come with Flex 2 and are supported by Flex Builder 2, you will need to identify which components to use.
308
❑
A Label control to display the title of the mashup
❑
A List control to display the list of video clips
❑
A VideoLoader control to play the video
❑
A set of button controls to allow playing, pausing and stopping of the video
The Flex 2 Mashup ❑
The Hbox control to properly lay out elements from left to right
❑
The Vbox control to properly lay out elements from top to bottom
❑
A SWFLoader control to load the Flash client’s SWF
Each of these controls has its own unique set of properties. They can be explored in the Flex Component and Style Explorers, introduced in Chapter 18, “Yahoo! Maps and Flex 2” and accessible through the Flex Builder 2 start page. You will code these elements into the MXML next.
Coding the Controls It is now time to code the MXML that will support the controls and layout: Golf Videos” />
The Hbox handles the overall horizontal layout, creating a side-by-side presentation. On the left side, wrapped in a Vbox control, to manage layout from top to bottom, is, first, the Label control. This displays the title of your mashup. Next to the Label control is the List control. This control will let the user select a golf shot from the defined data, which is hooked into the control by means of the dataProvider property. This allows the control to reference the data within the Model control you coded above. When the selection happens, a change event handler will call the listSelect function, which you will code in the next step. The VideoDisplay control provides a very simple way to display the video. To allow the user subsequent control of the video, three buttons neatly laid out inside an Hbox do the trick. Each button calls a method against the VideoDisplay instance. Finally, the SWFLoader will load the Flash client map SWF, the compiled AS-Flash API. You will code this, equipping it to fully accept the map commands through the local connection as part of this mashup.
Handling User Interaction You need to add ActionScript within the MXML class on the Flex client to support the elements you will add. As in past Flex 2 examples, the ActionScript is much like what you would code in the Flash IDE:
309
Chapter 22
The listSelect function is called from the List event handler when the list is changed. The object that is sent as part of the event carries with it the selected item data of the row selected in the list. This index allows the ActionScript to extract all the properties from the Model based on the selected item. Lastly, the playVideo function is coded to accept the selectItem object. Within this function, the url property of the selectedItem will be loaded in the VideoLoader control. addMarkerByLatLon is also called against the local connection instance. The lat, lon and label properties will be carried through the local connection and ultimately be received by the Flash client SWF. There, they will resolve to add a marker to the map representing the location of the golf shot shown in the selected video clip.
Completing the MXML It is time to complete the Flex client. Here you will see the fully coded MXML, putting together the different sections you have become familiar with.
1. 2. 3.
With Flex Builder 2, open Flex2Maps.mxml. Save it as Flex2Maps_golf.mxml. Replace the existing MXML with the following:
310
The Flex 2 Mashup Golf Video” />
4.
Save the file (Crtl + S). You should not try to run the file since the local connection and Flash client pieces have not been coded yet.
In addition to the sections you have already worked on, the XML and Application tags have been added. This completes the Flex client piece of the mashup. You will not code the local connection piece, which enables communication between the Flex and Flash clients.
The Local Connection This section will guide you through coding the bridge script to enable communication between the Flex 2 and Flash clients. As I mentioned in Chapter 18, “Yahoo! Maps and Flex 2,” the bridge script is necessary to allow the Flash player to run both Flex 2 and ActionScript 2 applications. Because Flex 2 runs ActionScript 3, it requires a different virtual machine that is available in Flash Player 9. The ASFlash API requires a different ActionScript virtual machine (AVM) to run and so it cannot be loaded directly into Flex 2 or other ActionScript 3–based applications. You enable the local connection to communicate this call by modifying the MapConnector class. This part will receive the call from the Flex client and pass the call and its data in an object to the Flash client. This local connection file, like the ones you have coded in other chapters, fields calls from the Flex client and passes them along to a listening Flash client. There, the calls are picked up and ultimately called, with any proper data passed along, against the instance of the map.
Coding the MapConnector Class You will now code the aforementioned “bridge” between the compiled AS-Flash API instance and your Flex 2 application.
1. 2. 3.
In the IDE of your choice, open MapConnector.as. Save it as MapConnector_golf.as. Enter the following code to populate the file:
package { //Import the local Connection class import flash.net.LocalConnection; //Declare the class MapConnector extending the LocalConnection class public class MapConnector_golf extends LocalConnection {
312
The Flex 2 Mashup //Declare the isInitialized variable private var isInitialized:Boolean; //Declare the mapConnector constructor public function MapConnector_golf(server:String = “_flexClient”) { //Try to connect to Flex Client and see if error occurs try { connect(server); } catch (error:ArgumentError) { // server already created/connected } //Instantiate the extended Local Connection class super(); } //Function called when map is initialized by Flash client public function mapInitialized():void { isInitialized = true; } //Function called when Flex client calls for adding marker public function addMarkerByLatLon(lat:Number, lon:Number, index:String):void { //Conditional to make sure map is initialized for attempting map control if(isInitialized) send(“_flashClient”,”addMarkerByLatLon”, { lat:lat, lon:lon, index:index }); } } }
4.
Save the file. Make sure it stays in the same directory as the SWF and the MXML you are working with.
The differences between this class and others you created previously are minimal. In addition to the class name changing and that change being reflected in the constructor, you are adding a new function. The addMarkerByLatLon will be called from the Flex client piece and pass three parameters. The lat, lon and index parameters will be channeled into the addMarkerByLatLon event as an object. You will work with the AS-Flash API next, as you code the Flash client piece of the application and complete your mashup.
313
Chapter 22
Making the Video There’s a little bonus for you in this mashup project: you get to work with Flash Video. Flash’s Video format (FLV) represents one of the most highly compressed yet best quality video formats available. Since its introduction in 2002, Flash video has benefited from the high impression usage of the Flash Player. Flash video can live within your Flash application in three different ways. Embedded, the video material lives within the Flash application, enabling you to manipulate actual video content via the timeline. The major downside to this method is that the video cannot be dynamic. Also, if the video is too long, it may cause performance issues for the user. Another way to include Flash video is via progressive download. This is the most common technique. It requires you to keep the video outside the Flash application, meaning that it is loaded dynamically. The main benefit is that should the video change you will not need to recompile your application. Another benefit is that the video can be loaded by other Flash applications, as it will likely be hosted on your server. The last option for including video in your application is to stream it. While this is the best way to feature video, it is often not a popular option for independent developers. This is because to stream video, you need to leverage the Flash Media Server (called FMS, formerly Flash Communication Server). Streaming video and using FMS introduces all sorts of new features, including the ability to control and monitor performance as well as the ability to use cameras for real-time chatting. For this mashup, you will be applying the progressive download method. While the FLV you will be using is already created and available (you added the links to the FLV files when you coded the MXML), you will now learn the steps to create your own FLV files.
Converting Media to Flash Video You start by creating or obtaining your own video content. Using a hard drive or media-based camera like a Sanyo HD1 or Canon Everio is your best bet. This way you can pluck video right off the camera or its removable media. You also can use a digital video camera, but that will require you to pull the video off using firewire technology. For a quick and cheap way of obtaining your own video, you can use a standard webcam and just capture its output right to your computer. Once you have obtained the video, it is time to convert it to FLV. This process requires you to load the video into Flash, compress it and export it as an FLV.
Try It Out
Make an FLV File
You will need to acquire a video file (.mov, .avi, .mpeg4 and many others) to complete these steps. You should also have a server account where you can host and serve the FLVs from. (The following process may vary slightly with newer versions of the Flash IDE.)
1. 2. 3. 4. 314
With the Flash IDE open, create a new Flash document. Save the Flash document as Ymaps_video.fla. Go to File ➪ Import ➪ Import to Library. Browse to where you have stored the video file on your system and press Open.
The Flex 2 Mashup 5.
The Sorenson Spark Video Import Wizard will launch. You have the option to import the entire video or edit the video first. For this example, choose to import the entire video (as shown in Figure 22-1). Click Next.
Figure 22-1
6. 7.
Choose the compression profile that is right for your users. The 256 kbps setting is very neutral.
8.
When compression is finished, you should see the video file show up inside the library panel (Ctrl + L). Clicking on that file should show a screenshot of it, depending on the file type.
9.
Right-click the video file and select Properties. You will be given details on the video, including when it was taken, its size and its duration. You can also change its name as a library item.
10.
Clicking Finish will start the importing process. You will be given a progress bar, which shows the time it will take to complete the compression. A combination of high-quality video with a slow computer will result in longer compression times.
Finally, click Export. You are prompted to save the file as an FLV. Enter a file name like testVideo, and click Save.
Your FLV is now available to be loaded dynamically into your Flash application. You can test out the file by browsing to it in your file system and double-clicking it. Uploading the FLV to your server will make it available online, where it can be loaded in many applications. If you are looking to include this video in your mashup, simply add its URL to the mx:Model control you coded earlier in the chapter when you were building the MXML.
315
Chapter 22
The Flash Client To build the Flash client, as you have done in previous chapters, you will need to use the Flash IDE to compile the AS-Flash API. The Flash client side of the application contains the API component attached to its stage. When compiled, all the classes and functionalities of the map API will become available to the application. To allow the Flash client to talk to the Flex client, you will add some very simple lines of code to enable the local connection. This will allow it to receive calls from the Flex client interface and control the map accordingly.
Architect the ActionScript Just as with the MXML, it is a good practice to architect the Flash client piece of the application. This step is an even better idea on the Flash side since it often involves thinking out the user elements that may exist by way of the visual authoring approach with the Flash IDE. While this mashup does not contain any Flash-based interaction elements, other than the map itself, this is still a very helpful step. The tasks to complete the Flash client are
1. 2. 3. 4. 5.
Import all the classes that the map will need. Create a local connection instance and register the Flash client. Add event listeners to field events broadcast from the map instance. Field the map instance events and set initial map properties. Build functions to handle local connection calls and return data as necessary.
Importing the Classes The first step to building the ActionScript for the Flash client is importing the classes: //Import PanTool class import com.yahoo.maps.tools.PanTool; //Import CustomPOIMarker class import com.yahoo.maps.markers.CustomPOIMarker; //Import LatLon class import com.yahoo.maps.LatLon
Here you have imported the PanTool class that will allow your users to drag the map around. The Custom POIMarker class will enable you to add a marker of this type to the map. You will need the LatLon class to cast the latitude and longitude properties of the golf shot and center the map on that location.
Create the Local Connection The local connection is an extremely important part of the Flex 2/AS-Flash API approach . //Create local connection object var connectedMap:LocalConnection = new LocalConnection(); //Connect to local connection as _flashClient connectedMap.connect(“_flashClient”);
316
The Flex 2 Mashup The LocalConnection class is built into Flash and does not need to be imported to work. The connectedMap object you are creating here will act as the local connection instance. You call the connect method against that instance to register the Flash client piece of the application as _flashClient.
Add the Event Listeners As you learned in previous chapters, events are fired at key points of the application. These events are often dispatched based on map occurrences or user interaction. //Add Initialize Event Listener to map instance myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap); //Add Zoom Event Listener to map instance myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_ZOOM_STOP, onZoom);
The EVENT_INITIALIZE event fires when the map initializes and calls onInitMap to carry on its activity. You are adding the EVENT_ZOOM_STOP listener so the application knows when the map finishes zooming. As you will see, this is a necessary timing step to allow the map to center itself and zoom before changing the map view type.
Field Map Instance Events The next step is to code the pass-through functions for the events. The functions carry on the event and data that are picked up in your listeners. //Function that executes when initialize event is fired function onInitMap(eventData) { //Add the PanTool to the map instance myMap.addTool(new PanTool(), true); //Position map to show Sunol Valley Golf club myMap.setCenterByAddressAndZoom(“7000 Mission Rd, Sunol, CA”, 2, 0) //Send init event via local connection connectedMap.send(“_flexClient”,”mapInitialized”); } //Function that executes when map is zoomed function onZoom() { myMap.setMapViewType(“satellite”); }
The onInitMap function will add the pan tool and center the map to its initial address. It will also send a call to the local connection instance that the map has initialized. This local connection depends on this occurrence to permit communication back to the Flash client. You may recall the conditional in the MapConnector class that establishes this. The onZoom function will call the setMapViewType against the map instance to change the tiles to satellite. This delay needs to occur since the map cannot handle changing its view type at the same time as centering and zooming.
317
Chapter 22
Field Local Connection Events The ActionScript needs to listen for events from the local connection to field calls sent through it from the Flex client. //Listen for addMarker from local connection connectedMap.addMarkerByLatLon = function (connectionData:Object):Void { //Clear out any existing marker(s) myMap.removeAllMarkers(); //Create latlon object based on lat and lon properties from local connection var latlon = new LatLon(connectionData.lat, connectionData.lon); //Create marker object with index property for CustomPOIMarker var marker:Object = { index:connectionData.index }; //Add the instance of the CustomPOIMarker to map with a latlon myMap.addMarkerByLatLon(CustomPOIMarker, latlon, marker); //Center map on an latlon matching the position of the marker myMap.setCenterByLatLon(latlon); }
This code sets up the Flash client to receive the addMarkerByLatLon call coming through the local connection. It is coded against the local connection instance of connectedMap. Once this fires, the first step is to clear out all markers. Pulling in the data from the connectionData object, you then cast a latlon object with the lat and lon properties passed through the local connection call’s object. The index property of this object is used to define the property of the same name to create the new marker. A marker will then be added against the instance of the map, using the CustomPOIMarker class, the latitude/longitude and the newly created marker object, featuring the index property. This index is actually the title of the golf shot selected by the user from the List control in the Flex client. Lastly, the map will center itself on the newly created marker using the same latitude and longitude at which the marker was added.
Completing the ActionScript You will now take each piece you have reviewed so far and put them all together. After you complete this code and compile it, the SWF becomes available to be pulled into the Flex client.
318
1. 2. 3.
With the Flash IDE, open the Flash document asFlashAPI.fla.
4.
Go to Window ➪ Development Panels ➪ Actions and select it (or press F9).
Save it as asFlashAPI_golf.fla. Select the first frame in the timeline. If the timeline is not visible, go to Window ➪ Timeline (Crtl + Alt + T).
The Flex 2 Mashup 5.
Enter the following code in the actions panel:
//Import PanTool class import com.yahoo.maps.tools.PanTool; //Import CustomPOIMarker class import com.yahoo.maps.markers.CustomPOIMarker; //Import LatLon class import com.yahoo.maps.LatLon //Create local connection object var connectedMap:LocalConnection = new LocalConnection(); //Connect to local connection as _flashClient connectedMap.connect(“_flashClient”); //Add Initialize Event Listener to map instance myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap); //Add Zoom Event Listener to map instance myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_ZOOM_STOP, onZoom); //Function that executes when initialize event is fired function onInitMap(eventData) { //Add the PanTool to the map instance myMap.addTool(new PanTool(), true); //Position map to show Sunol Valley Golf club myMap.setCenterByAddressAndZoom(“7000 Mission Rd, Sunol, CA”, 2, 0) //Send init event via local connection connectedMap.send(“_flexClient”,”mapInitialized”); } //Function that executes when map is zoomed function onZoom() { myMap.setMapViewType(“satellite”); } //Listen for addMarker from local connection connectedMap.addMarkerByLatLon = function (connectionData:Object):Void { //Clear out any existing marker(s) myMap.removeAllMarkers(); //Create latlon object based on lat and lon properties from local connection var latlon = new LatLon(connectionData.lat, connectionData.lon); //Create marker object with index property for CustomPOIMarker var marker:Object = { index:connectionData.index };
319
Chapter 22 //Add the instance of the CustomPOIMarker to map with a latlon myMap.addMarkerByLatLon(CustomPOIMarker, latlon, marker); //Center map on an latlon matching the position of the marker myMap.setCenterByLatLon(latlon); }
6. 7.
Save it (Ctrl + S). Go to Control ➪ Test Movie (Crtl + Enter) to compile the movie.
The compiled SWF should display, showing satellite tiles and centering on the Sunol Valley Golf Club in Sunol, California. Having loaded the PanTool, you should be able to click and drag the map. Other features you coded will come alive when the SWF is loaded by the Flex client. You will experience this functionality as you finalize the mashup next.
Finalize the Mashup Finally, it is time to fully compile the mashup. With each piece coded you will now reopen the Flex code and compile the entire application. Note that in order for the mashup to work, the SWF, the MapConnector class and the Flex client MXML must be in the same directory.
1. 2.
With Flex Builder 2, open Flex2Maps_golf.mxml. Run the application (in the toolbar, click the green circle with white arrow, or press Crtl + F11).
The Yahoo! Maps AS-Flash API will load within the Flex 2 application. The map will zoom in on the clubhouse at Sunol Valley Golf Club (Figure 22-2). A list of six golf shots will display in the upper-left corner within a List control. Clicking on a golf shot will result in the map recentering on where the golf shot was taken. A marker will be added at the point where the golf shot was taken and be populated with a title matching the golf shot. In the bottom-left corner, the video of the golf shot will play.
320
The Flex 2 Mashup
Figure 22-2
Enhancing the Mashup While the steps and the code provided and reviewed in this chapter give you a solid mashup, it is just a start. There are many ways to enhance both the code and presentation of your Flex 2/AS-Flash API–based mashup. Within the code itself, there are several things you can do to scale the application. Here are some suggestions: ❑
Experiment with different Component events, changing user interaction to make it more intuitive
❑
Add more options for the user to control the map. Add items like the NavigatorWidget, the SatelliteControlWidget, or a custom zoombar of your own
❑
Develop your own CustomSWFMarker to show each golf shot in a whole new way. With a custom marker, you can expand the marker well beyond its current capacity to feature more information on the video clip and its location.
❑
Try swapping out the hard-coded inline data for something dynamic.
321
Chapter 22 There are also several things you can do to jazz up your mashup. Try some of the following to take this basic and functional mashup you’ve created to the next level of presentation: ❑
Add various Flex controls and components to the MXML to allow additional user control.
❑
Try developing your own component to introduce a completely new experience to your user.
❑
Apply unique styles to the Flex controls you are using in your application. Use the style explorer found on the start page of Flex Builder 2.
Summar y This chapter helped you to develop your first Flex 2/AS-Flash maps mashup as well as work your own data inside the Model control. The mashup you created is just a start and should enable you to create even better applications with other data, Flex 2 controls and components. You have now completed the most advanced chapter. In assembling the mashup exercises throughout the book, especially the one featured in this chapter, you should feel confident in your ability to accomplish many things with the Yahoo! Maps APIs. With three APIs covered in the book and the additional Flex 2 application layer, the casual maps developer might want to pick one technology to work with further. Professional developers will find the advanced knowledge of all the map APIs and applications in this book beneficial, enabling them to develop mashups for nearly every solution. No matter what kind of developer you are, I hope that building mashups with Yahoo! Maps and Flickr, Yahoo! Travel, HotJobs and the video data in this chapter has intrigued you as to what else is possible with maps. There are many data sources to explore, and you, a developer having completed this book, have all the tools necessary to build creative, effective and innovative Yahoo! Maps mashups. For additional ideas on what mashups you can create with Flex 2 and the AS-Flash API as well as the others reviewed in the book, visit the Yahoo! Developer Networks application gallery at http://gallery .yahoo.com/maps. For the very best mashups using several technologies, visit www.mashupexperts.com.
322
A API Method Comparison Chart Developers looking to move between the Ajax and Flash APIs covered in this book will find the chart in this appendix very helpful. It is meant to act as a Rosetta stone for the APIs, indexing and comparing the various methods and classes available. Each common Ajax API method and class is paired with its equivalent among the Flash-based APIs.
Basic Set Methods and Classes As classified from chapter to chapter, the basic set methods and classes are those that offer primary functionality for controlling and manipulating the map’s location, zoom level and display type. Ajax Method
Flash Method
YMap(mapContainer, mapType, mapSize)
Map (container, appid, location, zoom, mapViewType)
The code for creating a map object is nearly identical for both API types. The Flash API lets you add initial location, zoom level and map view type. setZoomLevel(zlevel) setZoomRange(minZoomLevel,maxZoomLevel) addZoomScale() removeZoomScale()
setZoomLevel(zoomLevel)
This is one of those rare times when the methods are identical. In addition to setting the zoom, the Ajax API lets you set zoom range and manipulate zoom scale.
Appendix A drawZoomAndCenter(LocationType, ZoomLevel) panToLatLon(YGeoPoint)
setCenterByAddress(address, duration) setCenterByAddressAndZoom(address, zoomLevel, duration) setCenterByLatLon(latlon, duration) setCenterByLatLonAndZoom(latlon, zoomLevel, duration)
You can center the map easily with the Ajax API call, which accepts both address and latitude/longitude. With the Flash API, you must choose what parameter you want to center the map on. However, the Flash centering methods come with panning and zooming ability built in. setMapType(mapType)
setMapViewType(mapViewType)
The only variation in changing the map view type between APIs is that the Flash API refers to tile type as map view. panToXY(YCoordPoint)
SetCenterByPointDelta(point, duration)
In addition to centering and panning the map to latitude/longitude and address, both APIs support changing the map’s location based on x/y coordinates. YGeoPoint(lat, lon) convertLatLonXY(YGeoPoint)
LatLon (latitude, longitude)
Most methods for both APIs require the latitude/longitude to be cast in an object. The processes for doing this are very similar. The Ajax API provides a method for converting a LatLon(YGeoPoint) object into XY. resizeTo(new YSize(width,height))
setSize(width, height)
The APIs offer unique but similar ways to resize the appearance of the map when it is displayed in the mashup or application. The Ajax API requires the height and width values to be cast as a YSize object. convertXYLatLon(new YCoordPoint(x,y))
Point (x, y)
As with latitude/longitude, both APIs make it easy to cast x/y coordinates into a Point or YCoordPoint object. Once again, the Ajax API provides a conversion method to go from an x/y coordinate object to latitude/longitude.
324
API Method Comparison Chart
Basic Get Methods The basic get methods for the APIs enable you to retrieve important data about and settings for the map at any given time. Retrieving data about the map’s current position, zoom level, size and map (view) type can help in coding after the user has begun to engage the map. Ajax Method
Flash Method
getZoomLevel(input) getBestZoomAndCenter(input) getZoomValidLevels getUnitsPerPixel(ZoomLevel)
getZoomLevel()
Both APIs support methods to retrieve the current zoom level of the map. The Ajax API offers similar useful methods such as getBestZoomAndCenter, which suggests to you the best settings to display an array of locations. getCurrentMapType()
getCurrentMapType()
This method retrieves the map’s current view (tile) type. getMapTypes()
getMapViewTypes()
With the only difference being the added view in the name of the Flash API’s method, this method returns an array of valid tile types. getCenterLatLon
getCenter()
The APIs provide a similar way to retrieve the center position of the map. Both methods return their respective latitude/longitude objects. getContainerSize getWidth()
getHeight()
To retrieve the height and width of the map, the Flash API offers two methods. The Ajax API does this with one method and returns an object with the two properties, width and height.
Tools and Widgets The definitions of the terms tool and widget vary between the API types. Tools in the Ajax API are similar to widgets in the Flash APIs. They are sets of buttons and interactive elements that give the user interactive control of the map. Tools in the Flash APIs are defined as maneuverability elements that control the map, primarily based on mouse movement and events.
325
Appendix A Ajax Method
Flash Method
addTypeControl()
addWidget(new SatelliteControlWidget())
To add a set of buttons that let users toggle between map types, the Ajax API provides the addTypeControl method. The Flash API requires a new instance of the SatelliteControlWidget, which is then added using addWidget. enableDragMap disableDragMap isDragMapEnabled disablePanOnDoubleClick() disableKeyControls()
addTool(new PanTool(), isActive) EdgePan() CustomSWFTool (url, iconUrl)
The dragability of the map is a key functionality of both the Ajax and Flash APIs. The Ajax API provides a series of methods for controlling this functionality, including the ability to enable and disable certain interactions with the map. The Flash API lets you enable dragging of the map by adding the PanTool. Advanced mouse interaction with the Flash API allows for unique tools such as EdgePan. You can also develop your own mouse interaction using the CustomSWFTool. addZoomLong addZoomShort addPanControl
AddWidget(new NavigatorWidget)
Through a collection of tools, you can add various zoom buttons and pan arrows to your Ajax mashup. The Flash API enables all this with one effective widget, the NavigatorWidget. Like the engaging device found at maps.yahoo.com, this widget combines an interactive zoombar and minimap. removePanControl
removeTool(tool)
The Ajax API offers a specific method for removing the pan tool. In the Flash API, you must use removeTool, passing the instance of the tool you want to remove from the map instance. removeZoomControl
removeWidget(widget)
You can remove any added widgets in the Flash API by passing their instance into removeWidget. RemoveZoomControl is another example of an Ajax method provided to move a specific tool.
Markers and Overlays These sets of methods and classes enable the organized addition of data to the map instance. While the methods for adding markers and overlays to the map differ in many ways between the Ajax and Flash
326
API Method Comparison Chart APIs, their functionalities are very similar. The Ajax API comes with much overlay functionality built in to its map class. The Flash API does offer several avenues of customizability through a series of CustomSWF classes, such as the CustomSWFMarker. Ajax Method
Flash Method
addMarker(YGeoPoint, id)
addMarkerByLatLon(markerClass, latlon, data) addMarkerByAddress(markerClass, address, data)
Adding markers to the map is a simple task with both types of APIs. You use the open-ended addMarker method in the Ajax API. For the Flash API, you can choose your method based on whether you are adding the marker by latitude/longitude or address. removeMarker(id)
removeMarker(marker)
Removing a marker is nearly identical between the API types. removeMarkersAll
removeAllMarkers()
Both APIs provide the same method for removing all added markers to the map instance. addOverlay(Overlay)
addOverlay(overlay)
The blanket method for adding overlays to the map instance is identical between APIs. removeOverlay(overlayObject)
removeOverlay(overlay)
Once you have an overlay instance, the method for removing it is the same in both API types. searchLocal(YGeoPoint,query, radius,nresults)
LocalSearchOverlay()
The LocalSearchOverlay() class in the Flash API leverages a built-in hook to the Yahoo! Local API. Once you have added the LocalSearchOverlay() class, calling search() against this overlay instance will return results as markers on the map. The Ajax API has a similar built-in ability to query the Yahoo! Local API and return location data. searchTraffic(YGeoPoint,radius)
TrafficOverlay()
Comparable to the local search functionality, the traffic overlay will add traffic indicators based on the location of the map. Both APIs have an effective solution for this.
327
Appendix A YGeoRSS(URL) getGeoBox(points) geoCodeAddress(address)
GeoRSSOverlay(url)
The ability to add geo-encoded RSS feeds is built in to the map class of the Ajax API. To add a geoRSS overlay in the Flash API, you need to add an instance of the GeoRSSOverlay class. YPolyline(points, color, width, alpha) getPolylineIDs() getPolylineObject(id)
PolylineOverlay()
Polyline functionality is added to the map instance of the Ajax map with the Ypolyline class. Within its constructor, you can define the points to plot, as well as the color, width and alpha value of the line. All this information can be built in to an XML file and added with the PolylineOverlay class of the Flash APIs. YImage(srcImg,sizeImg, offsetSmartWindow,offset)
CustomImageMarker(url)
You add an image marker with the Flash API by defining the CustomImageMarker class and the path to the marker when adding a marker instance. With the Ajax API, it’s a bit more involved, requiring you to create a YImage instance and define parameters before adding the marker. YMarker(YGeoPoint, YImage, ID)
CustomPOIMarker (index, title, description, markerColor, strokeColor) CustomSWFMarker (url, ref) WaypointMarker(waypointIndex)
The generic marker class is very standard with the Ajax API. In the Flash API, along with the CustomImageMarker, you can add a customPOIMarker, build your own Flash marker with CustomSWFMarker, or add a basic WayPointMarker.
328
B API Example and Mashup Index Throughout the book, several examples are created to demonstrate the various methods and classes of each API discussed. This index provides file inventories and descriptions for each of the Yahoo! Maps APIs featured in the book. While the code for these examples is covered comprehensively within the chapters of the book, these indexes should provide you easy access to the online repository of Yahoo! Maps examples at www.mashupexperts.com.
Ajax API Examples The following files can be found at www.mashupexperts.com/ymaps/ajax and represent working examples of API methods and classes covered in Chapters 3 through 7. Additional examples will be posted as new features are released. These .htm files feature JavaScript, and you can view their source using the View Source feature in your browser, a coding IDE or a simple text reader such as Notepad. Filename
Description
ajax_addControls
Adds the zoomControl, panControl and mapTypeControl to a map centered on Seattle, WA.
ajax_addImageMarker
Adds an instance of an image marker of a lighthouse on the island of Nantucket. This example also features satellite tiles.
ajax_addMarker
Adds a basic marker in downtown Boston, MA.
ajax_addOverlay_geoRSS
Using geoRSS XML, adds markers of colleges in and around Boston, MA.
ajax_addOverlay_ polyline
Using polyline XML, draws a yellow line to indicate the route of a cruise ship from Ft. Lauderdale, FL, to the Bahamas and back. Table continued on following page
Appendix B Filename
Description
ajax_addPanControl
Adds the PanControl to the map, allowing the user to press arrow buttons to pan the map.
ajax_addTypeControl
Adds the TypeControl to the map, allowing the user to press buttons for map, satellite and hybrid in order to toggle the map’s view type.
ajax_addZoomLong
Adds a scrollable zoom control to the map.
ajax_addZoomShort
Adds a simple, two-button zoom control to the map.
ajax_controlMap
Using a form, lets the user enter an address to change the map’s center position.
ajax_eventTest
Displays various events as the user clicks and pans the map. Events are output to a form text area.
ajax_mapTypes
Outputs the array of map types into a form text area.
ajax_mashup_flickr_json
The Ajax API mashup featured in the book combines Yahoo! Maps with the Flickr API. This example uses JSON output from the Flickr API to display geo-coded (latitude/longitude-enabled) photos on the map.
ajax_settings
This example centers the map on a YGeoPoint displaying satellite tiles of Alcatraz Island in the San Francisco Bay.
ajax_setZoomLevel
Using a form entry, the user can change the zoom level. The new zoom level is returned in the form text area.
JavaScript Flash API Examples The following files can be found at www.mashupexperts.com/ymaps/jsflash and represent working examples of API methods and classes covered in Chapters 8 through 12. Additional examples will be posted as new features are released. These .htm files feature JavaScript, and you can view their source using the View Source feature in your browser, a coding IDE or a simple text reader such as Notepad.
330
Filename
Description
jsflash_addMarkers
The example in this book demonstrates adding various marker classes, including customPOI and customImage, to show castles in Austria.
jsflash_controlMap
A form is used to collect a new address and recenter the map. Additionally, the event_move event is captured to show the new center coordinate.
jsflash_mashup_ travel_json
The JS-Flash mashup merges the map API with Yahoo! Travel’s Trip Planner API. A request is made for trip plan details in Europe. The response, crafted in JSON, is parsed and results in customImage markers displayed.
API Example and Mashup Index Filename
Description
jsflash_panTool
This example demonstrates adding and removing the PanTool, which enables map dragability.
jsflash_trafficOverlay
An instance of the trafficOverlay is added easily to show markers for traffic incidents and alerts in Phoenix, AZ.
jsflash_setMapViewType
A combo box lists available map types, which, when submitted, change the map tiles displayed.
jsflash_setZoomLevel
This example uses a form to collect a new zoom level and sets the map accordingly upon submission. The Zoom_End event is used to display and confirm the map’s new zoom level.
ActionScript Flash API Examples The following files can be found at www.mashupexperts.com/ymaps/asflash and represent working examples of API methods and classes covered in Chapters 13 through 17. Additional examples will be posted as new features are released. These .fla files feature ActionScript 2.0, and can be viewed and compiled using Adobe’s Flash MX 2004 Professional IDE or the Flash 8 Professional IDE. Instructions for obtaining these programs can be found in Chapter 14, “Get Started with the AS-Flash API.” Filename
Description
As_customPOIMarker
Adds a customPOIMarker displaying details of the Washington Monument and White House in Washington, DC.
as_customSWFMarker (customSWFMarker)
This example adds a customSWFMarker over Rome, Italy. Available as a separate file, the marker attached includes a method that is called when the marker’s custom_marker_loaded event fires.
as_customSWFTool (customSWFTool) (customSWFToolIcon)
Adding the customSWFTool is easy with the supplied file, which is provided as a simple template for further exploration. The additional customSWFToolIcon adds an icon in the ToolBarWidget.
As_event_move
The event move example broadcasts the map’s center coordinates as the map is moved.
As_event_zoom
The event zoom example broadcasts the map’s old and new zoom levels (zoom from and zoom to) as the map zooms.
as_geoRSSOverlay (boston_colleges_georss)
Using the supplied XML file, this example loads college logos representing the locations of prestigious colleges in the Boston, MA, area.
As_getMapViewType
This example traces out the current map view type of satellite.
As_getMapViewTypes
This example traces out the list of available map types, returned to the map code as an array. Table continued on following page
331
Appendix B Filename
Description
As_initialize
The initialize event is used in most mashups and is used here to change the location of the map.
As_localSearchOverlay
In this file, the localSearchOverlay is added to display pizza restaurants in Chicago, IL. Additionally, the local search event’s data is traced out to show the full offering of search filter data.
As_mashup_hotjobs_rest
The AS-Flash API featured in this book combines the Yahoo! Maps ActionScript API with the HotJobs web service. This example makes a REST request for job listings based on user entry.
As_move
This example uses the move method to change the stage position of the map component instance.
As_navigatorWidget
Adds the NavigatorWidget to give the user a simple and interactive way to pan and zoom the map.
As_panTool
Adds PanTool and traces out pan events.
As_satelliteControl Widget
Adds the SatelliteControlWidget to give the user three buttons to toggle map view type.
As_setCenterByAddress
Demonstrates centering the map based on an address.
As_setCenterByLatLon
Demonstrates centering the map based on a Latlon object made from a latitude/longitude coordinate.
As_setCenterBy PointDelta
Moves the map to a new center point using the difference between two sets of x and y coordinates.
As_setMapViewType
This example shows how the setMapViewType is called to change the tile set the map displays.
As_trafficOverlay
In this file, the trafficOverlay is added to display available traffic incidents and alerts in the San Jose, CA, area. This overlay class has a built-in hook to Yahoo!’s real-time traffic API.
As_waypointMarker
This example plots key points along a popular bike route in New Hampshire.
AS-Flash/Flex 2 API Examples The following files can be found at www.mashupexperts.com/ymaps/flex2 and represent working examples of API methods and classes covered in Chapters 18 through 22. Additional examples will be posted as new features are released. The combination of files in these examples feature ActionScript 2.0 and 3.0 and Flex 2 MXML. They can be viewed and compiled using Adobe’s Flash MX 2004 Professional IDE or the Flash 8 Professional IDE along with Flex Builder 2. Instructions for obtaining these programs can be found in Chapter 19, “Get Started with Yahoo! Maps and Flex 2.”
332
API Example and Mashup Index Filename
Description
asFlashAPI Flex2Maps MapConnector
This basic set of files proves that the AS-Flash API works great with Flex 2 by adding out-of-the-box tab controls for changing map view type and a metered slider for altering zoom level.
asFlashAPI_address Flex2Maps_address MapConnector_address
Replacing the tab controls with a text field, this example lets the user enter a new address to center the map on. Via the MapConnecter_address class, the request is relayed to the ActionScript Flash instance.
asFlashAPI_getCenter Flex2Maps_getCenter MapConnector_getCenter
This example takes it a step further by returning a request for the center coordinate of the map back to Flex 2, where it is displayed in a text field.
asFlashAPI_mashup_golf Flex2Maps_mashup_golf MapConnector_mashup_ golf
In the section’s mashup example, personal data are mashed up with the map API to display various golf strokes at the Sunol Valley Club. A VideoDisplay control plays actual FLV clips alongside the map instance.
asFlashAPI_marker Flex2Maps_marker MapConnector_marker
This example lets your users add customPOIMarkers to a specified address. In addition, the description, index and title values are set with text fields. The markerColor and StrokeColor properties are set with Flex 2 color selector controls.
asFlashAPI_traffic Flex2Maps_traffic MapConnector_traffic
Using buttons, the Flex 2 interface sends a request via the local connection’s MapConnector_traffic class to add or remove the trafficOverlay class. Once this class has been added, available traffic incidents and alerts in the San Jose, CA, area appear.
333
Index
Index
SYMBOLS /* (backslash, asterisk), 78, 146 // (double backslashes), 77, 146
A actions panel, AS 2, 145–146 ActionScript. See AS-Flash API; AS-Flash API mashup ActionScript 2 (AS 2) actions panel, 145–146 benefits described, 150–151 classes, 148 commenting code, 146 components, 149–150 described, 145 events, 150 mashups outside browser, 151 methods, 148–149 mobile mashup possibilities, 151 Trace(), 149 ActionScript 3 (AS 3), 245 addMarker(), Ajax API, 48 addMarkerByAddress() AS-Flash API, 6, 201–202, 291–292 JS-Flash API, 6, 110 addMarkerByLatLon() AS-Flash API, 202, 292 JS-Flash API, 110 addOverlay() Ajax API, 49, 56 AS-Flash API, 212, 299 JS-Flash API, 121 addPanControl(), Ajax API, 52
address, street allowing users to view location by, AS-Flash API, 271–275 centering and zooming by AS-Flash API, 5, 170, 271 JS-Flash API, 5, 101–102 centering by AS-Flash API, 6, 166–170, 270 JS-Flash API, 6, 101 changing Ajax API, 44–46 JS-Flash API, 105–107 markers, adding Ajax API, 48 AS-Flash API, 6, 201–202, 291–292 JS-Flash API, 6, 110 address, URL GeoRSS feed, 60–61, 218–221 HotJobs RSS request examples, 229–230 HTTP response, 22 JSON request, 67–68, 132 passing to load parameter, 78 addTool() AS-Flash API, 195, 290 JS-Flash API, 115 addTypeControl(), Ajax API, 52 addWidget() AS-Flash API, 189, 289 JS-Flash API, 119 addZoomLong(), Ajax API, 53 addZoomShort(), Ajax API, 53 Adobe Developer channel, 149 Adobe Dreamweaver trial version, obtaining, 29
Adobe Flash Adobe Flash. See also AS-Flash API Ajax API versus basic get methods, 325 basic set methods and classes, 323–324 tools and widgets, 325–326 array data type, 147 RIA, 75 Adobe Flash Communication Server, 149 Adobe Flash IDE described, 142 examples, 332–333 instance, defining, 144–145 layers and depth, 143–144 stage, working with, 142–143 Adobe Flash Lite mobile development support, 151 Adobe Flash Player 9, 244 Adobe Flash Remoting, 149 Ajax API API classes, including, 29–31 application ID, obtaining, 27–28 applications, 18–19 benefits, 24–25 control methods adding to map, 53–55 addPanControl(), 52 addTypeControl(), 52 addZoomLong(), 53 addZoomShort(), 53 removePanControl(), 53 removeZoomControl(), 53 described, 2, 17–18 examples, 329–330 Flash method versus basic get methods, 325 basic set methods and classes, 323–324 markers and overlays, 326–328 tools and widgets, 325–326 initial map parameters, setting, 31–34 JavaScript commenting code, 20 CSS and DHTML, 23–24 described, 19–20 events, 21 functions and methods, 20–21 HTML, 17 XMLHttpRequest, 21–22 map address change exercise, 44–46 map positioning methods and events disableDragMap(), 42–43 drawZoomAndCenter(), 36, 41, 46
336
enableDragMap(), 42–43 endAutoPan, 42 endMapDraw event (redrawing after drawZoomAndCenter), 42 endPan event, 43 getCenterLatLon(), 43 isDragMapEnabled(), 43 onPan event, 43 panToLatLon() (new YGeoPoint, defining), 42 panToXY() (x/y coordinate), 42 startAutoPan, 42 startPan event, 43 map type methods and events getCurrentMapType(), 40 getMapTypes(), 41 setMapType(), 40 map zoom methods and events changeZoom event, 36–37 getZoomLevel(), 37–40 setZoomLevel(), 5, 36 YEvent class, 36 marker methods and classes addMarker(), 48 addOverlay(), 49 image marker, adding to map, 50–52 removeMarker(), 49 removeMarkersAll(), 49 YImage, 49 YMarker, 48–49 markers, 47 mashup approach, 64 coding, 69–73 enhancing, 73–74 Flickr, 63–64, 64–68 information needed, 68 methods, 35 overlay methods and classes addOverlay(), 56 described, 55 GeoRSS overlay, adding, 59–61 polyline overlay, adding, 56–58 YGeoRSS, 58 YPolyline, 56 software requirements, 28–29 album information, MP3 player, 10 API classes, including Ajax API, 29–31 JS-Flash API, integrating with, 85–88
application ID Ajax API, 27–28 AS-Flash API, 153–154 Flex, 255–256 JS Flash API, 83–84 Yahoo! Maps, 255–256 applications, 18–19 array data type, Flash, 147 AS-Flash API application ID, getting, 153–154 AS 2 actions panel, 145–146 benefits, 150–151 classes, 148 commenting code, 146 components, 149–150 described, 145 events, 150 methods, 148–149 Trace(), 149 AS 3, 245 classes, 183 component methods getWidth() and getHeight(), 181 move(), 180 setSize(), 180–181 described, 141, 269 downloading and installing, 154–155, 257–258 events described, 184–185 EVENT_MOVE, 185, 288 EVENT_PAN_START and EVENT_PAN_STOP, 186–187, 288 EVENT_ZOOM, 187–188, 288 EVENT_ZOOM_START and EVENT_ZOOM_STOP, 188–189, 289 setCenterByAddress(), 166–170 examples, 331–332 Flash IDE described, 142 examples, 332–333 instance, defining, 144–145 layers and depth, 143–144 stage, working with, 142–143 map API with ActionScript, 161–163 code, adding, 159–161 default parameters, setting, 158–159 described, 2, 155
document, creating new Flash, 156 document, opening, 156 initializing, 159 movie, compiling, 156–157 stage, 156–158 stage, adding component to, 157–158 map get methods center coordinates, displaying, 280–285 described, 173, 279–280 getCenter(), 6, 174, 280 getCurrentMapViewType(), 174, 285 getMapViewTypes(), 175–180, 285 getZoomLevel(), 174, 285 map objects and methods boundaries (setBounds() and getBounds()), 184, 288 LatLonRect, 184, 288 map set methods address, allowing users to view location by, 271–275 geocode success/error events, 167–170 setCenterByAddress(), 6, 166, 270 setCenterByAddressAndZoom(), 5, 170, 271 setCenterByLatLon(), 6, 171, 275–276 setCenterByLatLonAndZoom(), 171–172, 276–277 setCenterByPointDelta(point,duration), 172–173, 278–279 setMapViewType(), 173, 279 setZoomLevel(), 5, 166, 277–278 marker classes CustomImageMarker, 207, 293 CustomPOIMarker, 6, 203–205, 293–298 CustomSWFMarker, 6, 13, 207–211, 293 described, 202 WaypointMarker, 205–207, 293 marker methods addMarkerByAddress(), 6, 201–202, 291–292 addMarkerByLatLon(), 202, 292 removeAllMarkers(), 202, 292 removeMarker(), 202, 292 mashup described, 223–224 planning and approach, 224 overlay classes CustomSWFOverlay, 222, 299 described, 211–212 GeoRSSOverlay, 218–221, 299 LocalSearchOverlay, 7, 212–216, 299 TrafficOverlay, 7, 216–218, 299–304
337
Index
AS-Flash API
AS-Flash API (continued) AS-Flash API (continued) overlay methods addOverlay(overlay), 212, 299 instance variable, creating, 298–299 removeOverlay(overlay), 212, 299 software requirements, 154 stage, adding to, 258–260 tool classes CustomSWFTool, 197–201, 291 PanTool, 196–197, 291 tool methods addTool(), 195, 290 removeTool(tool), 195, 290 setActiveTool(tool), 195, 290 variable types case sensitivity, 147 common listed, 147 properly typed, examples of, 147 widget classes described, 189 NavigatorWidget, 7–8, 190–192, 289 SatelliteControlWidget, 192–193, 290 ToolBarWidget, 193–195, 289 widget methods addWidget(), 189, 289 removeWidget(), 189, 289 AS-Flash API mashup architecting, 231 described, 223–224 displaying data on map, 239–241 enhancing, 241–242 HotJobs web service described, 224, 229 RSS request, 229–230 RSS response, 230–231 layout map instance, adding, 225–226 user toolbar, adding, 226–228 planning and approach, 224 user interaction, 237–239 XML loading, 231–234 parsing, 234–237 authentication Flickr API, 65 Yahoo! Travel API, 129 authoring tool, Flex Builder 2, 247–249 axes, map geo-coding, 6 getCenter() pixel coordinate, 104, 174
338
B backslash, asterisk (/*), 78, 146 backslashes, double (//), 77, 146 bird’s-eye view, map, 190 Boolean data type, Flash, 147 boundaries (setBounds() and getBounds()), AS-Flash API, 184, 288 browser AS 2 mashups outside, 151 XMLHTTP request, 22 button, adding. See also instance Flex 2 Component Explorer, 247 map toggling, 326 map view buttons example for/each loop, 179 list of map view types, 178 on/off appearance, 180 setting types, 179 UI components, 175–177 SatelliteControlWidget, 192
C callback method JSON, 68 Yahoo! Travel API, 132–133 Capture method, 36 Cascading Style Sheets (CSS) controls, Flex Style Explorer, 248–249 HTML, 79 JavaScript Ajax API, 23–24 case sensitivity, AS-Flash API, 147 category parameter, HotJobs RSS request, 229 center getting Ajax API, 43 AS-Flash API, 6, 174, 280 JS-Flash API, 6, 104 setting by address and zoom AS-Flash API, 5, 170, 271 JS-Flash API, 5, 101–102 setting by latitude/longitude AS-Flash API, 6, 171, 275–276 JS-Flash API, 6, 102–103 setting by latitude/longitude and zoom AS-Flash API, 171–172, 276–277 JS-Flash API, 103 setting by point delta AS-Flash API, 172–173, 278–279 JS-Flash API, 103–104
centering Ajax versus Flash, 324 AS-Flash API, displaying, 280–285 on latitude/longitude, 32–33 changeZoom event, Ajax API, 36–37 city parameter, HotJobs RSS request, 229 classes AS 2, 148 AS-Flash API, 183 client ActionScript, adding, 260–262 Flex 2 mashup controls, coding, 309 data, 307–308 layout, 308–309 MXML, 307 Yahoo! Maps, 264–266 closer, (zoom level) buttons, adding, 326 getting, Ajax versus Flash, 325 JS-Flash API, changing, 99–101 map API, 4–5 methods, Ajax versus Flash, 323–324 start and finish, setting, 94 user interactions, 166 closer, zooming Ajax API changing, 36–37 drawing and centering, 36, 41, 46 getting, 37–40, 94–95, 174, 285 getZoomLevel(), 37–40, 94–95, 174, 285 long, 53 redrawing after, 42 short, 53 AS-Flash API EVENT_ZOOM, 187–188, 288 starting and stopping, 188–189, 289 JS-Flash API getZoomLevel(), 94–95 setZoomLevel(), 94 view type, changing, 95–97 zoomStart, zoomEnd, 94 code occurrences AS 2, 150 AS-Flash API described, 184–185 EVENT_MOVE, 185, 288 EVENT_PAN_START and EVENT_PAN_STOP, 186–187, 288
EVENT_ZOOM, 187–188, 288 EVENT_ZOOM_START and EVENT_ZOOM_STOP, 188–189, 289 setCenterByAddress(), 166–170 JavaScript, 21, 78–79 color-coded areas, 4 commenting code Ajax API, 20 AS 2, 146 JavaScript, 77–78 component methods, AS-Flash API move(), 180 setSize(), 180–181 components, Flash IDE, 143 connection, local Flex 2 mashup, 316–317 MapConnector class, 312–313 SWFs, 246 container for displaying map tiles, creating, 31 control methods, Ajax API adding to map, 53–55 addPanControl(), 52 addTypeControl(), 52 addZoomLong(), 53 addZoomShort(), 53 removePanControl(), 53 removeZoomControl(), 53 controls Flex 2 mashup, coding, 309 Flex Style Explorer, 248–249 coordinates, latitude/longitude Ajax versus Flash methods, 324 boundaries, AS-Flash, 184 center, returning (getCenterLatLon()), 43 centering on AS-Flash API, 171 described, 32–33 Flex 2 method (setCenterByLatLon()), 275–276 centering on and zooming into AS-Flash API, 171–172 Flex 2 method (setCenterByLatLonAndZoom()), 276–277 geo-coding, 6, 166–170 markers, adding, 48 coordinates, x,y geo-coding, 6 getCenter() pixel coordinate, 104, 174 country parameter, HotJobs RSS request, 229
339
Index
country parameter, HotJobs RSS request
CSS (Cascading Style Sheets) CSS (Cascading Style Sheets) controls, Flex Style Explorer, 248–249 HTML, 79 JavaScript Ajax API, 23–24 CustomImageMarker AS-Flash API, 207, 293 JS-Flash API, 111 customization, user Ajax versus Flash API, 325–326 AS-Flash API addTool(), 195, 290 CustomSWFTool, 197–201, 291 mashup, 237–239 PanTool, 196–197, 291 removeTool(), 195, 290 setActiveTool(), 195, 290 Flex 2 mashup client, 309–310 JS-Flash API addTool(), 115 CustomSWFTool, 118–119 PanTool, 115–118 removeTool(), 115 setActiveTool(), 115 trip searches, 130–131 views choosing, 175–180 toggling among, 120, 174 zoom level, 166 customization, user interaction events AS 2, 150 AS-Flash API described, 184–185 EVENT_MOVE, 185, 288 EVENT_PAN_START and EVENT_PAN_STOP, 186–187, 288 EVENT_ZOOM, 187–188, 288 EVENT_ZOOM_START and EVENT_ZOOM_STOP, 188–189, 289 setCenterByAddress(), 166–170 JavaScript, 21, 78–79 user toolbar, 226–228 CustomPOIMarker AS-Flash API, 6, 203–205, 293–298 JS-Flash API, 6, 110–111 CustomSWFMarker AS-Flash API, 6, 13, 207–211, 293 JS-Flash API, 6, 13, 111–112 CustomSWFOverlay, 222, 299 CustomSWFTool AS-Flash API, 197–201, 291 JS-Flash API, 118–119
340
D data, Flex 2 mashup, 307–308 date data type, Flash, 147 default parameters, AS (ActionScript) Flash API, setting, 158–159 deleting all markers Ajax API, 49 AS-Flash API, 202, 292 JS-Flash API, 112 overlay AS-Flash API, 212, 299 JS-Flash API, 121 pan control, Ajax API, 53 specific marker Ajax API, 49 AS-Flash API, 202, 292 JS-Flash API, 112 tools, user interaction AS-Flash API, 195, 290 JS-Flash API, 115 widgets AS-Flash API, 189, 289 JS-Flash API, 119 zoom control, Ajax API, 53 design AS-Flash API mashup map instance, adding, 225–226 user toolbar, adding, 226–228 Flex 2 mashup, 308–309 developers Adobe Developer channel, 149 commenting code for other Ajax API, 20 AS 2, 146 JavaScript, 77–78 DHTML (Dynamic HyperText Markup Language) JavaScript, 23–24 JS-Flash API, CSS and, 79–80 disableDragMap(), Ajax API, 42–43 disabling code for commenting Ajax API, 20 AS 2, 146 JavaScript, 77–78 displaying AS (ActionScript) Flash API mashup data on map, 239–241 DOM (document object model), 20 double backslashes (//), 77, 146 dragability, map checking status, 43 described, 326
disabling, 42–43 enabling, 42–43 draw methods Ajax API drawZoomAndCenter(), 36, 41, 46 endMapDraw event (redrawing after drawZoomAndCenter), 42 Flash, 211 drawZoomAndCenter(), Ajax API, 36, 41, 46 Dynamic HyperText Markup Language (DHTML) JavaScript, 23–24 JS-Flash API, CSS and, 79–80
E Eclipse IDE Flash code, 145 MXML files, 249 ECMAScript language, 20 employment, finding AS-Flash API mashup described, 224, 229 RSS request, 229–230 RSS response, 230–231 mashup source, 13 enableDragMap(), Ajax API, 42–43 endAutoPan, Ajax API, 42 endMapDraw event (redrawing after drawZoomAndCenter), Ajax API, 42 endPan event, Ajax API, 43 enlarging Ajax API changing, 36–37 drawing and centering, 36, 41, 46 getting, 37–40, 94–95, 174, 285 getZoomLevel(), 37–40, 94–95, 174, 285 long, 53 redrawing after, 42 short, 53 AS-Flash API EVENT_ZOOM, 187–188, 288 starting and stopping, 188–189, 289 JS-Flash API getZoomLevel(), 94–95 setZoomLevel(), 94 view type, changing, 95–97 zoomStart, zoomEnd, 94 enlarging view (zoom level) buttons, adding, 326 getting, Ajax versus Flash, 325 JS-Flash API, changing, 99–101
map API, 4–5 methods, Ajax versus Flash, 323–324 start and finish, setting, 94 user interactions, 166 zoombar, NavigatorWidget, 190 zoomEnd, JS-Flash API, 94 Ent, Peter (Adobe developer), 246 event calendar, 13 event listeners, Flex 2 mashup, 317 EVENT_MOVE, AS-Flash API, 185, 288 EVENT_PAN_START and EVENT_PAN_STOP, AS-Flash API, 186–187, 288 events AS 2, 150 AS-Flash API described, 184–185 EVENT_MOVE, 185, 288 EVENT_PAN_START and EVENT_PAN_STOP, 186–187, 288 EVENT_ZOOM, 187–188, 288 EVENT_ZOOM_START and EVENT_ZOOM_STOP, 188–189, 289 setCenterByAddress(), 166–170 JavaScript, 21, 78–79 EVENT_ZOOM, AS-Flash API, 187–188, 288 EVENT_ZOOM_START and EVENT_ZOOM_STOP, AS-Flash API, 188–189, 289 Extensible Markup Language. See XML external code, including in JavaScript, 77
F field local connection events, 318 map instance events, 317 Finance, Yahoo!, 18 Flash Ajax API versus basic get methods, 325 basic set methods and classes, 323–324 tools and widgets, 325–326 array data type, 147 RIA, 75 Flash Communication Server, 149 Flash IDE described, 142 examples, 332–333 instance, defining, 144–145 layers and depth, 143–144 stage, working with, 142–143
341
Index
Flash IDE
Flash Lite mobile development support Flash Lite mobile development support, 151 Flash Player 9, 244 Flash Remoting, 149 Flex authoring tool, Flex Builder 2, 247–249 described, 243 getting, 246 history, 244–245 integrating, 245–246 map API, 2 MapConnector class, 262–264 MXML, 296 RIA, 243 Yahoo! Maps application ID, 255–256 AS-Flash API, downloading and installing, 257–258 benefits, 252 software requirements, 256–257 Flex 2 Component Explorer, 247 Flex 2 mashup client controls, coding, 309 data, 307–308 layout, 308–309 MXML, 307, 310–312 user interaction, 309–310 concept, 305–306 enhancing, 321–322 examples, 332–333 finalizing, 320–321 local connection, MapConnector class, 312–313 planning and approach, 306–307 video, Flash client ActionScript, 316, 318–320 event listeners, 317 field local connection events, 318 field map instance events, 317 importing classes, 316 local connection, 316–317 video media, converting to Flash Video, 314–315 Flex Style Explorer, 248 Flickr Ajax, 18 mashup source, 12–13 trip journal, adding photos to, 129 Flickr API authentication, 65 described, 63–64 JSON callback, 68 request, making, 67–68
342
methods flickr.people.getPublicPhotos call, 67 flickr.photos.search REST call, 66 photos, geo-tagging, 64–65 flickr.people.getPublicPhotos call, 67 flickr.photos.search REST call, 66 FLV files, 149 for/each loop button, 179 Foronda, Nahuel (asfusion.com developer), 246 functions Ajax API, 20–21 JavaScript, 78
G geo-coding axes, map, 6 latitude/longitude, 6, 166–170 success/error events, 167–170 GeoRSSOverlay Ajax API, 59–61 AS-Flash API, 218–221, 299 described, 11–12 get methods Ajax versus Flash API, 325 boundaries, AS-Flash API, 184, 288 center AS-Flash API, 6, 174, 280 JS-Flash API, 6, 104 center by latitude and longitude, Ajax API, 43 center coordinates, AS-Flash API, 280–285 described, 37 map type, Ajax API, 40, 41 map view AS-Flash API, 174, 175–180, 285 JS-Flash API, 98 width and height, AS-Flash API, 181 Yahoo! Travel API, 131 zoom level Ajax API, 37–40 AS-Flash API, 174, 285 JS-Flash API, 94–95 getBounds(), AS-Flash API, 184, 288 getCenter() AS-Flash API, 6, 174, 280 JS-Flash API, 6, 104 pixel coordinate, x/y coordinate, 104 getCenterLatLon(), Ajax API, 43 getCurrentMapType(), Ajax API, 40 getCurrentMapViewType() AS-Flash API, 174, 285 JS-Flash API, 98
getMapTypes(), Ajax API, 41 getMapViewTypes() AS-Flash API, 175–180, 285 JS-Flash API, 98–99 getTrip, Yahoo! Travel API, 131 getWidth() and getHeight(), AS-Flash API, 181 getZoomLevel() Ajax API, 37–40 AS-Flash API, 174, 285 JS-Flash API, 94–95
H height, map, AS-Flash, 181 HotJobs web service AS-Flash API mashup described, 224, 229 RSS request, 229–230 RSS response, 230–231 mashup source, 13 HTML (HyperText Markup Language) Ajax API, 17 container for displaying map tiles, creating, 31 CSS, 79 JavaScript, 19 JS-Flash API, integrating with API classes, including, 85–88 map loading, 138–139 map paramaters, setting initial, 88–90 marker object, 48–49 HTTP (HyperText Transfer Protocol) response, 22 hybrid view, 4
I ID, application Ajax API, 27–28 AS-Flash API, 153–154 Flex, 255–256 JS Flash API, 83–84 Yahoo! Maps, 255–256 image map and satellite, 3–4 marker adding in Flash and Ajax, 50–52, 328 AS-Flash API, 207, 293 JS-Flash API, 111 types, Flash IDE, 142 YImage, Ajax API, 49 importing classes, Flex 2 mashup, 316 index, waypoints, 205–207 initial map parameters, setting, Ajax API, 31–34
initializing AS-Flash API, 159 instance AS-Flash API creating, 298–299 mashup, adding, 225–226 Flash IDE, defining, 144–145 interactivity Ajax versus Flash API, 325–326 AS 2, 150 AS-Flash API addTool(), 195, 290 CustomSWFTool, 197–201, 291 described, 184–185 EVENT_MOVE, 185, 288 EVENT_PAN_START and EVENT_PAN_STOP, 186–187, 288 EVENT_ZOOM, 187–188, 288 EVENT_ZOOM_START and EVENT_ZOOM_STOP, 188–189, 289 mashup, 237–239 PanTool, 196–197, 291 removeTool(), 195, 290 setActiveTool(), 195, 290 setCenterByAddress(), 166–170 Flex 2 mashup client, 309–310 JavaScript, 21, 78–79 JS-Flash API addTool(), 115 CustomSWFTool, 118–119 PanTool, 115–118 removeTool(), 115 setActiveTool(), 115 trip searches, 130–131 views choosing, 175–180 toggling among, 120, 174 zoom level, 166 Internet Explorer (Microsoft), XMLHTTP request, 22 isDragMapEnabled(), Ajax API, 43
J JavaScript. See also JS-Flash API; JavaScript Object Notation (JSON) Ajax API commenting code, 20 CSS and DHTML, 23–24 described, 19–20 events, 21 functions and methods, 20–21 HTML, 17 XMLHttpRequest, 21–22
343
Index
JavaScript
JavaScript (continued) JavaScript (continued) commenting code, 77–78 events, 78–79 external code, including, 77 functions and methods, 78 HTML container for displaying map tiles, creating, 31 JavaScript Object Notation (JSON) Flickr API request, making, 67–68 Yahoo! Travel API described, 131 request, making, 132 job openings, finding AS-Flash API mashup described, 224, 229 RSS request, 229–230 RSS response, 230–231 mashup source, 13 JS-Flash API application ID, getting, 83–84 benefits, 80 CSS and DHTML, 79–80 described, 75–76 examples, 330–331 HTML, integrating with API classes, including, 85–88 map paramaters, setting initial, 88–90 JavaScript commenting code, 77–78 described, 76–77 events, 78–79 external code, including, 77 functions and methods, 78 map positioning methods and events address, changing, 105–107 getCenter(), 6, 104 mapGeocodeSuccess, mapGeocodeError events, 102 move event, 104 setCenterByAddress(), 6, 101 setCenterByAddressAndZoom(), 5, 101–102 setCenterByLatLon(), 6, 102–103 setCenterByLatLonAndZoom(), 103 setCenterByPointDelta(), 103–104 map type methods and events getCurrentMapViewType(), 98 getMapViewTypes(), 98–99 mapTypeChanged event, 98 setMapViewType(), 97–98 zoom level, changing, 99–101
344
map zoom methods and events getZoomLevel(), 94–95 setZoomLevel(), 5, 94 view type, changing, 95–97 zoomStart, zoomEnd, 94 marker methods and classes addMarkerByAddress(), 6, 110 addMarkerByLatLon(), 110 CustomImageMarker, 111 CustomPOIMarker, 6, 110–111 CustomSWFMarker, 6, 111–112 map, adding variety of markers to, 112–114 removeAllMarkers(), 112 removeMarker(), 112 WayPointMarker, 111 markers, 109 mashup coding, 133–139 described, 127 enhancing, 139–140 planning and approach, 128 Yahoo! Travel API, 128–133 overlay methods and classes addOverlay(overlay), 121 CustomSWFOverlay, 125 GeoRSSOverlay, 124 LocalSearchOverlay, 7, 121–122 removeOverlay(overlay), 121 TrafficOverlay, 7, 122–124 software requirements, 84–85 tool methods and classes addTool(), 115 CustomSWFTool, 118–119 PanTool, 115–118 removeTool(tool), 115 setActiveTool(tool), 115 transitioning between APIs, 85 widget methods addWidget(), 119 NavigatorWidget, 7–8, 94, 119–120 removeWidget(), 119 SatelliteControlWidget, 120 ToolBarWidget, 120 JSON (JavaScript Object Notation) Flickr API request, making, 67–68 Yahoo! Travel API described, 131 request, making, 132
K keyframes, 142–143 keywords parameter, HotJobs RSS request, 229
L label blank marker, adding to, 48–49 layer of map, 4 latitude/longitude Ajax versus Flash methods, 324 boundaries, AS-Flash, 184 center, returning (getCenterLatLon()), 43 centering on AS-Flash API, 171 described, 32–33 Flex 2 method (setCenterByLatLon()), 275–276 centering on and zooming into AS-Flash API, 171–172 Flex 2 method (setCenterByLatLonAndZoom()), 276–277 geo-coding, 6, 166–170 markers, adding, 48 LatLonRect, AS-Flash API, 184, 288 layer, labeling, 4 layout AS-Flash API mashup map instance, adding, 225–226 user toolbar, adding, 226–228 Flex 2 mashup, 308–309 local connection Flex 2 mashup, 316–317 MapConnector class, 312–313 SWFs, 246 local search database, Yahoo!, 121–122 local search mashup source, 15 LocalSearchOverlay AS-Flash API, 7, 212–216, 299 JS-Flash API, 7, 121–122 longitude/latitude Ajax versus Flash methods, 324 boundaries, AS-Flash, 184 center, returning (getCenterLatLon()), 43 centering on AS-Flash API, 171 described, 32–33 Flex 2 method (setCenterByLatLon()), 275–276
centering on and zooming into AS-Flash API, 171–172 Flex 2 method (setCenterByLatLonAndZoom()), 276–277 geo-coding, 6, 166–170 markers, adding, 48
M map address change exercise, Ajax API, 44–46 map and satellite imagery, views, 3–4 map API AJAX, 2 AS-Flash, 2 AS-Flash API with ActionScript, 161–163 code, adding, 159–161 creating new Flash, 156 default parameters, setting, 158–159 described, 155 document, initializing, 159 movie, compiling, 156–157 stage, 156–158 described, 1 Flex, 2 geo-coding, 6 map and satellite imagery, 3–4 markers and custom markers, 6–7 navigation, 7–8 overlays, 7 panning, 5–6 technology, 2–3 zooming, 4–5 Map (container, appid, location, zoom, mapViewType) method, 323 map get methods, AS-Flash API center coordinates, displaying, 280–285 described, 173, 279–280 getCenter(), 6, 174, 280 getCurrentMapViewType(), 174, 285 getMapViewTypes(), 175–180, 285 getZoomLevel(), 174, 285 map objects and methods, AS-Flash API boundaries (setBounds() and getBounds()), 184, 288 LatLonRect (minLat,minLon,maxLat,maxLon), 184 map paramaters, setting initial, JS (JavaScript)-Flash API, integrating with, 88–90
345
Index
map paramaters, setting initial
map positioning methods and events map positioning methods and events Ajax API disableDragMap(), 42–43 drawZoomAndCenter(), 36, 41, 46 enableDragMap(), 42–43 endAutoPan, 42 endMapDraw event (redrawing after drawZoomAndCenter), 42 endPan event, 43 getCenterLatLon(), 43 isDragMapEnabled(), 43 onPan event, 43 panToLatLon() (new YGeoPoint, defining), 42 panToXY() (x/y coordinate), 42 startAutoPan, 42 startPan event, 43 JS-Flash API address, changing, 105–107 getCenter(), 6, 104 mapGeocodeSuccess, mapGeocodeError events, 102 move event, 104 setCenterByAddress(), 6, 101 setCenterByAddressAndZoom(), 101–102 setCenterByLatLon(), 6, 102–103 setCenterByLatLonAndZoom(), 103 setCenterByPointDelta(), 103–104 map set methods, AS-Flash API address, allowing users to view location by, 271–275 geocode success/error events, 167–170 setCenterByAddress(), 6, 166, 270 setCenterByAddressAndZoom(), 5, 170, 271 setCenterByLatLon(), 6, 171, 275–276 setCenterByLatLonAndZoom(), 276–277 setCenterByPointDelta(point,duration), 172–173, 278–279 setMapViewType(), 173, 279 setZoomLevel(), 5, 166, 277–278 map type methods and events Ajax API getCurrentMapType(), 40 getMapTypes(), 41 setMapType(), 40 JS-Flash API getCurrentMapViewType(), 98 getMapViewTypes(), 98–99 mapTypeChanged event, 98 setMapViewType(), 97–98 zoom level, changing, 99–101 map view buttons example for/each loop, 179 list of map view types, 178
346
setting types, 179 UI components, 175–177 map zoom methods and events Ajax API changeZoom event, 36–37 getZoomLevel(), 37–40 setZoomLevel(), 36 YEvent class, 36 JS-Flash API getZoomLevel(), 94–95 setZoomLevel(), 94 view type, changing, 95–97 zoomStart, zoomEnd, 94 MapConnector class ActionScript coding, 262–264 Flex 2 mashup, 312–313 mapGeocodeSuccess, mapGeocodeError events, 102 maps API. See Yahoo! Maps Maps API Application Gallery, 16 mapTypeChanged event, JS-Flash API, 98 marker methods and classes Ajax API addMarker(), 48 addOverlay(), 49 image marker, adding to map, 50–52 removeMarker(), 49 removeMarkersAll(), 49 YImage, 49 YMarker, 48–49 AS-Flash API addMarkerByAddress(), 6, 201–202, 291–292 addMarkerByLatLon(), 202, 292 CustomImageMarker, 207, 293 CustomPOIMarker, 6, 203–205, 293–298 CustomSWFMarker, 6, 13, 207–211, 293 described, 202 removeAllMarkers(), 202, 292 removeMarker(marker), 202, 292 WaypointMarker, 205–207, 293 JS-Flash API addMarkerByAddress(), 6, 110 addMarkerByLatLon(), 110 CustomImageMarker, 111 CustomPOIMarker, 6, 110–111 CustomSWFMarker, 6, 111–112 map, adding variety of markers to, 112–114 removeAllMarkers(), 112 removeMarker(), 112 WayPointMarker, 111 marker object, HTML, 48–49
markers address, adding, 48 Ajax API, 47 JS-Flash API, 109 map API, 6–7 mashup Ajax approach, 64 coding, 69–73 enhancing, 73–74 Flickr, 63–64 AS 2, 151 described, 9–10 JS-Flash API coding, 133–139 enhancing, 139–140 Yahoo! Travel API, 128–133 REST, 10–11 RSS and GeoRSS feeds, 11–12 sources Flickr, 12–13 HotJobs, 13 local search, 15 traffic, 14 Upcoming.org, 13 weather, 14 XML, 10 Yahoo! developer support Maps API Application Gallery, 16 message group, 15 YDN (Yahoo! Developer Network), 15 mashup, AS-Flash API architecting, 231 described, 223–224 displaying data on map, 239–241 enhancing, 241–242 HotJobs web service described, 224, 229 RSS request, 229–230 RSS response, 230–231 layout map instance, adding, 225–226 user toolbar, adding, 226–228 planning and approach, 224 user interaction, 237–239 XML loading, 231–234 parsing, 234–237 mashup, Flex 2 client controls, coding, 309 data, 307–308
layout, 308–309 MXML, 307, 310–312 user interaction, 309–310 concept, 305–306 enhancing, 321–322 examples, 332–333 finalizing, 320–321 local connection, MapConnector class, 312–313 planning and approach, 306–307 video, Flash client ActionScript, 316, 318–320 event listeners, 317 field local connection events, 318 field map instance events, 317 importing classes, 316 local connection, 316–317 video media, converting to Flash Video, 314–315 masking, Flash IDE, 143–144 media, converting to Flash Video, 314–315 Mercator map projection model, 3 message group, Yahoo! developer support, 15 methods Ajax API, 35 AS 2, 148–149 Flickr API flickr.people.getPublicPhotos call, 67 flickr.photos.search REST call, 66 JavaScript, 20–21, 78 Yahoo! Travel API getTrip, 131 tripSearch, 130–131 Microsoft Internet Explorer, XMLHTTP request, 22 middle. See center; centering mini-map AS-Flash API, 7–8, 190–192, 289 JS-Flash API, 7–8, 94, 119–120 mobile mashup possibilities, AS 2 (ActionScript 2), 151 mouse interaction Ajax versus Flash API, 325–326 AS-Flash API addTool(), 195, 290 CustomSWFTool, 197–201, 291 PanTool, 196–197, 291 removeTool(), 195, 290 setActiveTool(), 195, 290 JS-Flash API addTool(), 115 CustomSWFTool, 118–119 PanTool, 115–118 removeTool(), 115 setActiveTool(), 115
347
Index
mouse interaction
move(), AS-Flash API move(), AS-Flash API, 180 move event, JS-Flash API, 104 moving view Ajax versus Flash methods, 324 automatic ending, 42 starting, 42 begin, 186–187 control adding, 52 removing, 53 to latitude/longitude point, 42 start, 43 stop, 43, 186–187 tool, user interaction AS-Flash API, 196–197, 291 JS-Flash API, 115–118 new YGeoPoint, defining, 42 views, 5–6 movie clip, adding. See instance movie, compiling, 156–157 MovieClip data type, Flash, 147 MP3 player album information, 10 AS-Flash support, 149 music album information, MP3 player, 10 MXML described, 243 Flex 2 mashup, 307 Flex client AS-Flash API, 271–272, 280–284 completing, 310–312 controls and layout, 309 described, 296 user interaction, 309–310 Yahoo! Maps, 264–266 Yahoo! Maps coding and ActionScript, 250–252 described, 249 Flex client, 264–266
N NavigatorWidget AS-Flash API, 7–8, 190–192, 289 JS-Flash API, 7–8, 94, 119–120 null data type, Flash, 147 number data type, Flash, 147
348
O object data type, Flash, 147 objects and methods, AS-Flash API boundaries (setBounds() and getBounds()), 184, 288 LatLonRect, 288 LatLonRect (minLat,minLon,maxLat,maxLon), 184 occurrences, code AS 2, 150 AS-Flash API described, 184–185 EVENT_MOVE, 185, 288 EVENT_PAN_START and EVENT_PAN_STOP, 186–187, 288 EVENT_ZOOM, 187–188, 288 EVENT_ZOOM_START and EVENT_ZOOM_STOP, 188–189, 289 setCenterByAddress(), 166–170 JavaScript, 21, 78–79 on/off appearance, map view buttons, 180 onPan event, Ajax API, 43 overlay methods and classes Ajax API addOverlay(), 56 described, 55 GeoRSS overlay, adding, 59–61 polyline overlay, adding, 56–58 YGeoRSS, 58 YPolyline, 56 AS-Flash API addOverlay(overlay), 212, 299 CustomSWFOverlay, 222, 299 GeoRSSOverlay, 218–221, 299 instance variable, creating, 298–299 LocalSearchOverlay, 7, 212–216, 299 removeOverlay(overlay), 212, 299 TrafficOverlay, 7 JS-Flash API addOverlay(overlay), 121 LocalSearchOverlay, 7, 121–122 removeOverlay(overlay), 121 TrafficOverlay, 7 overlays AS-Flash API, 211–212 map API, 7
P panning Ajax versus Flash methods, 324 automatic ending, 42 starting, 42 begin, 186–187 control adding, 52 removing, 53 to latitude/longitude point, 42 start, 43 stop, 43, 186–187 tool, user interaction AS-Flash API, 196–197, 291 JS-Flash API, 115–118 new YGeoPoint, defining, 42 views, 5–6 panoramic shot, 5 panToLatLon() (new YGeoPoint, defining), Ajax API, 42 PanTool AS-Flash API, 196–197, 291 JS-Flash API, 115–118 new YGeoPoint, defining, 42 panToXY() (x/y coordinate), Ajax API, 42 parameter, passing URL to load, 78 passing URL to load parameter, 78 photo site, Flickr Ajax, 18 mashup source, 12–13 trip journal, adding photos to, 129 photo site, Flickr API authentication, 65 described, 63–64 JSON callback, 68 request, making, 67–68 methods flickr.people.getPublicPhotos call, 67 flickr.photos.search REST call, 66 photos, geo-tagging, 64–65 picture map and satellite, 3–4 marker adding in Flash and Ajax, 50–52, 328 AS-Flash API, 207, 293 JS-Flash API, 111 types, Flash IDE, 142 YImage, Ajax API, 49
POI (point of interest) AS-Flash API, 6, 203–205, 293–298 JS-Flash API, 6, 110–111 polyline overlay, Ajax API, 56–58 positioning methods and events Ajax API disableDragMap(), 42–43 drawZoomAndCenter(), 36, 41, 46 enableDragMap(), 42–43 endAutoPan, 42 endMapDraw event (redrawing after drawZoomAndCenter), 42 endPan event, 43 getCenterLatLon(), 43 isDragMapEnabled(), 43 onPan event, 43 panToLatLon() (new YGeoPoint, defining), 42 panToXY() (x/y coordinate), 42 startAutoPan, 42 startPan event, 43 JS-Flash API address, changing, 105–107 getCenter(), 6, 104 mapGeocodeSuccess, mapGeocodeError events, 102 move event, 104 setCenterByAddress(), 6, 101 setCenterByAddressAndZoom(), 101–102 setCenterByLatLon(), 6, 102–103 setCenterByLatLonAndZoom(), 103 setCenterByPointDelta(), 103–104 projection map technology, 2 properly typed variables, AS (ActionScript) Flash API, 147
R Radario.com, 18 Really Simple Syndication. See RSS feed reference on map AS-Flash API, 205–207, 293 JS-Flash API, 111 removeAllMarkers() Ajax API, 49 AS-Flash API, 202, 292 JS-Flash API, 112 removeMarker() Ajax API, 49 AS-Flash API, 202, 292 JS-Flash API, 112
349
Index
reference on map
removeOverlay() removeOverlay() AS-Flash API, 212, 299 JS-Flash API, 121 removePanControl(), Ajax API, 53 removeTool() AS-Flash API, 195, 290 JS-Flash API, 115 removeWidget() AS-Flash API, 189, 289 JS-Flash API, 119 removeZoomControl(), Ajax API, 53 removing all markers Ajax API, 49 AS-Flash API, 202, 292 JS-Flash API, 112 overlay AS-Flash API, 212, 299 JS-Flash API, 121 pan control, Ajax API, 53 specific marker Ajax API, 49 AS-Flash API, 202, 292 JS-Flash API, 112 tools, user interaction AS-Flash API, 195, 290 JS-Flash API, 115 widgets AS-Flash API, 189, 289 JS-Flash API, 119 zoom control, Ajax API, 53 request Flickr API, 67–68 Yahoo! Travel API, 132 resizing, Ajax versus Flash methods, 324 REST (Representational State Transfer) mashup, 10–11 RIA (rich internet applications) Flash, 75 Flex, 243 RSS (Really Simple Syndication) feed controlling, Ajax versus Flash, 328 mashup, 11–12 request, 229–230 response, 230–231
S satellite views, 3–4 SatelliteControlWidget AS-Flash API, 192–193, 290 button, adding, 192 JS-Flash API, 120
350
scaling map technology, 3 set methods and classes active tools AS-Flash API, 195, 290 JS-Flash API, 115 boundaries, AS (ActionScript) Flash API, 184, 288 center by address, then zoom AS-Flash API, 5, 170, 271 JS-Flash API, 5, 101–102 center by latitude and longitude AS-Flash API, 6, 171, 275–276 JS-Flash API, 6, 102–103 center by latitude and longitude, then zoom AS-Flash API, 171–172, 276–277 JS-Flash API, 103 center by point delta AS-Flash API, 172–173, 278–279 JS-Flash API, 103–104 Flash versus Ajax API, 323–324 map type, Ajax API, 40 size, AS-Flash API, 180–181 view type AS-Flash API, 173, 279 JS-Flash API, 97–98 zoom level Ajax API, 36 AS-Flash API, 5, 166, 277–278 JS-Flash API, 5, 94 setActiveTool() AS-Flash API, 195, 290 JS-Flash API, 115 setBounds(), AS (ActionScript) Flash API, 184, 288 setCenterByAddressAndZoom() AS-Flash API, 5, 170, 271 JS-Flash API, 5, 101–102 setCenterByLatLon() AS-Flash API, 6, 171, 275–276 JS-Flash API, 6, 102–103 setCenterByLatLonAndZoom() AS-Flash API, 171–172, 276–277 JS-Flash API, 103 setCenterByPointDelta() AS-Flash API, 172–173, 278–279 JS-Flash API, 103–104 setMapType(), Ajax API, 40 setMapViewType() AS-Flash API, 173, 279 JS-Flash API, 97–98 setSize(), AS (ActionScript) Flash API, 180–181
setZoomLevel() Ajax API, 36 AS-Flash API, 5, 166, 277–278 JS-Flash API, 5, 94 ShockWave Flash. See SWF files side to side, panning Ajax versus Flash methods, 324 automatic ending, 42 starting, 42 begin, 186–187 control adding, 52 removing, 53 to latitude/longitude point, 42 start, 43 stop, 43, 186–187 tool, user interaction AS-Flash API, 196–197, 291 JS-Flash API, 115–118 new YGeoPoint, defining, 42 views, 5–6 sources, mashup HotJobs, 13 local search, 15 traffic, 14 Upcoming.org, 13 weather, 14 stage AS-Flash API, 156–158, 258–260 Flash IDE, working with, 142–143 startAutoPan, Ajax API, 42 startPan event, Ajax API, 43 state parameter, HotJobs RSS request, 229 street address allowing users to view location by, AS-Flash API, 271–275 centering and zooming by AS-Flash API, 5, 170, 271 JS-Flash API, 5, 101–102 centering by AS-Flash API, 6, 166–170, 270 JS-Flash API, 6, 101 changing Ajax API, 44–46 JS-Flash API, 105–107 markers, adding Ajax API, 48 AS-Flash API, 6, 201–202, 291–292 string data type, Flash, 147
SWF (ShockWave Flash) files described, 142 markers AS-Flash API, 6, 13, 207–211, 293 JS-Flash API, 6, 13, 111–112 overlay, 222, 299 tool, user interaction AS-Flash API, 197–201, 291 JS-Flash API, 118–119 symbol, adding. See instance symbols, Flash IDE, 143
T tags, Flickr, 12–13 tiles, container for displaying, 31 timeline, Flash stage, 142–143 tool methods and classes Ajax versus Flash API, 325–326 AS-Flash API addTool(), 195, 290 CustomSWFTool, 197–201, 291 PanTool, 196–197, 291 removeTool(), 195, 290 setActiveTool(), 195, 290 JS-Flash API addTool(), 115 CustomSWFTool, 118–119 PanTool, 115–118 removeTool(), 115 setActiveTool(), 115 ToolBarWidget AS-Flash API, 193–195, 289 JS-Flash API, 120 Trace(), AS 2 (ActionScript 2), 149 traffic mashup source, 14 TrafficOverlay AS-Flash API, 7, 216–218, 299–304 JS-Flash API, 7 transitioning, JS (JavaScript)-Flash API, 85 Travel API. See Yahoo! Travel API trip journal, adding photos to, 129 trip searches, user interactions, 130–131 tripSearch, Yahoo! Travel API, 130–131
U UI components, map view buttons example, 175–177 undefined data type, Flash, 147 Upcoming.org mashup source, 13
351
Index
Upcoming.org mashup source
URL URL GeoRSS feed, 60–61, 218–221 HotJobs RSS request examples, 229–230 HTTP response, 22 JSON request, 67–68, 132 passing to load parameter, 78 user interaction Ajax versus Flash API, 325–326 AS-Flash API addTool(), 195, 290 CustomSWFTool, 197–201, 291 mashup, 237–239 PanTool, 196–197, 291 removeTool(), 195, 290 setActiveTool(), 195, 290 Flex 2 mashup client, 309–310 JS-Flash API addTool(), 115 CustomSWFTool, 118–119 PanTool, 115–118 removeTool(), 115 setActiveTool(), 115 trip searches, 130–131 views choosing, 175–180 toggling among, 120, 174 zoom level, 166 user interaction events AS 2, 150 AS-Flash API described, 184–185 EVENT_MOVE, 185, 288 EVENT_PAN_START and EVENT_PAN_STOP, 186–187, 288 EVENT_ZOOM, 187–188, 288 EVENT_ZOOM_START and EVENT_ZOOM_STOP, 188–189, 289 setCenterByAddress(), 166–170 JavaScript, 21, 78–79 user toolbar, 226–228
V variable types, case sensitivity, 147 version parameter, HotJobs RSS request, 229 video, Flex 2 mashup ActionScript, 316, 318–320 event listeners, 317 field local connection events, 318 field map instance events, 317
352
importing classes, 316 local connection, 316–317 media, converting to Flash Video, 314–315 views Ajax versus Flash methods, 324, 326 map and satellite imagery, 3–4, 173 panning, 5–6 toggling among, 120, 174 type, changing, 95–97 user interactions, 175–180 zooming, 4–5
W WayPointMarker AS-Flash API, 205–207, 293 JS-Flash API, 111 weather mashup source, 14 web browser AS 2 mashups outside, 151 XMLHTTP request, 22 widget methods and classes Ajax versus Flash API, 325–326 AS-Flash API addWidget(), 189, 289 described, 189 NavigatorWidget, 7–8, 190–192, 289 removeWidget(), 189, 289 SatelliteControlWidget, 192–193, 290 ToolBarWidget, 193–195, 289 JS-Flash API addWidget(), 119 NavigatorWidget, 7–8, 94, 119–120 removeWidget(), 119 SatelliteControlWidget, 120 ToolBarWidget, 120 width, map, AS-Flash, 181 work, finding AS-Flash API mashup described, 224, 229 RSS request, 229–230 RSS response, 230–231 mashup source, 13
X XML (Extensible Markup Language) AS-Flash API mashup loading, 231–234 parsing, 234–237
data type Flash, 147 geoRSS feed, 218–221 HotJobs RSS response, 230–231 mashup, 10 XMLHTTP request, Internet Explorer (Microsoft), 22 XMLHttpRequest, JavaScript, 21–22 x,y coordinates geo-coding, 6 getCenter() pixel coordinate, 104, 174
Y Yahoo! Developer Network. See YDN Yahoo! developer support. See also YDN Maps API Application Gallery, 16 message group, 15 Yahoo! Finance, 18 Yahoo! local search database, 121–122 Yahoo! Maps Flex ActionScript, adding to client side, 260–262 application ID, 255–256 AS-Flash API, 257–260 authoring tool, Flex Builder 2, 247–249 benefits, 252 client, 264–266 described, 243 getting, 246 history, 244–245 integrating, 245–246 MapConnector class, 262–264 software requirements, 256–257 MXML coding and ActionScript, 250–252 described, 249 Yahoo! Travel API authentication, 129 JSON callback method, 132–133 described, 131 request, making, 132 methods getTrip, 131 tripSearch, 130–131 travel content, location and, 128–129 YDN (Yahoo! Developer Network) Ajax ID application ID, 27–28 AS-Flash application ID, 153–154 downloading and installing components, 154–155, 257–258
Flickr API application ID, 64 HotJobs web service, 229 JS Flash API application ID, 83–84 mashup developer support, 15 Yahoo! Maps application ID, 255–256 components, downloading, 257–258 Yahoo! Travel API, 128 YEvent class, Ajax API, 36 YGeoPoint, 41 YGeoRSS, Ajax API, 58 YImage, Ajax API, 49 YMap(mapContainer, mapType, mapSize) method, 323 YMarker, Ajax API, 48–49 YPolyline, Ajax API, 56
Z zoom level buttons, adding, 326 getting, Ajax versus Flash, 325 JS-Flash API, changing, 99–101 map API, 4–5 methods, Ajax versus Flash, 323–324 start and finish, setting, 94 user interactions, 166 zoombar, NavigatorWidget, 190 zoomEnd, JS-Flash API, 94 zooming Ajax API changing, 36–37 drawing and centering, 36, 41, 46 getting, 37–40, 94–95, 174, 285 getZoomLevel(), 37–40, 94–95, 174, 285 long, 53 redrawing after, 42 short, 53 AS-Flash API EVENT_ZOOM, 187–188, 288 starting and stopping, 188–189, 289 JS-Flash API getZoomLevel(), 94–95 setZoomLevel(), 94 view type, changing, 95–97 zoomStart, zoomEnd, 94 zoomStart, JS-Flash API, 94
353
Index
zoomStart, JS-Flash API
Programmer to Programmer TM BROWSE BOOKS
P2P FORUM
FREE NEWSLETTER
ABOUT WROX
Get more Wrox
at Wrox.com! Special Deals
Free Chapter Excerpts
Take advantage of special offers every month
Be the first to preview chapters from the latest Wrox publications
Unlimited Access. . .
Forums, Forums, Forums
. . . to over 70 of our books in the Wrox Reference Library (see more details on-line)
Take an active role in online discussions with fellow programmers
Meet Wrox Authors! Read running commentaries from authors on their programming experiences and whatever else they want to talk about
Browse Books .NET SQL Server Java
XML Visual Basic C#/ C++
Join the community! Sign-up for our free monthly newsletter at newsletter.wrox.com