Web Services Creating Draggable Markers with the Google Maps API

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.

The most efficient way to use Google’s geocoding service is to request the coordinates only once, and then store those coordinates within a local database. Because the geocoded location is in all likelihood stationary (as opposed to a moving object such as a bus or taxi), storing the coordinates locally will prevent your application from needlessly having to repeatedly ask the Google server for these coordinates. While the service is surprisingly accurate for the vast majority of addresses, occasionally you’ll find the provided coordinates to be ever so slightly inaccurate, but enough so that the discrepancy could potentially cause confusion among your users. For instance, Figure 1 depicts the provided coordinates (as represented by the marker) of The Ohio State University’s football stadium. As you can see, the marker has been placed on the road next to, rather than directly on top of, the stadium.

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:

<title>Draggable Markers</title>
<script src=”http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;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);
var marker = new GMarker(new GLatLng(40.004003, -83.019363), {draggable: true});
<body onload=”initialize()” onunload=”GUnload()”>
<div id=”map_canvas” style=”width: 500px; height: 300px”></div>

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

Creating a Listener

Creating a draggable marker solves only part of the puzzle; you also need to listen for marker movement and record the new location when the user releases the marker. To do so, you’ll need to use the addListener() method to define a dragend listener, which will execute when the user has released the marker. In total, four listener types are also supported, including click, drag, dragend, and dragstart. Here’s an example that defines a dragend listener:

GEvent.addListener(marker, “dragend”, function() {

With the dragend listener added, you’ll be able to retrieve the updated coordinates as depicted in Figure 3:

Figure 3:
Retrieving the Marker’s New Coordinates

Sending the Data to a PHP Script

With the new coordinates in hand, you’ll need to send them back to the database. The easiest way to do this is by using Ajax. To help coordinate the Ajax communication process, you’ll take advantage of jQuery’s $.post function to send the coordinates (you’ll also need to add the jQuery library to the HTML file):

GEvent.addListener(marker, “dragend”, function() {
var point = marker.getLatLng();
var lat = point.lat();
var lng = point.lng();
{latitude: lat, longitude: lng},

The $.post function calls the update.php script, sending along the coordinates. The PHP script is able to retrieve these coordinates by referring to them within the $_POST array. The update.php script is presented next. To stay on topic, I’ll just write these coordinates to a text file rather than save them to an actual database. However, as you can see, it wouldn’t take much to perform the latter task:


$fh = fopen(“coordinates.txt”, “w”);

fwrite($fh, “Lat: “.$_POST[’latitude’].”rn”);
fwrite($fh, “Lat: “.$_POST[’longitude’].”rn”);

echo “Coordinates updated!”;


The PHP script concludes by returning a message to the caller, which will subsequently be written to a DIV titled #result.

Map-oriented Web Applications Made Easy

Using the powerful Google Maps API in conjunction with other technologies, such as jQuery and PHP, creating fascinating and flexible map-oriented Web applications is trivial. I’d love to hear from you if you’re doing anything in this regard!

About the Author

Jason Gilmore is founder of EasyPHPWebsites.com, and author of the popular book, “Easy PHP Websites with the Zend Framework”. Formerly Apress’ open source editor, Jason fostered the development of more than 60 books, along the way helping to transform their open source line into one of the industry’s most respected publishing programs. Over the years he’s authored several other books, including the best-selling Beginning PHP and MySQL: From Novice to Professional (currently in its third edition), Beginning PHP and PostgreSQL: From Novice to Professional, and Beginning PHP and Oracle: From Novice to Professional.

Jason is a cofounder and speaker chair of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer’s conference, and was a member of the 2008 MySQL Conference speaker selection board.

Jason has published more than 100 tutorials and articles within prominent publications such as Developer.com, Linux Magazine, and TechTarget.

Latest Posts

Related Stories