Hubvill
Hubvill

Reputation: 504

How to use this in google.maps.event.addListener

The following example works, but when I try to pass a parameter and use this in the function does not work.

Working:

google.maps.event.addListener(markers[i], 'click', showInfoWindow);

      function showInfoWindow() {

          var service_marker = this;
          service.getDetails({placeId: service_marker.placeResult.place_id},
          function(place, status) {
            if (status !== google.maps.places.PlacesServiceStatus.OK) {
              return;
            }

          });
        }

When I try to pass a parameter service_obj with the following code. It does not work and the error Uncaught TypeError: Cannot read property 'place_id' of undefined is displayed.

    google.maps.event.addListener(markers[i], 'click', showInfoWindow(service_obj));

      function showInfoWindow(service_obj) {

          var service_marker = this;
          service.getDetails({placeId: service_marker.placeResult.place_id}, //error here
          function(place, status) {
            if (status !== google.maps.places.PlacesServiceStatus.OK) {
              return;
            }

          });
        }

I believe this is not refering to the instance markers[i] anymore. I am fairly new to this so sorry about the terminology mistakes. If anyone could help me out or lead me in the right direction that would be fantastic.

Upvotes: 3

Views: 32602

Answers (1)

geocodezip
geocodezip

Reputation: 161334

When you pass an argument to the function in the third argument, the function is executed immediately (which is why this isn't what you expect) and the return value is used as the event handler function. You can use an anonymous function to allow you to call a function with parameters:

google.maps.event.addListener(marker, 'click', function (evt) { // the click event function is called with the "event" as an argument
    showInfoWindow(evt, this, service, map, infowindow);
});

function showInfoWindow(evt, service_marker, service, map, infowindow) {
  service.getDetails({
      placeId: service_marker.placeResult.place_id
    }, 
    function (place, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        infowindow.setContent(place.name);
        infowindow.open(map, service_marker);
      } else {
        infowindow.setContent("error: "+status);
        infowindow.open(map,service_marker);
      }
    });
}

proof of concept fiddle

code snippet:

var markers = [];
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);

  service.nearbySearch({
    location: map.getCenter(),
    radius: 50000,
    keyword: "restaurant"
  }, function(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      var bounds = new google.maps.LatLngBounds();
      for (var i = 0; i < results.length; i++) {
        var marker = createMarker(results[i], service, map, infowindow);
        bounds.extend(marker.getPosition());
      }
      map.fitBounds(bounds);
    }
  });
}

function createMarker(place, service, map, infowindow) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });
  marker.placeResult = place;

  google.maps.event.addListener(marker, 'click', function(evt) { // the click event function is called with the "event" as an argument
    showInfoWindow(evt, this, service, map, infowindow);
  });
  return marker;
}

function showInfoWindow(evt, service_marker, service, map, infowindow) {
  service.getDetails({
      placeId: service_marker.placeResult.place_id
    }, //error here
    function(place, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        infowindow.setContent(place.name);
        infowindow.open(map, service_marker);
      } else {
        infowindow.setContent("error: " + status);
        infowindow.open(map, service_marker);
      }

    });
}

google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>

Upvotes: 3

Related Questions