In the previous article we have created draggable Google map Marker, Now lets create a Google map with a draggable marker and when you drag the marker lets generate the Latitude, Longitude and postal address of that location where you place the marker.      

Generate draggable marker on Google Map

Insert the following div where you want to display the map. And lets create input fields to display address, Latitude and Longitude.  

<div id="myMap"></div>
<input id="address" type="text" style="width:600px;"/><br/>
<input type="text" id="latitude" placeholder="Latitude"/>
<input type="text" id="longitude" placeholder="Longitude"/>

CSS Code

<style>
#myMap {
   height: 350px;
   width: 680px;
}
</style>

JavaScript Code

The follow code will generate a graggable marker on the Google map and when you drag the marker it will display address, Latitude and Longitude in the input fields.

.  
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=[YOUR KEY]">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript"> 
var map;
var marker;
var myLatlng = new google.maps.LatLng(20.268455824834792,85.84099235520011);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize(){
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(document.getElementById("myMap"), mapOptions);

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

geocoder.geocode({'latLng': myLatlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});

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

geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});

}
google.maps.event.addDomListener(window, 'load', initialize);
</script>


Output




Download File

Total Downloads: 5832
Top