Trying to add a right-click delete marker function, to working left-click add marker code

google-maps-api-3

Solution

You want the 'rightclick' event listener on the marker, not the map. Put it in the addMarker function:

function addMarker(location) {
        var marker = new google.maps.Marker({
        position: location,
        map: map
    });
    google.maps.event.addListener(marker, 'rightclick', function(event) {
        marker.setMap(null);
    });

    markers.push(marker);
}

Note: this will remove the marker from the map, but won't remove it from the markers array.

Remove the one on the map, delete these lines:

google.maps.event.addListener(map, 'rightclick', function(event) {
            marker.setMap(null);
});

Problem

Hello and thanks in advance. The following modified sample google code creates markers upon left mouse clicks, and adds those markers to an array. That part works fine. I have tried to add a second event handler that deletes a marker if there is a right click on it. I've tried a lot of variations without success. It is my understanding that the use of marker.setMap(null) would set the associated array element to null, and remove the marker from the display. Thanks again! ``` <!DOCTYPE html> <html> <head> <title>Marker Test</title> <style> html, body { height: 100%; margin: 0; padding: 0; } #map-canvas, #map_canvas { height: 100%; } #map-canvas, #map_canvas { height: 650px; } </style> <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> <script> var map; var markers = []; function initialize() { var NY = new google.maps.LatLng(40.739112,-73.785848); var mapOptions = { zoom: 16, center: NY, mapTypeId: google.maps.MapTypeId.TERRAIN } map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions); google.maps.event.addListener(map, 'click', function(event) { addMarker(event.latLng); }); google.maps.event.addListener(map, 'rightclick', function(event) { marker.setMap(null); }); } function addMarker(location) { var marker = new google.maps.Marker({ position: location, map: map }); markers.push(marker); } google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <div id="map-canvas"></div> </body> </html> ```

Original source