Using the Yahoo! Maps Flash API

29 August, 2006

With the release of Yahoo! Maps beta, an ActionScript and Flex-based map application, Yahoo! also released the Maps beta API. This API is designed to give you the unique opportunity of integrating much of the enhanced functionality and precise map data into your own Macromedia Flash applications.

The Yahoo! Maps API is distributed as a Flash component, packaged to integrate easily into your own code. Because Yahoo! serves up the mapping data, there are no server requirements on your part other than snapping in the simple component. Once I walk you through the quick component installation (same as any MXP packaged V2 component), I’ll review with you several copy-and-paste code examples. Within minutes, you’ll be building a map-based application that allows your users to pan, zoom, and even search and display listings from the Yahoo! Local Search.

The best part is that, thanks to the inventory of simple API calls, adding each of these great features requires no more than a simple understanding of a few lines of code. The sky’s the limit—and you have over a dozen zoom levels to explore it.

Requirements

In order to make the most of this article, you need the following software and files:

Macromedia Flash 8

Note: You can also use Macromedia Flash MX 2004.

You need an application ID to use the AS-Flash API (Yahoo! login required).

Notes about the sample code in this article:

  • Throughout this article, I will continue to mention the very comprehensive Reference Manual for the Yahoo! Maps Flash APIs. The Yahoo! Developer Network has put together a great launch pad to get you started with the Maps component.
  • The examples in the article are full copy-and-paste code excerpts. While I encourage you to add your own elements, I wanted to provide you with as much of a head start as possible.
  • To implement all the code examples, you can simply add them to the first frame of your FLA file. It is good practice to create separate layers for the component and the ActionScript.
  • If you are using an IDE such as Eclipse, PrimalScript, or SEPY, you can drop the code in your AS script or class files to work with your application.
  • Start each section with a new FLA file. This is how I wrote each example and it helps to have a clean slate to understand the unique functionality being presented.

The basics: The YahooMap component

Let’s start at the beginning.

Install the component:

  1. Download the Yahoo! Maps MXP.
  2. Double-click the MXP to launch the Macromedia Extension Manager. You may need to download the latest extension manager. After accepting the installation terms and clicking OK, the API will be fully installed.
  3. Obtain an application ID from the Yahoo! Developer Network.
  4. Launch the Flash application (Flash MX 2004 or later) and expand the Components window (Control + F7). You should see the YahooMap component listed in the Components panel.

Set the stage:

  1. Create a new Flash file.
  2. Drag the YahooMap component to your Stage and keep it selected.
  3. In the Properties panel, with the YahooMap component on the Stage selected, name the instance of the YahooMap component myMap. (All the code excerpts in this article refer to the map instance as “myMap”.)
  4. Resize the component to 500 x 400 pixels, either in the Properties panel or by using the Free Transform Tool (Q).
  5. Back in the Properties panel, select the Parameters tab. Enter the AppID you registered with the Yahoo! Developer Network.

See the world:

  1. Compile the FLA file (Control + Enter).
  2. Continue to read and explore this article and learn how you can change the world that you have created with the Yahoo! Maps API.

Tools and widgets: Controlling the map

Tools are a set of behaviors you can add to the map to give your users more control over the displayed content. Panning is probably the most frequent user action when it comes to maps interaction. Importing the PanTool class and creating an instance of it once the map initializes lets your users click and drag the map in all directions. The panning class adds click and double-click capabilities, which center the map on a certain point and zoom in on a specific point, respectively:

import com.yahoo.maps.tools.PanTool;
myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap);
function onInitMap(eventData) {
     var panTool = new PanTool();
     myMap.addTool(panTool, true);
}

Reminder: Start each section with a new FLA file. This is how I wrote each example in this tutorial. It helps to have a clean slate to understand the unique functionality being presented for each section.

The NavigatorWidget is a very sleek interface, combining the essential zoom bar with the super “minimap” navigation tool. The minimap replicates the very large map data and scales it into a much smaller window. The minimap provides precision navigation of the big map, like a voodoo doll.

In the center of the minimap is a draggable box (some call it the “hockey puck”). When a user drags the box up, the larger map pans up too, and so on. The box in the center of the minimap also scales to the displayed proportions of the component as a whole. This widget appears in the top right of the map:

import com.yahoo.maps.widgets.NavigatorWidget;
myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap);
function onInitMap(eventData) {
     var navWidget = new NavigatorWidget("open");
     myMap.addWidget(navWidget);
}

The NavigatorWidget has two states, open and closed, which you can controll by passing the initial state when creating the instance. When it’s closed, the Navigator shows only the vertical zoom bar. Even when it’s open, the user can still close the Navigator by clicking the little white arrow (see Figure 1). The sleek widget, in Flash fashion, animates between states.

NavigatorWidget with the minimap that a user can use to zoom in on a region

Figure 1. NavigatorWidget with the minimap that a user can use to zoom in on a region

While I will go into more detail on changing the map view in the next set of examples, adding the SatelliteControlWidget is a quick way of providing your users with a cool way to toggle the map view. The SatelliteControlWidget consists of three buttons (one for each map view type) and displays in the top-left corner of your map.

This example shows that you can create an instance of a widget without saving it to a variable. This saves a line of code, but will make it harder to call methods on this widget. Unlike the Navigator, the Satellite Control has no open/closed states:

import com.yahoo.maps.widgets.SatelliteControlWidget;
myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap);
     function onInitMap(eventData) {
     myMap.addWidget(new SatelliteControlWidget());
}

Map views: Changing to satellite and hybrid

The API lets you work with satellite and hybrid tiles, in addition to the default map tiles. I’m going to show you three simple ways to display and let your users choose the different kinds of map views to display with the component in your application.

You can set the default map view type when the component first loads. On the Stage, select the component and then look in the Parameter tab to select the map view type. The component collects this parameter when it first is created, providing the best experience for the user.

To set the map view type programmatically, use the setMapViewType method. Note that the map loads first with the default type and then redraws upon initializing, with the new map view type:

import com.yahoo.maps.MapViews;
myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap);
function onInitMap(eventData) {
     myMap.setMapViewType(MapViews.SATELLITE); //for Hybrid use MapViews.HYBRID
}

The API gives you some options for changing the map view type outside the component. By using getMapViewTypes, you get an array (“map”, “hybrid”, “satellite”).

The following example shows how you can build your own set of map view buttons, a custom alternative to the SatelliteControlWidget that I discussed previously, using getMapViewTypes(). Creating or attaching your own buttons, particularly outside the map, lets you control the map with user interface elements consistent with your application. While the SatelliteControlWidget buttons are rather small and tightly designed, putting buttons alongside the map will open up your map area a bit more.

After the map initializes, getMapViewTypes() can be called, giving you the array of all map view types available. Loop through this array and call the makeButton function, passing the iteration value and map view type value:

myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap);
function onInitMap(eventData) {
    var mapViews:Array = myMap.getMapViewTypes();
    for (var i=0;i< mapViews.length;i++) {
        makeButton(i, mapViews[i]);
    }
}

This is where you can attach or create buttons. Coding a function like the makeButton function lets you create some simple, lightweight buttons (see Figure 2). By incrementing the y or x values, you can manage the placement of the buttons either vertically or horizontally. Be sure to set the variable for your y/x value outside the function.

Adding buttons to the map

Figure 2. Adding buttons to the map

In this example, I use the _buttonX variable to lay out the buttons across the top of the application. Within the onPress function, you call the setMapViewType with the label value. This changes the map view when the user clicks each button. You can also use a simple conditional to track the state of the buttons. To do this, you will need to use another method, getCurrentMapViewType. The text in the button will be bold when it represents the active map type:

var _buttonX:Number = 0;
var _selButton;
function makeButton(i:Number, mapView:String) {
    var buttonBase:MovieClip = this.createEmptyMovieClip("buttonBase"+I, i);
    buttonBase._x = _buttonX;
    buttonBase.moveTo(0, 0);
    buttonBase.lineStyle(1, 0x000000, 100);
    buttonBase.beginFill(0x999999, 100);
    buttonBase.lineTo(100, 0);
    buttonBase.lineTo(100, 22);
    buttonBase.lineTo(0, 22);
    buttonBase.lineTo(0, 0);
    var buttonLabel:TextField = buttonBase.createTextField("buttonLabel", 1, 0, 0, 100, 22);
    buttonLabel.id = mapView;
    buttonLabel.html = true;
    buttonLabel.selectable = false;

if (mapView == myMap.getCurrentMapViewType()) {
        buttonLabel.htmlText = "<b>" + mapView + "</b>";
        _selButton = buttonLabel;
    } else {
        buttonLabel.htmlText = mapView;
    }

buttonBase.onPress = function () {
        this._parent.myMap.setMapViewType(buttonLabel.text);
        _selButton.text = _selButton.id;
        buttonLabel.htmlText = "<b>" + buttonLabel.text + "</b>";
        _selButton = buttonLabel;
    }

_buttonX+=120;
}

Explore the Reference Manual for the Yahoo! Maps Flash APIs to find out how you can use your own buttons to control many other aspects of the map.

Overlays: The Local search feature

Think of overlays as potential weather systems on top of the map. Essentially, they are a container for managing multiple markers and movie clips on top of the map, within a single layer. Overlays manage data independent of the core map. Once they’re initialized, you can turn them on and off programmatically.

Adding the LocalSearchOverlay to your map and application gives your users a gateway in the powerful Yahoo! Local database and services. After the map initializes, create a new instance of the LocalSearchOverlay. I suggest saving the overlay instance to a global variable. This makes the overlay instance available to other functions in subsequent examples. Use addOverlay to add the overlay instance to the map.

When working with markers, it is good to let the user pan, so I suggest adding the PanTool. And because this is local content, set Chicago as the default city, using setCenterByAddress(). Finally, use makeLocalSearch() to build the form elements, allowing users to enter their own local search criteria:

var _localSearch;
import com.yahoo.maps.overlays.LocalSearchOverlay;
import com.yahoo.maps.tools.PanTool;
myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap);
function onInitMap(eventData) {
    _localSearch = new LocalSearchOverlay();
    myMap.addOverlay(_localSearch);
    var panTool = new PanTool();
    myMap.addTool(panTool, true);
    myMap.setCenterByAddress("Chicago");
    makeLocalSearch();
}

This simple makeLocalSearch function builds a text input field and button. As I mentioned previously, when you build satellite buttons, you can use your attach components or your own graphic elements:

var _searchInput:TextField;
function makeLocalSearch() {

var inputBase:MovieClip = this.createEmptyMovieClip("inputBase", 1);
    inputBase._x = 0;
    inputBase.width = 100;
    inputBase.height = 22;
    _searchInput = inputBase.createTextField("searchInput", 1, 0, 0, 100, 22);
    _searchInput.border = true;
    _searchInput.background = true;
    _searchInput.selectable = true;
    _searchInput.type = "input";
    _searchInput.text = "Pizza";

var searchButton:MovieClip = this.createEmptyMovieClip("searchButton", 2);
    searchButton._x = 120;
    searchButton.moveTo(0, 0);
    searchButton.lineStyle(1, 0x000000, 100);
    searchButton.beginFill(0x999999, 100);
    searchButton.lineTo(100, 0);
    searchButton.lineTo(100, 22);
    searchButton.lineTo(0, 22);
    searchButton.lineTo(0, 0);
    var searchLabel:TextField = searchButton.createTextField("searchButton", 1, 0, 0, 100, 22);
    searchLabel.selectable = false;
    searchLabel.text = "Search";

searchButton.onPress = function () {
        this._parent.searchLocal();
    }
}

One more effect I will add is an event that zooms in on the map once the address above it resolves itself. When working with local content, the closer you get, the more relevant your search results will appear:

myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_MAP_GEOCODE_SUCCESS, onMapMove);
function onMapMove(eventData) {
    myMap.setZoomLevel(5);
}

The LocalSearchOverlay uses the search method to query the local database. Searching the Yahoo! Local database—in this case with hard-coded search criteria—the returned data is represented with attached markers within the overlay.

These markers represent local listings, complete with addresses, ratings data, and a More Info link to Yahoo! Locals, giving your users a splendid resource and adding depth to the area being displayed in your map (see Figure 3). Your application will call searchLocal(): when the map finishes zooming and, more importantly, each time your user clicks the Submit button.

Map with Yahoo! Local content, featuring address and rating data within a marker.

Figure 3. Map with Yahoo! Local content, featuring address and rating data within a marker.

On first pass, I need to plug in a variable. Because I’m using Chicago as a location, my default search criteria is none other than “Pizza”:

myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_ZOOM_STOP, searchLocal);
function searchLocal(eventData) {
    var searchVar:String = "";
    if (_searchInput.text == undefined) {
        searchVar = "Pizza";
    } else {
        searchVar = _searchInput.text;
    }
    _localSearch.search(searchVar, this._parent.myMap.getCenter(), 1, 10);
}

Find out more details on LocalSearchOverlay and its methods in the Reference Manual for the Yahoo! Maps Flash APIs.

Geocoding: Converting an address to latitude/longitude

Geocoding is at the heart of map data. It’s the “flux capacitor” of the maps machine. Whether they are built in Flash or Ajax, all map applications use some form of geocoding to resolve coordinates around the world and offer several key map functionalities, such as locating an address, calculating driving directions, and displaying traffic use geocoding.

In our Flash maps, we take the coordinates (latitude and longitude, or what we call “latlon”) and convert them into points (x and y) in the application. When determining where a user has panned or zoomed to in the application, we reverse the process going from points to latlon.

In this final exercise, I show you how to resolve the latlon based on the center point of your map. You might find this technique useful when creating your own mashup. If you are setting out to plot points on your map—adding markers and such—you will likely create your own RSS (called geoRSS for maps points), XML, or database to store those points.

Storing latlon coordinates can be much more efficient and provide better performance than storing and processing address strings. Another benefit is that by passing a latlon instead of an address string to a method, you have more options for controlling the map programmatically.

First, import the LatLon class, which will let you convert the points to a latlon object. To get the initial map center coordinates, use getCenter() when the map first initializes:

import com.yahoo.maps.LatLon;
import com.yahoo.maps.tools.PanTool;
myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_INITIALIZE, onInitMap);
function onInitMap(eventData) {
    var pantool = new PanTool();
    myMap.addTool(pantool, true);
    var points = myMap.getCenter();
    convert(points);
}

Using your preferred debugging method (such as the trace(), for instance), display the values returned by the getCenter() method. This method returns points, values that are in reverse order of latitude and longitude. In other words, and this can be tricky, x and y represent the horizontal and vertical location of the point, while latitude and longitude represent the opposite: Latitude is the vertical location and longitude is the horizontal location.

As I mentioned earlier, there are several other events fired based on map interaction and movement. Adding the EVENT_MOVE listener to the map will ultimately let you call getCenter() each time the user moves the map.

myMap.addEventListener(com.yahoo.maps.api.flash.YahooMap.EVENT_MOVE, onMapMove);
function onMapMove() {
    var points = myMap.getCenter();
    convert(points);
}

Finally, taking the object returned by getCenter() and creating a new LatLon object with it will convert those points into latitude and longitude. Remember, you need to switch the values to get the right point. The best way to do this is by getting the latitude and longitude properties, “lat” and “lon” respectively. Adding the trace() method should display your latitude/longitude in the output window.

var _latlon:Object;
function convert(points:Object) {
	_latlon = new LatLon(points.lat, points.lon);
	trace(_latlon);
}

You can find more methods you can call with a latlon value in the Reference Manual for the Yahoo! Maps Flash APIs.

Where to go from here

I hope these code examples give you a great start in developing your own maps mashup. Be sure to visit the Yahoo! Developer Network’s excellent coverage and examples of the Yahoo! Maps APIs.

Acknowledgements

Special thanks to Zach Graves, who lent his expertise as a technical reviewer for this article.

About the author

Charles (Chuck) Freedman is a senior Flash developer for Yahoo! Maps, where he leads development for both the consumer and API versions of the Flex-based Maps application. With a Communications degree in Film and Television from Boston University, Chuck combines his education in multimedia with expertise in content management, server-side scripting, and database and interactive design. Recently he has produced some of the most highly visible dynamic Flash content, developing modules for the home pages of eBay, eBay China, and Fidelity. Visit his website at chuckstar.com. Born in Boston, Chuck relocated with his wife Jamie to sunny Santa Clara, Calif., to join Yahoo! in 2005. Still a season ticket holder, he is planning many trips back east to see his beloved Red Sox win another World Series.


Windows XP Explorer menus (only info)

29 August, 2006

 

 

http://www.dynarch.com/products/navbar/

As you could have figured out already, Dynarch NavBar is very close to the all-so-known Windows XP Explorer menus. The missing part was a CSS file that defines a similar look. Well, there you have it! :-)

In order to make your NavBar look like WinXP menus, just load the /navbar/themes/winxp/skin.css skin, and set _NavBar_icons_url = "/navbar/themes/winxp/". View the source of this page for more details.

You can read more information about CSS files and custom icons in the NavBar documentation.

JavaScript actions

As of version 2.5, NavBar supports custom JavaScript action handlers for menu items in a very straightforward way. Instead of passing an URL, just pass a reference to a JavaScript function which is previously defined. In order to pass a custom argument to that function, put it in place of the “target” attribute. For example:

function showDate(param, item, section) {
    var menu = section.parent;
    // "menu" is a reference to the NavBar object
    // you can use it now i.e. to set preferences:
    // menu.setPref("auto-hide", true);

    // but let's show the date:
    alert(new Date() + "\nPassed argument is: " + param);
}
var menu = new NavBar(...);
new NavSection(menu, "Section label", [
   [ "Show date", showDate, "tooltip", "icon.gif", "custom argument" ]
]);

The above code creates an item that will call our custom function “showDate” when clicked. The function receives 3 arguments. Beware that the first one may be undefined if you don’t pass it. In the code above though we pass it and its value is “custom argument”. The other two arguments are “item” — a referenece to the TR element that holds the item elements, and “section” — a reference to the NavSection object that this item belongs to.


Using the AJAX Map Viewer Component

29 August, 2006

This tutorial shows you how to use Sun Java Studio Creator’s Integrated Development Environment (IDE) to build a JavaServer Faces web application that uses the sample AJAX Map Viewer component. You import the Java BluePrints AJAX components into the IDE, then use Google’s free map service API to create a custom map. The map includes marker text and a flag that pinpoints an address entered by the user.

The sample Java BluePrints AJAX components are provided to help you learn about AJAX and to show how AJAX fits with the Java Studio Creator IDE. For an introduction to the AJAX technology, see AJAX and Sun Java Studio Creator 2.

 

Contents

 

- Obtaining a Google Maps API Key
- Creating the AJAX Web Application
- Adding a Map Coordinates Input Page
- Adding a Map Marker
- Adding a Map Marker Flag
- Doing More With the AJAX Map Viewer Component
[spacer] Content on this page applies to Sun Java Studio Creator 2

 

Obtaining a Google Maps API Key

 
To use the Google map service APIs, you must first create a Google account if you do not already have one, log in, and obtain a map key. The Google map key is specific to your application and allows up to 50,000 page views each day. Both the Google account and map key are free.

  1. In your web browser, go to http://www.google.com/apis/maps/.

    The Google map key sign up page opens in your web browser.

  2. Click Sign up for a Google Maps API key.

    The Google map key license agreement page opens in your web browser.

  3. Review, then accept the agreement and enter the URL for your web site.

    To find the URL for your web site, deploy an application and look at the server name and port number. For example, http://localhost:28080/.

    The URL that you specify must exactly match the one that you use to execute the application. You may use this same key for any application using the Google Maps API that you deploy to your local application server. If you reconfigure your server to use a port or you deploy to a different server, then you must obtain another key from Google.

  4. Click Generate API Key.

    Google generates your map key.

  5. Copy the map key and save it in a text file or other convenient location. You use the map key as you build the AJAX map viewer application.

 

Creating the AJAX Web Application

 
Now you create the first page of the application, which contains the Map Viewer component.

  1. Download and import the AJAX components if you have not already done so.
  2. Create a web application project and name it AjaxMapViewer.

    AjaxMapViewer’s initial page, Page1, opens in the Visual Designer.

  3. In the Palette, expand the BluePrints AJAX Components node if it is not already expanded, then drag the Map Viewer component and drop it onto Page1.

    A map image appears on Page1 and the components mapViewer1 and mapViewer1_center appear in the Outline window, similar to the following figure.

    Map Viewer Component

    Figure 1: Map Viewer Component

     

  4. In the Properties window, find the Map Viewer’s key property and enter the Google map key that you saved earlier, as shown in the the following figure.

    Map Key Property

    Figure 2: Map Key Property

     

  5. Build and run the application to see what you have so far. The AjaxMapViewer project opens in your web browser.

    Map Viewer Application, Take 1

    Figure 3: Map Viewer Application, Take 1

     

Adding a Map Coordinates Input Page

 
The latitude and longitude properties of the mapViewer1_center component determine the map location. In this section, you add a page that takes a text address as input and uses the AJAX Support Bean Geocoding Service Object component to convert the address into latitude and longitude coordinates. You add latitude and longitude properties to the Request Bean and use these properties to set the coordinates on the mapViewer1_center component.

 
Designing the Map Coordinates Input Page

  1. In the Projects window, right-click AjaxMapViewer > Web Pages and choose New > Page from the pop-up menu.
  2. In the New Page dialog box, type the file name GetCoordinates, and click Finish.

    The IDE opens the GetCoordinates page in the Visual Designer. The following figure shows the page you will design.
     

    GetCoordinates Page Design

    Figure 4: GetCoordinates Page Design

     

  3. From the Basic section of the Palette, drag a Label component and drop it in the upper-left corner of the page. Set the text of the Label to Enter an address:
  4. Drag a Text Field component and drop it to the right of the Label component. In the Properties window, set the Text Field’s required property to True.
  5. Drag a Button component onto the page and drop it below the Text Field component. Set the Button’s text property to Get Map and the id property to getMap.
  6. Drag a Message Group component onto the page and drop it below the Get Map button.

 
Setting Up Page Navigation

  1. Right-click anywhere in the Visual Designer and choose Page Navigation from the pop-up menu.

    The Page Navigator window opens in the IDE.

  2. Click the GetCoordinates.jsp icon and drag a connector from the getMap button to Page1.jsp.
  3. In the Projects window, right-click the AjaxMapViewer > Web Pages > GetCoordinates node and choose Set As Start Page from the pop-up menu.

    A green arrow appears next to the GetCoordinates node, as shown in the following figure.

    GetCoordinates Start Page Mark

    Figure 5: GetCoordinates Start Page Mark

     

Adding the Input Logic

 

  1. Return to the GetCoordinates page by clicking its tab.
  2. From the BluePrints AJAX Support Beans section of the Palette, drag the Geocoding Service Object component and drop it anywhere the GetCoordinates page.

    The geoCoder1 component appears in the Outline window, as shown in the following figure.

    geoCoder1 in the Outline Window

    Figure 6: geoCoder1 in the Outline Window

     

  3. If you are working behind a firewall, configure the proxy settings on the geoCoder1 component because it does not retrieve the proxy settings from the IDE. If you are not working behind a firewall, skip this step.
    1. In the Properties window for the geoCoder1 component, set the proxyHost property to the appropriate proxy for your location.
    2. Set the proxyPort property to the appropriate port for your location.

Adding Latitude and Longitude Properties to the Request Bean

 

  1. In the Outline window, right-click RequestBean1 and choose Add > Property from the pop-up menu.

    The New Property Pattern dialog box opens.

  2. Enter longitude in the Name field and double (lower-case) in the Type field, and then click OK.
  3. Create a second Request Bean property. Enter latitude for the Name and double (lower-case) for the Type, and then click OK.
  4. Double-click the Get Map button in the Visual Designer. The IDE opens the GetCoordinates page in the Java editor at the getMap_action() method.
  5. Add the following code (shown in bold) to the getMap_action() method.

    Code Sample 1: GetMap Button Code
    public String getMap_action() {
            GeoPoint points[] = geoCoder1.geoCode((String)textField1.getText());
            if (points.length < 1) {
                error("Sorry, cannot find that location; please be more specific.");
               return null;
            }
            getRequestBean1().setLatitude(points[0].getLatitude());
            getRequestBean1().setLongitude(points[0].getLongitude());
             return "case1";
    }

     

  6. Right-click in the Java Editor, then choose Fix Imports from the pop-up menu to resolve the GeoPoint not found error.
  7. Click the Page1 tab and then click the Java button.
  8. In the Java Editor for Page1, scroll down to the prerender() method and add the following code shown in bold.

    Code Sample 2: prerender Method
    public void prerender() {
            mapViewer1_center.setLatitude(getRequestBean1().getLatitude());
            mapViewer1_center.setLongitude(getRequestBean1().getLongitude());
    }

     

  9. Build and run the application. AjaxMapViewer opens in your web browser. Enter a physical address, such as 15 Network Circle, Menlo Park, CA, and click the Get Map button. A map showing the location you entered opens in your web browser, similar to the following figure.
     

    Take 2

    Figure 7: Map Viewer Application: Take 2

     

Adding a Map Marker

 
The map you created in the previous section shows the area around the location you entered, but does not pinpoint the location itself. In this section, you add a map marker to the application.

 

  1. Open the Design View for Page1.
  2. From the BluePrints AJAX Support Beans section of the Palette, drag a Map Marker component and drop it anywhere on Page1.
  3. In the Properties window for mapMarker1, set the markup property to This is the place!.
  4. In the Outline window, right-click the mapViewer1 component and choose Property Bindings from the pop-up menu.
  5. In the Property Bindings dialog box, bind mapViewer1’s info property to Page1’s mapMarker1 property, as shown in the following figure. Click Apply, then Close.

    Binding the  mapViewer1 info property to mapMarker1

    Figure 8: Binding the mapViewer1 info Property to mapMarker1

     

  6. Double-click anywhere on Page1 to open the Java Editor.
  7. Scroll to the prerender() method and add with the following two lines shown in bold.

    Code Sample 3: prerender() Method With Map Marker Support
    public void prerender() {
            mapViewer1_center.setLatitude(getRequestBean1().getLatitude());
            mapViewer1_center.setLongitude(getRequestBean1().getLongitude());
            mapMarker1.setLatitude(mapViewer1_center.getLatitude());
           mapMarker1.setLongitude(mapViewer1_center.getLongitude());
    }

     
    This code sets the coordinates on the mapMarker1 component so that it points to the location on which the map is centered.

  8. Build and run the application. When the AjaxMapViewer application opens in your web browser, enter an address such as 15 Network Circle, Menlo Park, CA, and then click the Get Map button. The map opens in your web browser with a map marker pointing to the location, similar to the following figure.
     

    Map with Map Marker

    Figure 9: Map Viewer Application: Take 3

     

Adding a Map Marker Flag

 
Finally, you add a map marker flag to further pinpoint the map location. 

  1. In the Java Editor for Page1, find the public class Page1 extends AbstractPageBean declaration. Add the following code (shown in bold) under the Creator-Managed Component Definition code fold.
    Code Sample 4: Adding a MapMarker Array to Page1
    public class Page1 extends AbstractPageBean {
        Creator-managed Component Definition
    
    private MapMarker[] markers;
        public MapMarker[] getMarkers(){
            return markers;
        }

     

  2. Scroll to the prerender() method and add the following two lines of code shown in bold.
    Code Sample 5: prerender() Method With Map Marker Flag Code
    public void prerender() {
            mapViewer1_center.setLatitude(getRequestBean1().getLatitude());
            mapViewer1_center.setLongitude(getRequestBean1().getLongitude());
            mapMarker1.setLatitude(mapViewer1_center.getLatitude());
            mapMarker1.setLongitude(mapViewer1_center.getLongitude());
            markers = new MapMarker[1];
           markers[0] = mapMarker1;
    }

     

  3. Click the Design button to return to the Page1 Design View.
  4. In the Outline window, right-click the mapViewer1 component and choose Property Bindings from the pop-up menu.
  5. In the Property Bindings dialog box, bind mapViewer1’s markers property to Page1’s markers array, as shown in the following figure. Click Apply, then Close.
     

    Binding the Markers Property to the Markers Array

    Figure 10: Binding the Markers Property to the Markers Array

     

  6. Build and run the application. Enter an address such as 15 Network Circle, Menlo Park, CA, and then click the Get Map button. The map opens in your web browser with a map marker and flag pointing to the location, similar to the following figure.
     

    Map with Map Marker

    Figure 11: Map Viewer Application: Take 4

     

Doing More With the Ajax Map Viewer Component

 
Try It. In the section Adding a Map Marker Flag, you added a MapMarker array to contain the map marker and marker flag. Try using the array to place multiple markers on the map.

 
Try It. This tutorial shows how to store the MapMarker array at page scope. Try storing the MapMarker array at session scope and implement an “add a marker” page to add markers to the map. Ensure that the extra addresses you provide appear on the map at the scale factor you are using. The default scale factor is 4.

 
Try It. This tutorial shows how to use one Java BluePrints AJAX map component to create one custom map. Try building an application that creates more than one map. Rather than store the Google map service API key as a property on each map component that you use, create a context initialization parameter named com.sun.j2ee.blueprints.ui.mapviewer.KEY in your web.xml file and store the Google map service API key value there.