首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >infowindow google地图错误:无法访问词法声明'infowindow‘

infowindow google地图错误:无法访问词法声明'infowindow‘
EN

Stack Overflow用户
提问于 2020-09-10 11:42:30
回答 1查看 104关注 0票数 0

我想画一张50个州的叶绿体地图。每个状态都有一个潜在的信息窗口。

问题是,当用户单击某个状态时,会打开一个信息窗口。挑战是在单击另一个状态时将其关闭。问题出在下面的代码中,我甚至无法打开第一个infowindow。

我得到的错误是:Uncaught ReferenceError: can't access lexical declaration 'infowindow' before initialization

代码语言:javascript
复制
"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();
  });






}

如何更新它以使其成为“一次一个信息窗口”的场景?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-10 11:44:05

改为在持久外部作用域中创建变量:

代码语言:javascript
复制
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
  });
  // etc
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63822506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档