Google Maps API - Draggable Marker

From NoskeWiki
Jump to navigation Jump to search
Marker you can drag.


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


 * @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( + ',' + 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.

  // Add dragging event listeners.
  google.maps.event.addListener(marker, 'dragstart', function() {
      updateMarkerStateTxt('Dragging start...');

  google.maps.event.addListener(marker, 'drag', function() {

  google.maps.event.addListener(marker, 'dragend', function() {
      updateMarkerStateTxt('Drag ended');

// Onload handler to fire off the app:
google.maps.event.addDomListener(window, 'load', initialize);


  <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;

  <script type="text/javascript" src="">
  <script type="text/javascript" src="draggable_marker.js"></script>
  <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>

<!-- Acknowledgments: Gebrehiywet Fissaha for his providing the code
on which this was based (minus the cool geocode stuff he added). See: -->

See Also