Google Maps API v2
Google Maps API v2
CHAPTER 1: INTRODUCTION TO GOOGLE MAPS...................................................................... 3 1.1 WHAT IS GOOGLE MAPS? ................................................................................................................. 4 1.2 GETTING A GOOGLE MAPS KEY ...................................................................................................... 4 1.3 GOOGLE MAPS DOCUMENTATION ................................................................................................... 4 1.4 CREATING A BASIC GOOGLE MAP WITH CONTROLS .......................................................................... 4 CHAPTER 2: THE GOOGLE MAPS API.......................................................................................... 11 2.1 GMAP2 ......................................................................................................................................... 12 2.2 GPOINT AND GLATLNG ................................................................................................................ 15 2.3 GMARKER ..................................................................................................................................... 16 2.4 GPOLYLINE .................................................................................................................................. 16 2.5 A WORD ABOUT POLYGONS .......................................................................................................... 17 2.6 GSIZE ........................................................................................................................................... 17 2.7 GLATLNGBOUNDS ........................................................................................................................ 17 CHAPTER 3: MAP CONTROLS........................................................................................................ 17 3.1 PANNING ...................................................................................................................................... 18 3.2 ZOOMING..................................................................................................................................... 18 3.3 MAP TYPE CONTROLS .................................................................................................................... 19 3.4 OVERVIEW MAP CONTROL ............................................................................................................ 20 3.5 SCALE CONTROL ............................................................................................................................ 21 CHAPTER 4: ADDING USER DATA................................................................................................ 22 4.1 GMARKER ..................................................................................................................................... 22 4.2 GICON .......................................................................................................................................... 23 4.3 INFO WINDOWS ............................................................................................................................. 24 CHAPTER 5: EVENTS....................................................................................................................... 27 5.1 GEVENT ....................................................................................................................................... 27 5.2 GMAP2 EVENTS ............................................................................................................................ 28 5.3 GMARKER EVENTS ........................................................................................................................ 29 CHAPTER 6: GEOCODING.............................................................................................................. 30 6.1 GEOCODING SOFTWARE ................................................................................................................ 31 6.2 YAHOO GEOCODING API .............................................................................................................. 31 6.3 GOOGLE GEOCODING HACK ......................................................................................................... 31 6.4 GEOCODER.US ............................................................................................................................... 34 6.5 COMMERCIAL GEOCODING SOLUTIONS .......................................................................................... 35 CHAPTER 7: AJAX .............................................................................................................................. 35 7.1 WHAT IS AJAX?............................................................................................................................. 35 7.2 XMLHTTPREQUEST...................................................................................................................... 36 Table1.CommonXMLHttpRequestObjectMethods. .................................................................... 37 Table2.CommonXMLHttpRequestObjectProperties................................................................. 38 7.3 GXMLHTTP ................................................................................................................................... 39 7.4 GDOWNLOADURL FUNCTION ........................................................................................................ 41 CHAPTER 8: DEBUGGING CODE IN GOOGLE MAPS................................................................. 42 CHAPTER 9: SUMMARY.................................................................................................................... 43
Headquarters. You can copy and paste the HTML and JavaScript generated into a plain text file, save it to the web server directory you specified when you generated the key, and then display the map in your web browser. As you begin working with the Google Maps API you will notice how easy it is to create a basic, navigable map with just a few lines of code. Lets begin by creating a basic Google Map and then well expand on that by adding navigation and map type controls as well as markers and info windows. First, take a look at the basic example map below.
Lets take a look at the code that was used to generate this simple map. All the code examples that you will see in this book will be written in JavaScript.
The <script> tags are used to designate an area that will be used to write JavaScript code. The first <script> tag that you see in this example imports the Google Maps library. The key that you generated must be inserted here. In addition, you must also specify a Google Maps version id. Notice in our code sample that were using version 2 of the Google Maps API which was released on April 3rd, 2006. Although version 2 was designed to be 99% compatible with version 1 you should make plans to upgrade any existing code that you have written as soon as possible because Google will ultimately default everything to version 2.
Here is the full code used to generate the basic Google Map.
The <div> tag serves as a placeholder for your map. Youll want to give the tag a name through the id attribute. In this case weve simply named our placeholder map. The second <script> tag is where all the work of creating your Google Map occurs. o new GMap2( ) creates the Google Map. In the constructor for GMap2 you simply pass in the <div> specifying where the map will appear. o map.setCenter centers the map at a particular latitude, longitude and zooms to the level specified. Google uses an 17 point scale with zoom level 0 showing the entire world and zoom level 17 zoomed to the street level.
Now that youve seen a basic Google Map lets take the next step and add the navigation and map type components. We will add each of these components through the addControl( ) method on the GMap2 object.
Notice in the code example that weve added two controls to our map. map.addControl(new GLargeMapControl()) o Adds a map zoom control that allows the user to change the zoom level of the map. This control is always located on the left hand side of the map. map.addControl(new GMapTypeControl()) o Adds a control to the top right hand corner of the map that allows the user to flip between the Map, Satellite, and Hybrid views. These two lines of code result in a map that now looks like the figure below.
By default, the Normal view will be displayed when you create a new instance of a Google Map. However, you can change this to any of three basic types, and with version 2 of the API you can now create your own map types. For instance, if youd like the initial display of your map to be a hybrid display of satellite imagery and streets you could do so with the code that you see below.
The setMapType method is used to control the view of the map. o G_HYBRID_MAP displays a combination of satellite imagery and streets o G_NORMAL_MAP is the default and provides a display of the regular streets o G_SATELLITE_MAP displays a satellite image
Although it is relatively simple we now have a fully functional web mapping application with just a few lines of code. We can pan, zoom in and out, and change the display style of the map. Next, lets add some point data to our map and attach an info window that well use to display attribute information about the point. This is where the true power of Google Maps really comes into play. By giving you the ability to add points of interest and polylines you can supplement Google Maps with your own user specific data sets. In addition, the Google Maps API provides classes and methods that allow you to read your user specific data from an XML file stored on your server making it easy to centralize the storage of your points of interest. This ability to plot user specific data in the form of points and polylines has truly opened the world of dynamic web applications to the masses. Although mapping applications have existed on the web for roughly a decade they have remained largely in the domain of large organizations with the resources available to purchase and support the infrastructure necessary to run these applications. However, Google Maps greatly simplifies the task of creating web based mapping applications and at a mere fraction of the cost in both monetary and human resource terms. With that said lets take a look at how you can add points of interest and info windows to your Google Maps application. Examine the code example below to see how to add points of interest and info windows. Copyright 2006: Geospatial Training & Consulting, LLC 9
Lets take a look at some of the code required to add points of interest and info windows to your Google Map. The GLatLng and GMarker classes work together to produce a point of interest that can be plotted on your map. o var pt = new GLatLng(-96.340264, 30.609682) This creates a point object centered at the longitude, latitude coordinate specified. o var marker = new GMarker(pt) Using the point object we created with new GLatLng( ) we can create a marker object with the constructor for GMarker. Now that we have a marker object we can create an info window and attach it to the marker for display. o var html = Kyle Field<br>College Station, TX<br>Home of the Fightin Texas Aggies! This line specifies the html code that will be displayed in the info window. Any valid html can be used in your info windows. o GEvent.addListener Creates a listener for a particular event. In this instance, the marker will now respond to the click event. This means that the code specified in the function will run in respond to a user click on the marker. In this case it will display the html we specified. Finally, we add the new marker to our map with map.addOverlay(marker)
All of this combines to produce an image similar to what you see below.
10
Windows are often used in conjunction with GMarker to display attribute information about the marker. For instance, in a real estate application you might display a photo of a home along with other relevant details such as the sales price, square footage, number of bedrooms and baths. These are some of the most commonly used objects, but there are others that we will explore as well throughout this course.
GMap2
Controls
GLargeMapControl GSmallMapControl
InfoWindow
GMarker
2.1 GMap2
Although the old map class, GMap, will continue to exist in Version 2 of the API all the new features provided by Google will be attached to the new Version 2 class called GMap2. Like the original GMap class, the GMap2 class enables you to create map instances. You can create as many map instances as necessary for your application although most commonly this will only be a single instance. Maps are typically embedded within an HTML container called a <div> tag. The size of the map will default to the size specified in your <div> tag. Once youve generated an instance of GMap2 you can use the various methods and properties available on this object to manipulate other aspects of the map such as the controls included, the display of points of interest or polylines, and many other things. Everything in Google Maps flows through an instance of the GMap2 class.
12
GMap2
Figure 6: GMap2
GMap2 can also respond to a whole host of events. Events are simply an external stimulus to the map triggered by the user. Typical events might include the user dragging the map or clicking the map, an overlay marker being added to the map, or the map type changing from regular to aerial. You can write code that responds to any of these and other events. For instance, you might want to add a marker at the point where the user clicks the map, or perhaps you could display the latitude, longitude coordinates of the center of the map after a pan event has occurred. The constructor for GMap2 takes a container as its only required argument. In addition, several optional arguments can also be supplied including a list of map types to include with the map and the width and height of the map.
13
Notice in the code example above that we use the HTML document object model to find our <div> tag that has been given the name map. We can control the map types that are displayed in our map through the use of a second argument. By default, all map types (Satellite, Hybrid, and Normal) will be available. However, you can control the available map types through a list that is provided in the GMap2 constructor.
Notice in the code example above that we are restricting the map types that can be displayed to hybrid and satellite only, the Map button will be suppressed as seen in the figure below.
14
The final optional parameters control the width and height of the map. If these arguments are not included in the constructor, the map will default to the size specified in your container. These numeric parameters specify the pixel height and width of the map. Once youve created a map object you will have access to a number of methods that can be used to control the configuration, state, controls, overlays, info windows, and events that can be associated with a map. Well explore many of these methods throughout the course.
In this code example, -96.340264 represents the x or longitude value while 30.609682 represents the y or latitude value. GLatLng is normally used for two different yet important functions in Google Maps. The first reason for using GLatLng is to set the center point of your map. In the code example below youll see an example of using GLatLng to set the center point of your map. The setCenter( ) method on GMap2 takes a parameter that centers the map at a given longitude/latitude coordinate. setCenter( ) also takes a second parameter that sets the zoom level of your map. This will be a numeric value between 0 and 17. However, its the GLatLng object that is used to set the center of your map.
GLatLng is also used in conjunction with GMarker to create points of interest that are displayed as markers on your map. GMarker must have a coordinate defined by GLatLng to know where to place itself on the map. Notice how GMarker uses an instance of GLatLng in the code example below.
Lets examine the GMarker class in more detail to get a better understanding of how it works with GLatLng to create markers on your Google Map.
15
2.3 GMarker
The GMarker class is used to create icons showing points of interest on your Google Map. GMarker takes a single required parameter in its constructor. This parameter is an instance of GLatLng which we saw in the last code example. A second, optional parameter can be specified in the event that you need to display custom icons. By default, Google will display the icon shown here: However, if youd like to display custom icon markers youll need to obtain the custom icons and then use the GIcon class to specify how these icons should be displayed on the map. Well explore this subject in detail later in the book.
2.4 GPolyline
A polyline represents a vector line drawn on the map. GPolyline uses two or more instances of GLatLng to create a vector line between the two points. The vector lines generated by GPolyline can be created in various colors, weights, and transparency.
Lets examine the code above to get a better understanding of how to create polylines in Google Maps. The first parameter in the GPolyline constructor is an array of GPoint objects. For our purposes you can think of an array as a list. You must include at least two points in the array so that GPolyline can create the vector line between the points. Typically youll also include a number of points between the start and end point. The rest of the parameters are optional and include the ability to specify the line color, width of the line, and transparency of the line. The color is specified as a hex HTML color such as #ff0000 for blue. The width of the line is specified as a numeric value that controls the size of the line in pixels. Finally, you can control the transparency of the line by including a float value between 0 and 1 with a value of 1 indicating full transparency.
If you want to show polylines on your map you need to include the VML namespace and some CSS code in your XHTML document to make everything work properly in IE. The beginning of your XHTML document should look something like this for IE browsers:
16
2.6 GSize
The GSize class represents a two-dimensional size in pixels and is used when defining custom icons. Well take a closer look at this class later in the book when we examine custom icons.
2.7 GLatLngBounds
The GLatLngBounds class represents a box or envelope that contains the current geographic extent of the map. This extent is represented by minimum and maximum x (longitude) and y (latitude) values whose values change each time a pan or zoom action occurs. The map.getBounds( ) method returns a GLatLngBounds object. This object is frequently used to constrain the points of interest shown on a map when an application has access to large amounts of data that could potentially decrease the performance of the application if drawn all at once.
17
3.1 Panning
By default, every Google Map that you create in your application has the ability to pan. Panning simply gives you the ability to move the map in any direction by dragging in that direction. Google provides a number of ways to accomplish this task. Panning is most commonly performed simply by using the mouse to drag the map in a particular direction. In addition, Google provides a map control that can be used for panning the map.
Simply clicking one of the directional arrows will pan the map in the direction selected. Panning can also be controlled programmatically. As mentioned, panning is enabled automatically, but through the use of the map.disableDragging( ) method you can disable the ability to pan. Panning is not typically disabled in most applications, but there are times when you may have a need to turn off this functionality. For instance, if you are using an overview map in your application it probably makes sense to disable panning in the overview map while allowing panning to remain enabled in the main map. The Google Maps API can also be used to programmatically pan a map. You can use the panTo(GLatLng) method on GMap2 to programmatically pan the map to a latitude/longitude coordinate. The panBy(distance) method on GMap2 is used to programmatically pan the map by a specified distance. Finally, the panDirection(dx, dy ) method is to programmatically pan the map in a direction specified by dx and dy.
3.2 Zooming
The Google Maps API provides the ability to attach zoom controls to your application thereby giving your users control over the zoom level at which they view your map. The zoom controls are automatically added to the left side of your map. You have three choices available when coding your application. The default map control provided by maps.google.com is the GLargeMapControl object. GLargeMapControl shows all 18 levels of zoom on the slider along with a plus and minus button at the top and bottom of the slider. In addition to clicking the various levels on the control you can also drag the slider to the desired level. If you need to conserve real estate in your application, you can use the GSmallMapControl which discards the full slider in favor of the plus/minus zoom buttons. It also provides the pan buttons. Finally, the smallest possible control available is the GSmallZoomControl which displays only the plus/minus buttons without the zoom slider or pan controls.
18
To add any of the three map controls to your application, simply use the addControl( ) method on GMap2 along with the name of the control. For instance, this code example shows how to add GLargeMapControl to a map:
In the figure below you see an example of all three zoom controls.
GLargeMapControl
GSmallMapControl
GSmallZoomControl
As mentioned earlier in the book, you have control over which map types are displayed in your application through the mapTypes argument on the GMap2 constructor. The mapTypes argument is an array containing the map types youd like to display. An array in Copyright 2006: Geospatial Training & Consulting, LLC 19
Javascript is similar to a list. Notice that the creation of the array is specified with opening and closing brackets.
In the code example above, only the Hybrid and Satellite map types will be displayed. Several additional methods on GMap2 can be used manipulate map types. The map.setMapType(map_type) method is used to specify the currently visible map type. For instance, the following code example would set the current map type to Hybrid.
In addition to the G_HYBRID_MAP you may also specify values for Satellite (G_SATELLITE_MAP) and Map (G_NORMAL_MAP). The map.getCurrentMapType( ) method can be used to get the active map type while map.getMapTypes( ) returns an array containing all the map types available in the map. Now, the interesting thing with both these methods is that neither method returns a descriptive string for the map types. They both return objects and neither object contains helper functions that return the textual name of the map type(s). You will have to write a simple helper function to return this information in a human readable format. I am including just such a function in the code sample below.
This will add a collapsible overview map to the corner of the screen which displays the geographic extent of the main map. The geographic extent of the main map can be Copyright 2006: Geospatial Training & Consulting, LLC 20
controlled by dragging the rectangular extent in the overview map. See Figure 9 for an example of an application with an overview map included.
Figure 9: GOverviewMapControl
21
4.1 GMarker
The GMarker class is used to create icons showing points of interest on your Google Map. In the Google Maps API chapter we introduced GMarker, and we said that GMarker is used in conjunction with GLatLng to plot points of interest on a map. Lets provide a bit of a refresher on the GLatLng object before going into more detail on GMarker. Remember that GLatLng stores a longitude/latitude coordinate representing the geographic coordinates of a point of interest.
However, GLatLng does not provide the capability of plotting points on a map. This functionality is provided by the GMarker object which uses an instance of GLatLng to plot an icon at the coordinates specified in an instance of GLatLng. The constructor for GMarker takes a single required parameter containing an instance of GLatLng.
GMarker will display the default icon provided by Google Maps if you do not specify the second (optional) parameter in the GMarker constructor.
Once youve created an instance of GMarker you need to call the map.addOverlay( ) method to actually plot the icon on the map.
Icons can be removed from a map through the use of one of two methods provided on GMap2. The map.removeOverlay(marker) method can be used to remove a single instance of GMarker while map.clearOverlays( ) is used to remove all markers that have been added to a map. One thing that you will want to keep in mind is that although you can theoretically add an unlimited number of markers to your map you will find that performance starts to suffer when you attempt to add more than a couple hundred markers. There are a number hacks that you can use to deal with situations where you have hundreds or even thousands of Copyright 2006: Geospatial Training & Consulting, LLC 22
potential markers that can be placed on a map. We cover these in more detail in our Google Maps For Your Apps! virtual training course.
4.2 GIcon
In many instances you may not want to use the default marker icon provided by Google Maps. Perhaps you have your own set of icons that accurately represent the user data you are attempting to present in your application. In Figure 9 you will see an sample of an application that was created using custom GIcons. Fortunately, Google Maps provides the ability to customize the look and feel of the user data in your application. Through the use of the GIcon object your can attach any PNG file to create a custom marker. Theoretically your icon files can be of any size, but for practical purposes you should keep the size between 20-30 square pixels. For example, the default marker provided by Google Maps is 24x30. Anything larger makes the icons appear too large in relation to the map. It is beyond the scope of this book to go into great detail on how to create these icons, but well show you how to use them once you (or a graphic artist) create them. Many additional customizations of your icons are possible. Most custom icons also come with an additional icon that represents the shadow of an icon. Through the use of the icon.shadow( ) and icon.shadowSize( ) methods you can add these shadow files to your icons. At a minimum you should specify the icon, iconSize, shadow, and shadowSize properties as you see in the code example below.
In addition to these properties the icon.iconAnchor and icon.infoWindowAnchor properties can be used to specify anchor points. The icon.iconAnchor property is used to specify the exact pixel that will be attached to the instance of GLatLng. For example, if you want the upper left hand corner of an icon to be placed at the point of interest you specify a value of 0,0. When your application is going to use Info Windows you will also want to specify the icon.infoWindowAnchor property which will be used as the origination point of the Info Window. For browser compatibility reasons, specifying custom icons can become very complex and there are a number of other properties that can be set to account for the differences in browser types. For more details on these additional properties please see the Google Maps API Documentation for the printImage, mozPrintImage, printShadow, transparent, and imageMap properties on GIcon.
23
Notice in this case that we first defined a variable called html that we use to define the HTML markup that will be displayed in the Info Window. This isnt absolutely necessary,
24
but its perhaps a bit cleaner. The marker.openInfoWindowHtml method is then called and the html variable is passed in as the only parameter. Youll also notice that we used a new class that we havent discussed up to this point. The GEvent class is used to register event listeners. Well go into much greater detail on the GEvent class in a later chapter, but for now you can think of events as user initiated actions. In this case the event we are registering is a mouse click on the marker. When the user clicks the marker the Info Window will be displayed with the contents of the html variable displayed inside the window as you see in the figure below.
The map.openInfoWindowHtml( ) method also opens an Info Window containing an HTML string, but it differs slightly from marker.openInfoWindowHtml( ) in that you must pass in a point as the required first parameter along with an html string. Several optional parameters are also available including a pixelOffset parameter that controls where the Info Window originates. Basically this is the anchor of the Info Window. The map.openInfoWindowHtml( ) method is normally used to automatically display an Info Window without any sort of user initiated event like a mouse click. Take a look at the code Copyright 2006: Geospatial Training & Consulting, LLC 25
below to see an example of how to use map.openInfoWindowHtml( ) to automatically open an Info Window when the map is displayed.
Notice that we use a GLatLng instance (pt) already defined elsewhere in our code along with an offset to automatically display the html code in an Info Window when the map is created. Several other methods are also available through GMap2 and GMarker for displaying Info Windows. These include the openInfoWindow( ) method which is used to display an HTML DOM element and openInfoWindowXslt( ) which displays XML in an Info Window. One exciting new method introduced at Version 2 of the Google Maps API is the openInfoWindowTabsHtml( ) method. openInfoWindowTabsHtml( ) gives you the ability to include tabs in your Info Windows through the GInfoWindowTab class similar to what you see in Figure 12.
26
The following code was used to produce this new, tabbed version of the Info Window.
The openInfoWindowTabsHtml( ) method is supplied with an array (infoTabs) of GInfoWinowTab objects that specify the tab name and HTML that will be included on each tab. Should the need arise you can also suppress the display of Info Windows at the map level through the use of the map.disableInfoWindow( ) method. By default, the display of Info Windows is enabled so you shouldnt call this method unless you have a specific need to suppress their display.
Chapter 5: Events
For those of you new to programming, events can be described as actions that take place within an application. Typically these actions are invoked by the user and could include things such as clicking a point on the map, dragging the map in an effort to pan, and changing map types from map to satellite. These are all examples of user generated events. In any case, an event is a user or system generated action. You can write application code that responds to these events in some way. For example, when the user clicks the map, you could add a GMarker at the point where the user clicked. Another example could include displaying the latitude, longitude coordinates where the user clicked the map. The GMap2 and GMarker classes in the Google Maps API have a list of events that they can respond to and well examine these in more detail soon, but first lets look at the mechanics of how you register an event.
5.1 GEvent
All registration and handling of events occurs through the GEvent class which exposes a number of static methods for these purposes. A static method is simply a method that is called on the class itself rather than an instance of the class. In other words, you dont need to create an instance of GEvent to call its methods.
27
The addListener( ) method is used to register an event with the system. For instance, the following code can be used to register the click event on GMarker.
Three required parameters are included with the addListener( ) method. The first parameter is the source or object that will be responding to the event. The second parameter is the event that it will listen for. In this case were registering the click event with a marker object. Our final parameter is a function that will run in response to the event. In our example, the marker will display an Info Window when clicked. Removal of listeners can be accomplished through either the removeListener( ) method which removes an individual event or the clearListeners( ) method which will remove all currently active events. In cases where you need to trigger an event without user input you can call the trigger( ) method which can be used to trigger the function for a particular event. Lets now take a look at some of the more commonly used events associated with a couple Google Maps classes.
28
infowindowchanged o This event is fired when another map type is selected. addoverlay o Triggered after an overlay is added to the map removeoverlay o Triggered after an overlay is removed from the map clearoverlays o Triggered after all overlays are cleared mouseover o This event is fired when the user moves the mouse over the map from outside the map. mouseout o This event is fired when the user moves the mouse off the map. mousemove o This event is fired when the user moves the mouse inside the map. dragstart o This event is fired when the user starts dragging the map. drag o This event is repeatedly fired while the user drags the map. dragend o This event is fired when the user stops dragging the map.
29
o This event is fired for the DOM mouseup on the marker. Notice that the marker will not stop the mousedown DOM event, because it will not confuse the drag handler of the map. mouseover o This event is fired when the mouse enters the area of the marker icon. mouseout o This event is fired when the mouse leaves the area of the marker icon. remove o This event is fired when the marker is removed from the map.
Chapter 6: Geocoding
Plotting points of interest on a map is perhaps the most commonly used function in Google Maps. In Figure 13 you will see a visual example of an application that plots various address points on a map. To plot these points, you must have latitude, longitude coordinates for each point of interest or address. These coordinates are generated through a process known as geocoding which can be defined as an interpolation of the geographic location (latitude, longitude) of an address.
30
Lets examine a real world geocoding example. Assume for a moment that we have a point of interest located at 150 Main St. What we need to do is determine the geographic coordinates for this address. In the real world, Main Street could be a road segment with an address range of 100 to 200. Geocoding software is used to interpolate the relative location of 150 Main St. in relation to the existing Main Street segment that runs from 100 to 200 Main St. In this simple case, the geocoding software would interpolate 150 Main St. as being exactly half way between 100 and 200 Main St. The software will then assign a latitude, longitude coordinate to this address. After an address has been geocoded it can then be plotted as a map overlay in Google Maps similar to what you see in Figure 13 where multiple addresses have been geocoded and plotted on the map.
the map, and the second call gets the map, and plots the point coordinates obtained in the first call. In this example Im going to use ColdFusion as the language for accomplishing this hack, but you can use whatever language youre most comfortable with to accomplish the same thing. Lets take a look at how this is done. The first step in our hack is to pass an address to Google Maps and in return Google will generate a latitude, longitude coordinate for the address. However, using certain ColdFusion tags we can limit the return from Google to output only the result, not the map. Our first step is to use the ColdFusion <cfset> tag to declare a variable called addr which will hold an address that well pass to Google Maps. This address is hard coded in our example, but you could easily set it up to hold the contents of form controls that the user has dynamically entered. We then use the ColdFusion <cfhttp> tag to query Google Maps with the addr variable we declared and populated. Notice that we make an http call using the get method with a URL that points to Google Maps and contains the addr variable. We then use the ColdFusion <cfhttp.filecontent> tag to output the results of the query. Here is the full code example for passing the address to Google Maps.
If you run this code from a web page it will return a seemingly empty page, but through ViewSource in your web browser you can see the information that was returned. Part of the information contains the latitude and longitude of the address as you can see below:
After the initial return I can parse out the latitude, longitude coordinates and then make a second call to Google Maps to zoom to this address. This technique of dynamically obtaining address coordinates is something of a hack and since it requires two calls to Google Maps it could potentially have a negative affect on the performance of your application so you need to keep this in mind. Although the code examples youve just seen were written in ColdFusion, the same concept applies to whatever language youre using. Heres the ColdFusion code I used to parse the latitude and longitude from the initial call:
32
33
6.4 geocoder.us
If the Yahoo and Google solutions dont fit your needs there are a number of other free geocoding services available for non-commercial uses. One web service that I recommend is geocoder.us which offers a Web Service that allows you to purchase 20,000 lookups for $50. The data used by geocoder.us is provided by the US Census Bureau so you will be limited to address requests within the US. A RESTful web service request to geocoder.us could take the form:
34
You could then parse this data to plot the point on a Google Map.
Chapter 7: AJAX
At this point weve covered all the major bases related to the Google Maps API save for one all important topic AJAX. AJAX is what makes Google Maps such an attractive platform for building interactive web mapping applications. The traditional web mapping application model works something like this: Most user actions in the interface trigger an HTTP request back to a web server. The server does some processing retrieving data, crunching numbers, talking to various legacy systems and then returns an HTML page to the client. Its a model adapted from the Webs original use as a hypertext medium, but what makes the Web good for hypertext doesnt necessarily make it good for software applications (James, Jesse, 2005). The traditional approach to web application development makes sense from a technical point of view, but from a practical standpoint it leaves much to be desired in that it forces the user to wait while the server completes its processing and refreshes the display with a new page. AJAX changes this traditional model.
35
An AJAX application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary an AJAX engine between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true (James, Jesse, 2005) Instead of loading a webpage, at the start of the session, the browser loads an AJAX engine written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the users behalf. The AJAX engine allows the users interaction with the application to happen asynchronously independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something (James, Jesse, 2005).
7.2 XMLHttpRequest
Part of the AJAX equation is the XMLHttpRequest object which is the technical component that makes asynchronous server communication possible. Basically, the XMLHttpRequest object provides a method for client side JavaScript to make HTTP requests. Even though the object is called XMLHttpRequest, this object is not limited to being used just with XML. It can request or send any type of document. So whats the big deal you say? Well, here is a partial list of what can be accomplished through this object. Call server-side scripts without refreshing the page o This ability alone is a huge benefit for web application interactivity. o Typically you would call server-side scripts in HTML through forms. However, forms require a page reload which is not user friendly. o Calling server-side scripts through XMLHttpRequest allows you to call the script without refreshing the page. Load and read XML files o This is important for Google Maps applications because it allows you to read in points of interest stored in XML files and plot them to the map without refreshing the display. Make HEAD requests Does a URL exist?
Lets take a closer look at the XMLHttpRequest object for more details on how it works. The GXmlHttp object in the Google Maps API is used to create a cross-browser XmlHttpRequest so youll be using the same methods and properties.
36
New instances of the XMLHttpRequest class are created in slightly different ways depending upon the browser. For Safari and Mozilla browsers, the following call creates a new instance of XMLHttpRequest.
For IE, youll need to pass in the name of the object to the ActiveX constructor as you see below.
In Google Maps the GXmlHttp class exports a factory method called GXmlHttp.create( ) that creates a cross-browser XmlHttpRequest instace so you wont have to distinguish between the browser types when creating mapping applications built with Google. Object Methods All instances of the XMLHttpRequest object share a list of methods and properties. Table 1. Common XMLHttpRequest Object Methods
Method abort() getAllResponseHeaders() Description Stops the current request Returns complete set of headers (labels and values) as a string Returns the string value of a single header label Assigns destination URL, method, and other optional attributes of a pending request Transmits the request, optionally with postable string or DOM object data Assigns a label/value pair to the header to be sent with a request
setRequestHeader("label", "value")
The two most commonly used methods are open( ) and send( ). The open( ) method assigns a destination URL, method, or other optional attributes of a pending request. Two required parameters are the HTTP method you intend for the request (GET or POST) and the URL for the connection. You will want to use the GET method when specifying data retrieval requests and the POST method when sending data to the server. The send( ) method is used to transmit the request that you specified in the open( ) method.
37
The readyState property is used inside the onreadystatechange event handler to determine the status of the request. One of five states can be assigned to the readyState property. 0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete
The state we are interested in is a value of 4 which indicates that the request is complete and we now have a response from the server. In addition to checking the readyState property we also need to check the status or statusText properties to get confirmation that the transaction completed successfully before performing an operation on the results. A value of 200 in the status property or OK in the statusText property indicate success. Assuming that we have a readyState value of 4 and a status of 200 we can proceed with processing the response.
38
Data returned in the response can be accessed through the responseText or responseXML properties. The responseText property provides only a string representation of the data while the responseXML property gives us access to data that is returned in a well-formed XML DOM object that can then be parsed using node tree methods and properties.
7.3 GXmlHttp
Now that you understand the basic functionality provided by the XmlHttpRequest object well examine the GXmlHttp class provided by the Google Maps API. Really, the GXmlHttp object is just XmlHttpRequest in disguise, but with the added benefit of being cross browser compliant. All the methods and properties are the same as what youll find with XmlHttpRequest. The only real difference is how you create the instance as youll see below.
This line of code is used to create a cross browser compliant instance of XMLHttpRequest which can then access the methods and properties we detailed above. GXmlHttp is used in Google Maps applications primarily to read XML files containing points of interest that need to be plotted on a map. Lets take a look at a code example that will show you how to take advantage of this class. For this example, assume that you have an XML file containing points of interest defined by their latitude/longitude coordinates. This example contains only a very small amount of data, but in a real application you would probably include many other data attributes beyond just the coordinates. Assume that you have an XML file called data.xml containing the following data stored on your web server:
Now, lets create an instance of GXmlHttp, download and read the XML file, and then plot these coordinates on a map.
39
The first line of code simply creates a cross browser instance of XMLHttpRequest. We then use the open(Get, data.xml, true) method to assign the parameters that will be used in the request. Note that since we are requesting data, we use the GET method. In the event that you need to send data to the server youd use the POST method. The second parameter (data.xml) specifies the file that we are going to open, and the third parameter (true) flags this as an asynchronous request. In other words, processing of the code will continue once the send( ) method is called. A value of false in this parameter would hold up processing of the code until the request/response cycle is complete. In the third line of code we set the onreadystatechange event handler equal to a function that will be called when the readyState property changes. Were really only interested in a readyState of 4 which indicates that the request is complete and we now have a response from the server. Once the readyState code is set to a value of 4 we then do a second test to ensure that the request was successful, and this is indicated by a value of 200 in the request.status property. At this point we know that the request has been received and a valid response has been returned. In this case since weve requested an XML file (data.xml) well need to use the responseXML property to get an instance of the XML DOM object. Once we have this object we can use getElementsByTagName to return an array of markers which we then parse and plot on a Google Map similar to Figure 15.
40
41
The file is read asynchronously and the data is passed into the specified function as one long text string. GdownloadUrl uses an XmlHttpRequest object to execute the request.
42
writes a hyperlink to the URL into the log window. You can click, shift-click or ctrlclick the URL to open the link in this or another window or tab. writeHtml(html) o writes a fragment of html text into the log window.
This simple log window was created with the following line of code:
Chapter 9: Summary
By now you should have a good understanding of the basic functionality provided by the Google Maps API and youre probably ready to create your own Google Maps application Copyright 2006: Geospatial Training & Consulting, LLC 43
or Mashup as they are called. There are many examples of Google Maps Mashups on the web so you should spend some time getting familiar with the many fun and practical applications. Mick Peggs Google Maps Mania blog is perhaps the most comprehensive listing of mashups and other resources related to Google Maps. Spend some time at Mikes blog and youll quickly understand that you are only limited by your imagination. Reference: (James, Jesse., February 18, 2005) Ajax: A New Approach to Web Applications, from http://www.adaptivepath.com/publications/essays/archives/000385.php) Need More Information on Google Maps: GeoSpatial Training & Consulting, LLC also provides a full length, virtual training course entitled Google Maps For Your Apps!. This course is designed to enable you to take advantage of Google Maps for your website. You will learn how to create maps, add map controls for user interactions (zooming, and panning), programmatically alter the map extent, add points of interest to the map, add custom icons, geocode addresses on the fly, read addresses from a database or XML file, and display aerial photography. These topics are discussed in detail through a virtual training format that features audio and video lectures, demonstrations, code samples, and a bound hard-copy of our lectures so you can take notes during the lectures. About GeoSpatial Training & Consulting, LLC Geo-Spatial Training provides virtual and instructor led training courses designed to keep you on top of the rapidly evolving and increasingly technical nature of Geographic Information Systems (GIS). In today's world, implementing a GIS increasingly requires advanced skills that blend geospatial theories and concepts with advanced computer science skills. Our goal at Geo-Spatial Training is to integrate these sometimes disparate concepts into training materials that you can use to become a more effective GIS professional. Our affordable, self-paced virtual training courses are designed to fully engage the student in the learning process through the use of audio lectures, visual software demonstrations, exercises, Flash based lectures, and one-on-one interactions between the student and instructor. Contact Us: Website: http://www.geospatialtraining.com Email: [email protected] Phone Orders: 210-260-4992 Course Catalog: http://www.geospatialtraining.com/catalog.cfm Google Maps Virtual Training Course: http://www.geospatialtraining.com/catalog_googlemaps.cfm
44