seanbrodie seanbrodie - 20 days ago 5
jQuery Question

Drag and Drop Google Maps Marker

I have made a drag-and-drop feature so that users can drag an icon from the sidebar and when they drop the icon, a marker is placed.

The below implementation seemed like the best (only) way to achieve it, but issues are occurring when the network is slow, presumably because the lat/lng from the mouseover event is (very) inaccurate.

Can anyone offer an alternative way I could do this? Perhaps placing the marker immediately and then using the built-in maps drag-n-drop ?

function placeMarker(lat, lng) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
draggable: true,
map: map
});
return marker;
}

$(".icon").draggable({helper: 'clone',

start: function(e, ui) {
map.setOptions({draggable: false});
$("#map").css('cursor', 'crosshair');
},

stop: function(e,ui) {
map.setOptions({draggable: true});
$("#map").css('cursor', 'default');

google.maps.event.addListenerOnce(map, "mouseover", function(event) {
var lat = event.latLng.lat(),
lng = event.latLng.lng(),
id = ui.helper.context.id;

pointA = id === "pointA" && pointA === true
? pointA.setMap(null) : placeMarker(lat, lng);

pointB = id === "pointB" && pointB === true
? pointB.setMap(null) : placeMarker(lat, lng);
});
}
});

Answer

The issue is resolved when using the mousemove event instead of mouseover.

I think this is the event I should have been using all along. The low latency obviously interferes with the initial mouseover event not firing as the pin is dropped.

Hope this can help others.