Google Maps containsLocations会抛出未捕获的TypeError

时间:2012-12-07 05:23:32

标签: 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");
}

      }

我看不出有什么问题,也不知道为什么不发射警报。我甚至在我的几何形状出错的情况下将它改为假......

1 个答案:

答案 0 :(得分:2)

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