Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send additional parameters in a google maps event function

I had this, works fine:

google.maps.event.addListener(marker, 'rightclick', function(event) {
    infowindow.close();
    marker.setMap(null);
    marker.solucionado = true;
    cant_markers--;
    cant_solucionados++;
});

But I want to do this:

google.maps.event.addListener(marker, 'rightclick', deleteMarker);

function deleteMarker(marker) {
    infowindow.close();
    marker.setMap(null);
    marker.solucionado = true;
    cant_markers--;
    cant_solucionados++;
});

marker it's currently out of the scope, there is a way to send the marker object as a parameter?

like image 861
goncy Avatar asked Feb 10 '23 09:02

goncy


1 Answers

marker isn't out of scope, marker is the scope where the handler will be executed.

The scope of a handler added via addListener is always the object where the listener has been added to(first argument of addListener, it's marker in your code)

Simply use this to access the marker inside the handler:

function initialize() {

  var map = new google.maps.Map(document.getElementById("map-canvas"), {
      center: new google.maps.LatLng(0, 0),
      zoom: 1
    }),
    marker = new google.maps.Marker({
      map: map,
      position: map.getCenter()
    });
  google.maps.event.addListener(marker, 'rightclick', deleteMarker);

}

function deleteMarker() {
  this.setMap(null);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map-canvas"></div>

However, when you wan't to pass additional arguments to the handler it's possible too, use deleteMarker.call(or deleteMarker.apply)

Example:

function initialize() {

  var map = new google.maps.Map(document.getElementById("map-canvas"), {
      center: new google.maps.LatLng(1, 2),
      zoom: 1
    }),
    marker = new google.maps.Marker({
      map: map,
      position: map.getCenter()
    }),
    var1 = "it ",
    var2 = "work's";
  google.maps.event.addListener(marker, 'rightclick',
    function(e) {
      deleteMarker.call(this, //the scope of the handler...the marker
        e, //the original event
        var1, //additonal argument
        var2 //another argument
      );
    }
  );

}

function deleteMarker(event, v1, v2) {
  this.setMap(null);
  alert(v1 + v2 + '@' + event.latLng)
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map-canvas"></div>
like image 81
Dr.Molle Avatar answered Feb 11 '23 23:02

Dr.Molle