Get the coordinates on marker drag event in the Google Maps (Latitude, longitude)
Description:
Let’s create a Google map with a draggable marker and when you drag the marker lets generate the Latitude and Longitude of that location where you place the marker.
Html Part:
Insert the bellow html code where you want to display the map. And let’s create input fields to display Latitude and Longitude.
Latitude: <input id="lat" name="lat" val="40.713956" /> <br/>
Longitude: <input id="long" name="long" val="74.006653" /> <br/>
<div id="map_canvas" 500px; height: 250px;"></div>
JavaScript Code
The bellow code will generate a graggable marker on the Google map and when you drag the marker it will display Latitude and Longitude in the input fields.
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(40.713956, -74.006653);
var myOpti>
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("lat").value = event.latLng.lat();
document.getElementById("long").value = event.latLng.lng();
infoWindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, "load", initialize());
Don’t forgot to include the google map api before this code or add bellow line
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
Leave a Reply