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

2024-05-16

以下示例有效,但是当我尝试传递参数并使用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;
            }

          });
        }

当我尝试传递参数时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;
            }

          });
        }

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


当您在第三个参数中将参数传递给函数时,该函数会立即执行(这就是为什么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);
      }
    });
}

概念证明小提琴 http://jsfiddle.net/geocodezip/s018Lbu2/6/

代码片段:

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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 google.maps.event.addListener 中使用它 的相关文章

随机推荐

  • jQuery 可以操作插入的元素吗?

    我是 jQuery 的新手 我认为 jQuery 可以操作由代码添加的元素是合理的 但我发现现在还不能 function addVideo click function publisher append div div
  • 使用 PHP 修剪字符串开头的任何零

    用户将在字段中填写与其帐户相关的数字 不幸的是 一些用户会在号码开头添加零来组成六位数字 例如 000123 001234 而其他用户则不会 例如 123 1234 我想 修剪 前面带有零前缀的用户的数字 因此如果用户输入 000123 它
  • 使用 ZBarSDK 时 iPhone 相机失去自动对焦功能

    我正在开发一个应用程序 用户可以选择是否要扫描条形码或拍摄某物的照片 为了拍照 我正在使用UIImagePickerController照常 为了扫描条形码 我使用 ZbarSDK 1 2ZBarReaderViewController 拍
  • React中如何触发同级组件的函数?

    I am new to front end world and could not figure out how to trigger a function from a sibling component Lets say I have
  • UILabel 中的文本未垂直居中

    我使用以下代码创建了一个标签 func setupValueLabel valueLabel numberOfLines 1 valueLabel font UIFont name Avenir Black size 50 valueLab
  • 指示电子邮件的类型

    我有以下自动化程序 它将电子邮件发送给我自己 并添加了特定的链接 import win32com client as win32 import easygui import tkinter as to from tkinter import
  • 将 N 种类型的参数包折叠成 N-1 对

    我正在尝试折叠参数包N不同类型分为std tuple of N 1 std pairs与各自的类型 例如表达式 ResolveToTupleOfPairs
  • 导入模块 WebAdministration 不会从脚本加载,但会从命令行加载

    我正在进行一个使用的项目PowerShell编写构建脚本 该构建利用了WebAdministration模块来管理本地 IIS 实例 当我运行构建脚本时 尝试导入时会引发以下错误WebAdministration 错误 06 29 2016
  • 简单 Haskell Monad - 随机数

    我正在尝试扩展代码这个帖子 https stackoverflow com questions 3944170 haskell and state 接受的答案 允许我能够基于以种子作为参数的函数 randomGen 调用 randomGen
  • 重写 getPreferredSize() 会破坏 LSP

    我总是在这个压倒一切的网站上看到建议getPreferredSize 而不是使用setPreferredSize 例如 如前面的线程所示 对于固定大小的组件 使用重写 getPreferredSize 而不是使用 setPreferredS
  • Java 卡布局。多张卡中的一个组件

    一个组件 例如JLabel 在多张卡中使用CardLayout 目前看来该组件仅出现在它添加到的最后一张卡上 如果有办法做到这一点 我应该吗 这是不好的做法吗 或者有其他选择吗 你是对的 它只出现在 添加到的最后一张卡 中 但这与CardL
  • cameraOverlayView 防止使用 allowedEditing 进行编辑

    在我的应用程序中 使用以下行在拍摄照片后对其进行编辑 移动和缩放 效果很好 imagePicker setAllowsEditing YES 但如果我还使用cameraOverlayView 则编辑模式将不再起作用 屏幕出现 但平移和捏合手
  • 数据框 - 平均列

    我在 pandas 中有以下数据框 Column 1 Column 2 Column3 Column 4 2 2 2 4 1 2 2 3 我正在创建一个数据框 其中包含第 1 列和第 2 列 第 3 列和第 4 列等的平均值 ColumnA
  • 如何在 Jenkins 声明式管道中设置 PATH

    在 Jenkins 脚本化管道中 您可以像这样设置 PATH 环境变量 node git url https github com jglick simple maven project with tests git withEnv PAT
  • 迭代函数可以调用自身吗?

    当观看下面的 MIT 6 001 课程视频时 讲师在 28 00 将此算法标记为迭代 但是 在 30 27 他说这个算法和实际的 递归 算法都是递归的 该函数正在使用基本情况调用自身 那么这次迭代情况如何 private int itera
  • 如何使用 UNIX shell 计算字母在文本文件中出现的次数?

    我有几个文本文件 我想计算每个字母在每个文件中出现的次数 具体来说 我想使用 UNIX shell 来执行此操作 形式为 cat file 做东西 有没有办法让 wc 命令来执行此操作 grep char o filename wc l
  • Android 性能:SharedPreferences 的成本

    当我的应用程序启动时 我使用分片首选项中的值填充容器类 这个想法是处理 SharedPreferences 和 PreferenceManager 一次 因为我猜它们很重 这是一个示例 SharedPreferences prefs Pre
  • dplyr 中的标准评估:全局环境中的函数出现“无法找到函数”错误

    我试图在 dplyr 中对全局环境中的函数使用标准评估 但出现 无法找到函数 错误 这是一些代码 create data frame df lt data frame x rnorm 10 y rnorm 10 define arbitra
  • 如何使用 Python boto3 获取 redshift 中的列名称

    我想使用 python boto3 获取 redshift 中的列名称 创建Redshift集群 将数据插入其中 配置的机密管理器 配置 SageMaker 笔记本 打开Jupyter Notebook写入以下代码 import boto3
  • 如何在 google.maps.event.addListener 中使用它

    以下示例有效 但是当我尝试传递参数并使用this在该功能不起作用 Working google maps event addListener markers i click showInfoWindow function showInfoW