Right Click on marker - Google Maps V3

SeanCAtkinson picture SeanCAtkinson · Dec 17, 2013 · Viewed 14.2k times · Source

I've been trying to get a right click working on my markers but so far it seems that the event just isn't fired. As a workaround I'm currently detecting a right click on the map and then finding the nearest marker and triggering the right click method - obviously thats not great.

According to the docs, markers do have a right click event so I'm not sure what I'm doing wrong. https://developers.google.com/maps/documentation/javascript/reference#Marker

google.maps.event.addListener(marker, 'rightclick', handleRightClick)

doesn't work but

google.maps.event.addListener(map, 'rightclick', handleRightClick)

works fine. As does:

google.maps.event.addListener(marker, 'click', handleRightClick)

I'm also using a custom marker plugin called markerWithLabel - http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.9/docs/reference.html - I thought I'd cracked it when I discovered that this didn't add an event listener for the right click but even when I added one in myself, still no luck. I added this at line 257:

google.maps.event.addDomListener(this.eventDiv_, "rightclick", function(e) {
    if (me.marker_.getClickable()) {
        google.maps.event.trigger(me.marker_, "rightclick", e);
        cAbortEvent(e);
    }
})

Has anyone had similar issues or found better workarounds?

Thanks in advance.

Answer

ffflabs picture ffflabs · Dec 17, 2013

Let's say you had your map object and it's called globalmap (you made as a new google.maps.Map)

This will add a marker on maps' center:

var newmarker=new google.maps.Marker({map:globalmap, position: globalmap.getCenter()});

this will listen to right click on the marker;

google.maps.event.addListener(newmarker,  'rightclick',  function(mouseEvent) { alert('Right click triggered'); });

EDIT: Regarding the MarkerWithLabel plugin, I can see that it's extending from google.maps.OverlayView, and passes in a marker in the marker_ property of the object. This means you could still have your way doing (copying from the example):

 var marker1 = new MarkerWithLabel({
   position: homeLatLng,
   draggable: true,
   raiseOnDrag: true,
   map: map,
   labelContent: "$425K",
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75}
 });

and then add the right click behaviour as

google.maps.event.addListener(marker1.marker_,  'rightclick',  function(mouseEvent) { alert('Right click triggered'); });