不能让鼠标悬停多边形与未捕获的参考错误:谷歌没有定义

Can't get mouseover polygon to work with Uncaught Reference Error: google is not defined

本文关键字:错误 参考 谷歌 定义 悬停 鼠标 多边形 不能      更新时间:2023-09-26

新的编码和尝试建立和应用程序与谷歌地图功能利用多边形。看到这个问题问了几次,但似乎不能确定我的问题。地图初始化,多边形从定义的位置创建。我得到一个"未捕获的参考错误:谷歌没有定义"时,试图利用事件监听器,我用它来尝试改变多边形的样式时,它是悬停。

var map;
// Map Display options
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 9,
    center: {lat: 42.05, lng: -70.25},
    mapTypeId: google.maps.MapTypeId.SATELLITE
  });
  // Define the LatLng coordinates for the polygon.   
  var cc_peaked_hill =  [
    {lat: 42.049803, lng: -69.970551},
    {lat: 42.048273, lng: -69.978790},
    {lat: 42.043684, lng: -70.046082},
    {lat: 42.043684, lng: -70.058441},
    {lat: 42.056940, lng: -70.085907},
    {lat: 42.070194, lng: -70.118179},
    {lat: 42.079369, lng: -70.156631},
    {lat: 42.049803, lng: -69.970551}
  ];
  // Construct the polygon.
  var cc_peaked_hill_billsPollygon = new google.maps.Polygon({
    paths: cc_peaked_hill,
    strokeColor: '#F7F8FF',
    strokeOpacity: 0.8,
    strokeWeight: 1,
    fillColor: '#4562A8',
    fillOpacity: 0.45,
    editable: false
  });
  // Build the Polygons
  polygons = cc_peaked_hill_billsPollygon.setMap(map);
  //Listen for when the mouse hovers over the polygon.
  google.maps.event.addListener(polygons, 'mouseover', function (event) {
      // Within the event listener, "this" refers to the polygon which
      // received the event.
      this.setOptions({
          strokeColor: '#00ff00',
          fillColor: '#00ff00'
      });
  });
}

由于某些原因,我得到以下错误:

Uncaught Reference Error: google is not defined

如何解决这个问题?

问题是你首先这样做:

polygons = cc_peaked_hill_billsPollygon.setMap(map);

这实际上只是在多边形上设置map属性(实际上setMap不返回任何东西)。它没有给你一个多边形。在cc_peaked_hill_billsPollygon变量中已经有了。

所以当你尝试设置事件监听器时,就使用它。

事实上,你甚至不需要调用setMap。只需在创建多边形时分配map属性。

// Construct the polygon.
  var cc_peaked_hill_billsPollygon = new google.maps.Polygon({
    paths: cc_peaked_hill,
    strokeColor: '#F7F8FF',
    strokeOpacity: 0.8,
    strokeWeight: 1,
    fillColor: '#4562A8',
    fillOpacity: 0.45,
    editable: false,
    map: map   // Does the equivalent of `setMap(map)`
  });
  //Listen for when the mouse hovers over the polygon.
  google.maps.event.addListener(cc_peaked_hill_billsPollygon, 'mouseover', function (event) {
      // Within the event listener, "this" refers to the polygon which
      // received the event.
      this.setOptions({
          strokeColor: '#00ff00',
          fillColor: '#00ff00'
      });
  });

PS:还有一种更简洁的方式可以添加事件侦听器。只做:

  cc_peaked_hill_billsPollygon.addListener('mouseover', function (event) {
      // Within the event listener, "this" refers to the polygon which
      // received the event.
      this.setOptions({
          strokeColor: '#00ff00',
          fillColor: '#00ff00'
      });
  });