【问题标题】:Leaflet markers not always applying传单标记并不总是适用
【发布时间】:2017-07-19 12:07:55
【问题描述】:

所以我正在使用leaflet-react,我需要添加一些圆圈标记。

现在这段代码可以工作......有时。在地图上单击应该添加一个圆形标记,但有时它不是。看似随机,它不会添加可见标记。如果我更改缩放级别,有时标记会变得可见,但并非总是如此。所有代码每次都会运行,所以并不是 addMarker() 没有被调用,最后一个标记的删除(通过清除标记层)总是运行。

谢谢,埃德。

【问题讨论】:

    标签: node.js reactjs leaflet jsx react-leaflet


    【解决方案1】:

    您似乎没有使用react-leaflet 包。我建议尝试一下。以下是一些示例代码,说明如何在点击事件中向地图添加标记:

    const React = window.React;
    const { Map, TileLayer, Marker, Popup } = window.ReactLeaflet;
    
    class SimpleExample extends React.Component {
      constructor() {
        super();
        this.state = {
          markers: [[51.505, -0.09]]
        };
      }
    
      addMarker = (e) => {
        const {markers} = this.state
        markers.push(e.latlng)
        this.setState({markers})
      }
    
      render() {
        return (
          <Map 
            center={[51.505, -0.09]} 
            onClick={this.addMarker}
            zoom={13} 
            >
            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
            />
            {this.state.markers.map((position, idx) => 
              <Marker key={`marker-${idx}`} position={position}>
              <Popup>
                <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
              </Popup>
            </Marker>
            )}
          </Map>
        );
      }
    }
    
    window.ReactDOM.render(<SimpleExample />, 
    document.getElementById('container'));
    

    这是一个展示实现的 jsfiddle:https://jsfiddle.net/q2v7t59h/413/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      相关资源
      最近更新 更多