javascript 如何在 google.maps.event.addListener 中使用它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34053826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:11:41  来源:igfitidea点击:

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

javascriptgoogle-maps

提问by Hubvill

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

以下示例有效,但是当我尝试传递参数并this在函数中使用时不起作用。

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_objwith the following code. It does not work and the error Uncaught TypeError: Cannot read property 'place_id' of undefinedis displayed.

当我尝试service_obj使用以下代码传递参数时。它不起作用并Uncaught TypeError: Cannot read property 'place_id' of undefined显示错误。

    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 thisis 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.

我相信this不再是指实例markers[i]了。我对此很陌生,因此对术语错误感到抱歉。如果有人能帮助我或引导我朝着正确的方向前进,那就太棒了。

回答by geocodezip

When you pass an argument to the function in the third argument, the function is executed immediately (which is why thisisn'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:

当您将参数传递给第三个参数中的函数时,该函数将立即执行(这就是为什么this不是您所期望的)并且返回值用作事件处理函数。您可以使用匿名函数来允许您调用带参数的函数:

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>