我想画一张50个州的叶绿体地图。每个状态都有一个潜在的信息窗口。
问题是,当用户单击某个状态时,会打开一个信息窗口。挑战是在单击另一个状态时将其关闭。问题出在下面的代码中,我甚至无法打开第一个infowindow。
我得到的错误是:Uncaught ReferenceError: can't access lexical declaration 'infowindow' before initialization
"use strict";
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
center: {
lat: 28,
lng: -85
}
}); // Load GeoJSON.
map.data.loadGeoJson(
//"https://storage.googleapis.com/mapsdevsite/json/google.json"
"maps/US_ALL_STATES.geojson"
); // Color each letter gray. Change the color when the isColorful property
// is set to true.
map.data.setStyle(feature => {
let color = "blue";
if (feature.getProperty("isColorful")) {
color = feature.getProperty("color");
}
return (
/** @type {!google.maps.Data.StyleOptions} */
({
fillColor: color,
strokeColor: color,
strokeWeight: 2
})
);
}); // When the user clicks, set 'isColorful', changing the color of the letters.
map.data.addListener("click", event => {
if (infowindow) infowindow.close();
var content = "State: " + event.feature.getProperty("NAME") + "\r"
content = content + "Click <a href='county.html?state="+event.feature.getProperty("STATEFP")+"'>here</a> to Zoom in"
const infowindow = new google.maps.infowindow({
content: content
});
event.feature.setProperty("fillColor", "pink");
infowindow.setPosition(event.latLng);
infowindow.open(map);
console.log(event.feature);
}); // When the user hovers, tempt them to click by outlining the letters.
// Call revertStyle() to remove all overrides. This will use the style rules
// defined in the function passed to setStyle()
map.data.addListener("mouseover", event => {
map.data.revertStyle();
map.data.overrideStyle(event.feature, {
strokeWeight: 8,
fillColor: "green",
strokeColor: "pink"
});
});
map.data.addListener("mouseout", event => {
map.data.revertStyle();
});
}如何更新它以使其成为“一次一个信息窗口”的场景?谢谢。
发布于 2020-09-10 11:44:05
改为在持久外部作用域中创建变量:
let infowindow;
map.data.addListener("click", event => {
if (infowindow) infowindow.close();
var content = "State: " + event.feature.getProperty("NAME") + "\r"
content = content + "Click <a href='county.html?state="+event.feature.getProperty("STATEFP")+"'>here</a> to Zoom in"
infowindow = new google.maps.infowindow({
content: content
});
// etchttps://stackoverflow.com/questions/63822506
复制相似问题