使用多边形进行编码并尝试使用谷歌地图功能构建和应用的新手。已经看过几次这个问题,但似乎无法确定我的问题。地图初始化并从定义的位置创建多边形。我收到了一个"未被捕获的引用错误: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
我该如何解决这个问题?
答案 0 :(得分:1)
问题是你首先要这样做:
polygons = cc_peaked_hill_billsPollygon.setMap(map);
这实际上只是在多边形上设置map
属性(实际上setMap
不会返回任何内容)。它没有给你一个多边形。您已经拥有cc_peaked_hill_billsPollygon
变量。
因此,当您尝试设置事件侦听器时,只需使用它。
事实上,您甚至不需要致电setMap
。只需在创建多边形时指定地图属性。
// 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'
});
});