Creating Draggable Markers with the Google Maps API
Although online mapping solutions have been around for years, it wasn't until the June 2005 release of the Google Maps API that truly powerful mapping applications began to proliferate across the Web. During the past two years this occasional series has introduced quite a few of the Google Maps API's features, including the highly anticipated June 2006 addition of a native geocoding solution.
Native geocoding capabilities make it possible for developers to provide a mailing address and receive the corresponding latitudinal and longitudinal coordinates in return. The geocoding feature was documented in a previously published tutorial, so if you're not familiar with it consider taking a moment to read up on this powerful feature before continuing.
Figure 1: Miscalculating the Ohio State University Football Stadium Location
In order to provide your users with the most accurate representation possible, those coordinates need to be tweaked so the marker will appear directly atop the stadium. But without having another source for geocoding the stadium address, how can you make the correction?
The easiest way is by making the marker draggable and configuring a listener to geocode the dragged marker's new location. This will enable you to associate the updated coordinates with the stadium, saving them to the local database.
Creating a Draggable Marker
Defining a marker as draggable using the API is surprisingly easy; all you need to do is pass along the option {draggable: true} when creating the marker. Here's an example:
var marker = new GMarker(point, {draggable: true})
Here is a larger example that incorporates the draggable marker:
<html>
<head>
<title>Draggable Markers</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=KEY" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(40.004003, -83.019363), 15);
map.setUIToDefault();
var marker = new GMarker(new GLatLng(40.004003, -83.019363), {draggable: true});
map.addOverlay(marker);
}
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
</body>
</html>
Executing this example produces a map in which the user can move the marker to the proper location, as depicted in Figure 2.
Figure 2: Moving a Draggable Marker to the Proper Location
Page 1 of 2
