Reputation: 28545
Im using this excellent jquery plugin for working with google maps:
Im using the "Map Marker Drag" example.
Once I have dragged a marker how can I get the new/current coordinates of the Marker?
Thanks
Upvotes: 1
Views: 10412
Reputation: 2218
Try something like this using javascript and google maps API:
// update element with latest lat and lon
function updateMarkerPosition(latLng) {
document.getElementById('ll').value = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function initialize() {
// look for any lat lon in url, to set map center
if ($.urlParam('ll')) {
var llparam = $.urlParam('ll').split(', ');
var lat = parseFloat(llparam[0]);
var lon = parseFloat(llparam[1]);
var latLng = new google.maps.LatLng(lat, lon);
} else {
var latLng = new google.maps.LatLng(47.65130629733119, -122.34994607543945);
}
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 12,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
}
Upvotes: 2
Reputation: 18572
I wrote a project that does just this, it uses version 2 of Google Maps API. Here is the snippet of code to make a draggable marker that will show lat/long after you drag it to a new place on map:
function createMarker(latlng, number, html) {
var marker = new GMarker(latlng, {draggable: true});
marker.value = number;
var myHtml = html;
var center = marker.getLatLng();
map.openInfoWindowHtml(latlng, "<font color=black>" + myHtml + "<br>" + center.toString() + "</font>");
GEvent.addListener(marker, "dragstart", function() {
map.closeInfoWindow();
});
GEvent.addListener(marker, "dragend", function() {
var center = marker.getLatLng();
marker.openInfoWindowHtml("<font color=black>" + myHtml + "<br>" + center.toString() + "</font>");
});
return marker;
}
Upvotes: 3
Reputation: 2720
You can access the markers .latLng() to get coordinates of any marker.
Upvotes: 0