In this blog post, you will learn how to create google maps draggable marker using Google Maps Javascript API v3, and when you drag the marker position then get coordinates (latitude and longitude) of that location where you place the marker.
- Keep reading on Google Maps Location Sharing Not Updating, How to show multiple locations on Google Maps
How to make a marker draggable?
To allow users to drag a marker to a different location on the map, set the draggable attribute to true in the marker options.
var myLatlng = new google.maps.LatLng(-25.363882,131.044922); var mapOptions = { zoom: 4, center: myLatlng } var map = new google.maps.Map(document.getElementById("map"), mapOptions); // Place a draggable marker on the map var marker = new google.maps.Marker({ position: myLatlng, map: map, draggable:true, title:"Drag me!" });
Get the coordinates on marker drag event in the Google Maps
The following example will demonstrate to you how to get Lat/Lng from google marker when the user moves the marker position on google maps. Find the below source code:-
index.html
<!DOCTYPE html> <html> <head> <title>Google Maps Drag Marker Get Coordinates</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js" type="text/javascript"></script> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR-KEY"></script> <script type="text/javascript"> function initialize() { // Creating map object var map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 12, center: new google.maps.LatLng(28.47399, 77.026489), mapTypeId: google.maps.MapTypeId.ROADMAP }); // creates a draggable marker to the given coords var vMarker = new google.maps.Marker({ position: new google.maps.LatLng(28.47399, 77.026489), draggable: true }); // adds a listener to the marker // gets the coords when drag event ends // then updates the input with the new coords google.maps.event.addListener(vMarker, 'dragend', function (evt) { $("#txtLat").val(evt.latLng.lat().toFixed(6)); $("#txtLng").val(evt.latLng.lng().toFixed(6)); map.panTo(evt.latLng); }); // centers the map on markers coords map.setCenter(vMarker.position); // adds the marker on the map vMarker.setMap(map); } </script> </head> <body onload="initialize();"> <h2> Google Maps Draggable Marker Get Coordinates </h2> <label for="latitude"> Latitude: </label> <input id="txtLat" type="text" style="color:red" value="28.47399" /> <label for="longitude"> Longitude: </label> <input id="txtLng" type="text" style="color:red" value="77.026489" /><br /> <br /> <br /> <div id="map_canvas" style="width: auto; height: 400px;"> </div> </body> </html>
Conclusion
I hope you liked this article on google maps draggable marker get coordinates. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Leave a Reply