首页 > 解决方案 > 我可以制作可点击的国家标签,但是当我点击其他任何地方时会出错

问题描述

当用户单击国家/地区标签时,我正在尝试创建一个弹出窗口。我的代码实现了这一点,但如果用户不小心点击了其他任何地方,我会收到错误“TypeError:无法读取未定义的属性'properties'”。任何帮助,将不胜感激。谢谢。

export default class App extends React.PureComponent {
constructor(props) {
    super(props);
    this.state = {
        lng: -32.87393,
        lat: 43.6439,
        zoom: 3,
        mxZoom: 7,
         
    };
    this.mapContainer = React.createRef();
}

componentDidMount() {
    const { lng, lat, zoom , mxZoom} = this.state;
    const map = new mapboxgl.Map({
    container: this.mapContainer.current,
    style: 'mapbox://styles/chriswade112358/ckpipp5el0jky18qwzep8ppyl',
    center: [lng, lat],
    zoom: zoom,
    minZoom: zoom,
    maxZoom: mxZoom,
    });

    map.on('style.load', function() {

        map.on('click', function(e) {
              const features = map.queryRenderedFeatures(e.point, { layers: ['country-label'] });
              new mapboxgl.Popup()
                  .setLngLat(e.lngLat)
                  .setHTML('you clicked here: <br/>' + features[0].properties.name)
                  .addTo(map);
        });
      });
}

标签: mapboxmapbox-gl-jsmapbox-gl

解决方案


推荐阅读