Index
[]Ajax Massive Storage System [See AMASS]autocomplete fields
Index
[]browsers
Index
[]
Index
[]data validation [See validation]data, receivingDirect Web Remoting [See DWR]
Index
[]Extensible Markup Language [See XML]Extensible Stylesheet Language and Transformation [See XSLT]
Index
[]Firefox
Index
[]
Index
[]HTMLHTTPHTTP response
Index
[]Internet Explorer
Hack 29. Use the Google Maps API Request Object
The Google Maps API comes with its own request object for making HTTP requests from JavaScript code.
This hack initially displays a Google Map based on a user's preferences. These include the latitude/longitude at which the map should be centered, and the zoom level or magnification of the map when it is first displayed on the web page. An application typically obtains user-specific properties by reading a cookie, a small piece of data saved on a user's hard drive, or having a user sign in. This hack skips this opening step in order to focus on the gist of the hack's technology: obtaining user preferences from a server component to control a Google Map display.
| discusses reading cookies in an Ajax application.
|
|
Personal Googling
This hack displays a 500-by-300-pixel U.S. map on a web page, which also shows the user's preferred coordinates for centering the map and preferred zoom level (a two-digit number from the highest zoom level of 1 to around 18). A zoom level of 18, for instance, shows the continents and oceans, whereas a zoom level of 1 displays a town's streets.
As mentioned previously, when the user requests this web page, the application can either obtain the user's username from a previously generated cookie, or ask the user to sign in and fetch the preferences from a database. However, we are not going to show that step (even though it is important in a real-world application) because we surmise that the reader is more interested in the API's Ajax-related objects and the map-display code.
Here is the HTML for the hack:
View Map
Your Google Map
Your specifications
Latitude:
Longitude:
Zoom level:
This code imports the hacks4_1a.js JavaScript code file, which contains the custom code for our application.
| Google Maps requires a separate developer key for every URL directory containing Google Mapsrelated web pages. For example, I have a developer key that covers every web page in the http://www.parkerriver.com/ajaxhacks/ directory. It is extremely easy to generate a developer key at http://www.google.com/apis/maps/signup.html. |
|
The map itself is displayed within a div tag that has an id of map. When the browser loads the page, the code first checks the compatibility of the browser using a Google global function, GBrowserIsCompatible( ). If this function returns TRue, the application calls a function named googleAjax( ). The window.onload event handler and googleAjax( ) appear inside the hacks4_1a.js file. googleAjax( ) queries a server for the user's specific preferences of a user by passing along the username ("bwperry," in this case). The application then uses the properties fetched by googleAjax( ) to display and zoom in on a map. Here is the code from hacks4_1a.js:
var map = null;window.onload = function( ){ if(GBrowserIsCompatible( )){ googleAjax('http://www.parkerriver.com/s/gmap?user=bwperry'); } else { alert('Your browser is not compatible with Google Maps!');}};function createMap(lat,lng,zoomLevel){ map = new GMap(document.getElementById("map")); GEvent.addListener(map, 'click', function(overlay, point) { document.forms[0]._longitude.value=point.x; document.forms[0]._latitude.value=point.y; map.addOverlay(new GMarker(point)); }); map.addControl(new GLargeMapControl( )); map.addControl(new GMapTypeControl( )); if(lat != null && lat.length != 0 && lng != null && lng. length != 0 && zoomLevel != null && zoomLevel.length != 0){ map.centerAndZoom(new GPoint(lng, lat), zoomLevel); } else { //center on roughly middle of USA map.centerAndZoom(new GPoint(-97.20703, 40.580584), 14); }}function googleAjax(url){ var request = GXmlHttp.create( ); request.open("GET", url, true); request.onreadystatechange = function( ) { if (request.readyState == 4) { if (request.status == 200) { var resp = request.responseXML; var rootNode = resp.documentElement; var zoom = rootNode.getElementsByTagName("zoomLevel")[0]; var latLng = rootNode. getElementsByTagName("centerCoords")[0]; var coordArr = latLng.firstChild.nodeValue.split(" "); var zoomLevel=zoom.firstChild.nodeValue; createMap(coordArr[0],coordArr[1],zoomLevel); alert(coordArr[0]+" "+coordArr[1]+" "+zoomLevel); document.forms[0]._latitude.value=coordArr[0]; document.forms[0]._longitude.value=coordArr[1]; document.forms[0]._zoomLevel.value=zoomLevel; } else { alert( "The application had a problem communicating with "+ "the server. Please try again."); }//inner if }//outer if }//end function request.send(null);}
It will probably help you visualize the application's purpose if I show you the map inside a browser window, before digging into the code. The page loads the map and displays the user's preferred coordinates and zoom level in text fields beneath it. shows the page displayed in a browser.
Figure 4-1. Google Map centered on MA with zoom level 10
Map Objects
Take a gander at the googleAjax( ) function and its creation of an object that makes HTTP requests:
function googleAjax(url){ var request = GXmlHttp.create( ); request.open("GET", url, true); request.onreadystatechange = function( ) { if (request.readyState == 4) { if (request.status == 200) { var resp = request.responseXML; var rootNode = resp.documentElement; var zoom = rootNode.getElementsByTagName("zoomLevel")[0]; var latLng = rootNode. getElementsByTagName("centerCoords")[0]; var coordArr = latLng.firstChild.nodeValue.split(" "); var zoomLevel=zoom.firstChild.nodeValue; createMap(coordArr[0],coordArr[1],zoomLevel); document.forms[0]._latitude.value=coordArr[0]; document.forms[0]._longitude.value=coordArr[1]; document.forms[0]._zoomLevel.value=zoomLevel;
} else { alert( "The application had a problem communicating with "+ "the server. Please try again."); }//inner if }//outer if }//end function request.send(null);}
Remember all the code that created a request object in onreadystatechange event handler, just as you would with a request object that you created with your own code.
| The ). |
|
This code fetches an XML document from the server that contains the user's map preferences:
var resp = request.responseXML;
The returned XML data might look like this:
42.057450220246 -71.6418457031210
Remember that you are getting this XML information from the server. The data is specific to each user and can be stored in a database. This information represents the user's preferred latitude and longitude for the center point of the map, as well as the preferred zoom level.