最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use this in google.maps.event.addListener - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Dec 2, 2015 at 21:55 HubvillHubvill 5041 gold badge7 silver badges16 bronze badges 3
  • possible duplicate of Google Map addDomListener function parameter – geocodezip Commented Dec 2, 2015 at 22:16
  • 1 possible duplicate of How to use a Google map event listener to pass a variable and submit a form – geocodezip Commented Dec 2, 2015 at 22:16
  • possible duplicate of what does “google.maps.event.addDomListener(window, 'load', initialize);” mean? – geocodezip Commented Dec 2, 2015 at 22:17
Add a ment  | 

1 Answer 1

Reset to default 3

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./maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>

发布评论

评论列表(0)

  1. 暂无评论