gpt4 book ai didi

javascript - 无法让鼠标悬停多边形与谷歌地图一起使用 - 未捕获的引用错误 : google is not defined

转载 作者:行者123 更新时间:2023-12-03 06:15:55 25 4
gpt4 key购买 nike

编码新手,尝试利用多边形构建和应用谷歌地图功能。已经多次看到这个问题,但似乎无法确定我的问题。 map 初始化并从定义的位置创建多边形。当尝试利用我用来尝试更改悬停在其上的多边形的样式的事件监听器时,我收到“ Uncaught ReferenceError :google 未定义”。

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'
});
});

关于javascript - 无法让鼠标悬停多边形与谷歌地图一起使用 - 未捕获的引用错误 : google is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com