【问题标题】:Get current coordinates on dragging react leaflet在拖动反应传单时获取当前坐标
【发布时间】:2020-12-20 17:48:15
【问题描述】:

我是反应传单的新手。我创建了我的地图并成功添加了多边形。但是,当我在地图上拖动或缩放时,如何获取整个屏幕的当前坐标?我使用openstreetmap的地图。非常感谢您的支持。 我的代码:

class App extends Component {
  componentDidMount()
  {
    //console.log(polygonData);
    navigator.geolocation.getCurrentPosition(function(position) { //mdn geolocation
      console.log(position)
    });
  }

  onEachContry = (feature, layer) =>{
    const contryName = feature.properties.NAME_1;
    //console.log(feature.properties.NAME_1);
    layer.bindPopup(contryName);

    if(contryName == "An Giang")
    {
      layer.options.fillColor = "yellow";
    }

    layer.on({
      /*mouseover: (event) => {
        console.log(event);
      }*/
    }
    )
  }

  countryStyle = {
    fillColor: "red",
    fillOpacity: 0.5,
    color: "black",
    weight: 2
  
  }

  render() {
    return (
        <MapContainer center={[10.7743, 106.6669]} zoom={6} >
          <TileLayer
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <GeoJSON
          style = {this.countryStyle}
          data={polygonData.features}
          onEachFeature={this.onEachContry}
          
          />
        </MapContainer>
    );
    }
}

/*<Marker position={[51.505, -0.09]}>
          <Popup>
            A pretty CSS3 popup. <br /> Easily customizable.
          </Popup>
        </Marker>
        */

export default App;

【问题讨论】:

    标签: javascript reactjs leaflet react-leaflet


    【解决方案1】:

    将函数组件用作MapContainer's 子级。那里使用useMapEvents 挂钩监听dragend 事件。 e.target.getBounds 提供您需要的一切,如getSouth()getWest()getEast() 等方法

     function MyComponent() {
            const map = useMapEvents({
              dragend: (e) => {
                console.log("mapCenter", e.target.getCenter());
                console.log("map bounds", e.target.getBounds());
              }
            });
            return null;
          }
    

    然后

    <MapContainer
         ...><MyComponent/>
    </MapContainer>
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 2018-09-16
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      相关资源
      最近更新 更多