Google Maps API - Draggable Marker
Jump to navigation
Jump to search
Contents
About
NOTE: This page is a daughter page of: Google Maps API
This piece of code allows you drag around a single marker on the map. Notice there is a single listener, and functions to deal with when the dragging starts, ends and is underway.
Draggable Marker
draggable_marker.js
/*
* @fileoverview Sets up map with a single marker which can be
* dragged around the map and report it's lat, lng.
*/
/*
* Changes 'marker-state' div to show text.
* @param: str String to write.
*/
function updateMarkerStateTxt(str) {
document.getElementById('marker-state').innerHTML = str;
}
/*
* Update the position of our 'marker-position' marker.
* @param: latLng Maps LatLng object.
*/
function updateMarkerPositionTxt(latLng) {
document.getElementById('marker-position').innerHTML =
String(latLng.lat()) + ',' + String(latLng.lng());
}
/*
* Sets up Google map into 'map-canvas' div and adds the
* the starting marker and a drag listener.
*/
function initialize() {
var latLng = new google.maps.LatLng(37.2434151284, -122.031447712);
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Draggable Marker',
map: map,
draggable: true
});
// Update marker position txt.
updateMarkerPositionTxt(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerStateTxt('Dragging start...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStateTxt('Dragging...');
updateMarkerPositionTxt(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStateTxt('Drag ended');
});
}
// Onload handler to fire off the app:
google.maps.event.addDomListener(window, 'load', initialize);
draggable_marker.html
<html>
<head>
<title>Draggable Marker</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
#map-canvas {
width: 500px;
height: 400px;
float: left;
}
#info-panel {
float: left;
margin-left: 10px;
}
</style>
</head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="draggable_marker.js"></script>
<body>
<div id="map-canvas"></div>
<div id="info-panel">
<b>Marker state:</b>
<div id="marker-state"><i>Click and drag the marker.</i></div><br>
<b>Current position:</b>
<div id="marker-position"></div>
</div>
</body>
</html>
<!-- Acknowledgments: Gebrehiywet Fissaha for his providing the code
on which this was based (minus the cool geocode stuff he added). See:
http://stackoverflow.com/questions/5280067/draggable-google-map-markers -->
See Also
- Google Maps API - more examples.