簡體   English   中英

從Google地圖的addListener()函數返回值

[英]Return a value from Google maps addListener () function

我正在使用Google Maps Javscript API:

google.maps.event.addListener(searchBox, 'places_changed', function() {
      var places = searchBox.getPlaces();

      for (var i = 0, marker; marker = markers[i]; i++) {
        marker.setMap(null);
      }

      // For each place, get the icon, place name, and location.
      markers = [];
      var bounds = new google.maps.LatLngBounds();
        var image = {
          url: places[0].icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };

        // Create a marker for the closest result
        marker = new google.maps.Marker({
          map: map,
          icon: image,
          draggable : true,
          title: places[0].name,
          position: places[0].geometry.location
        });

        $('#inputLocalisation').val(places[0].geometry.location);
        markers.push(marker);


        bounds.extend(places[0].geometry.location);

        map.fitBounds(bounds);

    });

用戶搜索位置時觸發此處理程序。 它在最接近的結果上創建一個標記。

我想返回標記,以便以后在其他處理程序中使用它:

google.maps.event.addListener(marker,'dragend',function() {
        $('#inputLocalisation').val(marker.getPosition());
    });

拖動標記時觸發此事件,但是我需要標記對象。 如何訪問先前創建的標記?

因此,您應該在創建我假設的標記的同時添加該事件監聽器?

在事件偵聽器函數中,可以使用關鍵字this引用它。

marker = new google.maps.Marker({
      map: map,
      icon: image,
      draggable : true,
      title: places[0].name,
      position: places[0].geometry.location
});

google.maps.event.addListener(marker,'dragend',function() {
    $('#inputLocalisation').val(this.getPosition());
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM