Hack 11. Where Did the User Click?

Find the location of a click on a map and display it on your web page.

Google Maps makes it easy to put an interactive map on your web page. At http://www.naffis.com/maphacks/latandlon.html you can click on a map and have the corresponding latitude and longitude displayed in a Google Maps info box.

In Figure 2-4 you can see the location of the Washington Monument.

Figure 2-4. The Washington Monument at 38.88941 N, 77.03517 W

This site solves the common problem of figuring out the coordinates of a location from a map view and is an example of the sort of quick hack that Google Maps has made possible. This page illustrates one way to get the latitude and longitude from a click on a map and display results in an info box. So how can you do it? At http://mappinghacks.com/projects/gmaps/click.html there is a simplified example of updating a form from the coordinates of a click on a map.

This is the Hello World map with three changes. An HTML form has been added to receive the latitude and longitude from the click event:


Latitude:   Longitude:  

In the script, the latitude and longitude used to set the initial map location with centerAndZoom( ) now comes from these form elements. This code defaults to starting at 38.4094 N, 122.8290 W. Change those values to change the initial focus of the map. The important change to the script is the addition of a GEvent.addListener. This code and the above form can be pasted into the body of your HTML page. Change the developer's key and you can capture clicks on a map:


This code adds a listener to the GMap object named map. If you click on the map, the code in the event handler will be run. The code is given both an overlay (a marker) and a point. If you click on a marker, the overlay will be set. If you don't click on a marker, then a GPoint object is given to the code.

These two lines are standard JavaScript. They ask the document for the value of the elements click_lat and click_long. The only elements with those names are the form elements. point.x and point.y are the longitude and latitude of the GPoint object that marks where you clicked.

	document.getElementById('click_lat').value = point.y;
	document.getElementById('click_long').value = point.x;

The end result is shown in Figure 2-5.

Figure 2-5. The click is back

The next steps are to add markers to the map from the click, populate a map from an external data source, and update an external data source based on the map.

You Are Here: Introducing Google Maps

Introducing the Google Maps API

Mashing Up Google Maps

On the Road with Google Maps

Google Maps in Words and Pictures

API Tips and Tricks

Extreme Google Maps Hacks

Google Maps Hacks
Google Maps Hacks: Tips & Tools for Geographic Searching and Remixing
ISBN: 0596101619
EAN: 2147483647
Year: N/A
Pages: 131

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net