• Draggable Marker for Google Maps

    Posted on June 6, 2012 by in Javascript, Other Programming

    Google Maps offers vast range of functionality, one of the them is allowing markers to be dragged and dropped. An option to make markers draggable was given to us with v2.46. Setting 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.

        marker = new google.maps.Marker({
    	position: latlng,
    	map: map,
    	draggable: true
        });
    

    In the example below, we are going retrieve the coordinates of the marker when the marker is dropped and then reverse geocode the coordinates to get the address. If you are unware, geocoding is a process of getting latitude and longitude from given address and reverse geocoding is getting an address from given coordinates.

    To get coordinates when the marker is dropped, we add an event listener to the marker as below

    google.maps.event.addListener(marker, 'dragend', function () {
       geocodePosition(marker.getPosition());
    });
    
    

    marker.getPosition() gets the position of the marker, we pass it to geocoding function to get the address from the position as below.

        var msg = "";
        geocoder.geocode({
    	latLng: pos
    	}, function (responses) {
    	    if (responses && responses.length > 0) {
    	       msg = 'Location : ' + responses[0].formatted_address + '<br/> ';
    	       msg = msg + 'Latitude : ' + pos.lat() + '<br/> ';
    	       msg = msg + 'Longitude : ' + pos.lng() + '<br/> ';
    	       attachMessage(marker, msg);
    	    } else {
    	       msg = 'Cannot determine address at this location.';
    	       attachMessage(marker, msg);
    	    }
       });	
    
       //Display the address when clicked on the marker 
       function attachMessage(marker, msg) {
    	var infowindow = new google.maps.InfoWindow({
    	            content: msg,
    	            size: new google.maps.Size(120, 150)
    	});
    	
    	google.maps.event.clearListeners(marker, 'click');
    	google.maps.event.addListener(marker, 'click', function () {
    	   infowindow.open(map, marker);
    	});
       }
    

    Complete Code

    <!DOCTYPE html>
    <html lang="en-US">
     <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    	<title>::Maps ::</title>
    	<script type="text/javascript" 
    
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&key=YOUR_KEY_HERE"></script>
    	<script type="text/javascript">
    	    var map;
    	    var marker;
    	    var geocoder = new google.maps.Geocoder();
    
    	    function geocodePosition(pos) {
                var msg = "";
    	        geocoder.geocode({
    	            latLng: pos
    	        }, function (responses) {
    	            if (responses && responses.length > 0) {
    	               msg = 'Location : ' + responses[0].formatted_address + '<br/> ';
    	               msg = msg + 'Latitude : ' + pos.lat() + '<br/> ';
    	               msg = msg + 'Longitude : ' + pos.lng() + '<br/> ';
    	               attachMessage(marker, msg);
    	            } else {
    	               msg = 'Cannot determine address at this location.';
    	               attachMessage(marker, msg);
    	            }
    	        });
    
    	    }
    
    	    $(document).ready(function () {
    	        var latlng = new google.maps.LatLng(40.748039, -73.985753);
    	        var myOptions = {
    	            zoom: 13,
    	            center: latlng,
    	            mapTypeId: google.maps.MapTypeId.ROADMAP
    	        };
    	        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    	        marker = new google.maps.Marker({
    	            position: latlng,
    	            map: map,
    	            draggable: true
    	        });
    
    
    	        google.maps.event.addListener(marker, 'dragend', function () {
    	            geocodePosition(marker.getPosition());
    	        });
    
    	    });
    
    	    function attachMessage(marker, msg) {
    	        var infowindow = new google.maps.InfoWindow({
    	            content: msg,
    	            size: new google.maps.Size(120, 150)
    	        });
    	        google.maps.event.clearListeners(marker, 'click');
    	        google.maps.event.addListener(marker, 'click', function () {
    	            infowindow.open(map, marker);
    	        });
    	    }
    
    	</script>
    	<style type="text/css">
    		html,body { height: 100%; margin: 0px; padding: 0px; }
    		#map_canvas {
    			width:1000px;
    			height:800px;
    		}		
    	</style>
    </head>
    <body >
    <div id="map_canvas">
    
    </div>
    <!--main-->
    <div id="map_cord"></div>
    </body>	
    </html>
    

    Please click on the link below to see working example

    For downloading complete set google maps api examples, click the link below

    NOTE : Please change the key if you using the code from the demo.

    Be Sociable, Share!

    Written by

    Vanamali Juvvadi is a Web enthusiast and loves all things design and technology. Founded qnownow with a group of friends to share anything/everything they know/find on the internet.

    View all articles by

    Email : [email protected]

    Leave a Reply