I set a marker on click on the map. I use MarkerWithLabel.
I use draggable marker.
If I drag a marker it works fine. But if I drag a label it works with click event on the map.
How can I use labels and can drag a label without click event?
In my example - when I drag a marker JS creates new marker.
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng)
});
function addMarker(latLng) {
var marker = new MarkerWithLabel({
position: latLng,
map: map,
draggable: true,
labelContent: "example",
labelAnchor: new google.maps.Point(30, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
google.maps.event.addListener(marker, 'dragend', function(e) {
alert(2);
})
}
JSFIDDLE
You may try something like this (Example) unless you have other solution:
var map, dragended;
// ...
google.maps.event.addListener(map, 'click', function(event) {
if(!dragended) {
addMarker(event.latLng);
}
dragended = false;
});
google.maps.event.addListener(marker, 'dragend', function(e) {
var target = e.target || e.srcElement;
if(target && target.className == 'labels') {
dragended = true;
}
alert(2);
});
The click
event is fired when you start dragging (Check this). It's a dirty hack using a global variable but it works if there is no other solution.
Their example page shows what you're looking for in action.
function your_function(e) { //Callback function
console.log("Drag: " + e.latLng.toString());
}
//Create map using the #map_canvas element
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 12,
center: new google.maps.LatLng(49.47805, -123.84716),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//Create new MarkerWithLabel (enhanced version of a Marker)
var marker = new MarkerWithLabel({
position: new google.maps.LatLng(49.47805, -123.84716),
draggable: true,
raiseOnDrag: true,
map: map, //Attach to map
labelContent: "example",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels" // the CSS class for the label
});
//Finally add a listener to the marker to call your_function when "drag" event has occurred.
google.maps.event.addListener(marker, "drag", your_function );
That's all the magic you need, I guess.
Edit: Upon further investigation of your Fiddle, I noted a the event bubble leak from the marker label to map. Since there's no known way to stop the event propagation from bubbling into a different type, you can set a variable to keep track of this scenario and clear it once it's triggered. Related SO question. You can optionally just set an actual local variable in the same scope as map, either way will work.
JSFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With