javascript - 谷歌地图包含位置抛出未捕获的类型错误

标签 javascript google-maps-api-3

我有我认为非常简单的代码。我画了一个多边形,一个标记,然后如果我硬编码的点在多边形内则发出警报。然而,当我运行它时,我在控制台中收到“Uncaught TypeError: Cannot call method 'lng' of undefined”错误。

我的代码如下:

   function initialize() {


        var mapOptions = {
          center: new google.maps.LatLng(38.990842,-76.93625),
          zoom: 17,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);

      var box = [new google.maps.LatLng(38.9913160,-76.937079),
      new google.maps.LatLng(38.991333,-76.936119),
      new google.maps.LatLng(38.990287, -76.936108),
      new google.maps.LatLng(38.990278,-76.937057),
      new google.maps.LatLng(38.990495,-76.937052),
      new google.maps.LatLng(38.990499,-76.936424),
      new google.maps.LatLng(38.991091,-76.93643),
      new google.maps.LatLng(38.991104,-76.937079)
      ];

        var mPoint = [new google.maps.LatLng(38.991300,-76.936165)];
  var marker = new google.maps.Marker({
    map: map, 
    position: new google.maps.LatLng(38.991300,-76.936165),
    //position: new google.maps.LatLng(mPoint),
    draggable: true
  });

        var AVpoly = new google.maps.Polygon({path:box,
  strokeColor:"#0000FF",
  strokeOpacity:0.8,
  strokeWeight:2,
  fillColor:"#0000FF",
  fillOpacity:0.4});

      AVpoly.setMap(map);
marker.setMap(map);
if(google.maps.geometry.poly.containsLocation(google.maps.LatLng(38.990842,-76.93625), box) == true) {
 alert("yes");
}

      }

我看不出这有什么问题,也不明白为什么不触发警报。如果我的几何图形有误,我什至将其更改为 false....

最佳答案

Box 不是 google.maps.Polygon;它是 google.maps.LatLng 对象的数组。改用 AVpoly( the documentation 指定第二个参数是 Polygon )。

那行不通,您还缺少 google.maps.LatLng 构造函数的"new"。这确实有效(使用返回 google.maps.LatLng 的 marker.getPosition 方法):

var marker = new google.maps.Marker({
    map: map, 
    position: new google.maps.LatLng(38.991300,-76.936165),
    draggable: true
  });

var AVpoly = new google.maps.Polygon({path:box,
    map: map, 
  strokeColor:"#0000FF",
  strokeOpacity:0.8,
  strokeWeight:2,
  fillColor:"#0000FF",
  fillOpacity:0.4});

  if(google.maps.geometry.poly.containsLocation(marker.getPosition(), AVpoly) == true) {
    alert("yes");
 }

Working (if annoying) example

关于javascript - 谷歌地图包含位置抛出未捕获的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13757388/

相关文章:

javascript - 获取包含点击事件的元素

javascript - 为什么 Visual Studio intellisense 不显示 XMLHttpRequest 对象方法?

javascript - 用前导零填充输入

javascript - 使用 CSS 将水平菜单更改为移动设备的响应式菜单

javascript - 是否可以将动画 svg 分配给 google Maps JavaScript API 中的标记符号?

javascript - 谷歌地图可以询问位置,但没有将 map 居中

javascript - 从加载的 KML 向标记添加点击事件

javascript - 为什么会抛出错误?

javascript - 谷歌地图自定义标记图像不起作用

javascript - 谷歌地图 API 3 + WMS