反应小叶获得当前经纬度的onClick

问题描述 投票:0回答:2

我是真的高兴,如果有人可以帮助我...我已经安装了反应小叶在我的反应项目和地图组件加载成功,我需要获得当前经纬度信息,并显示在弹出当我在地图上点击但我不知道该怎么:(

请......请......帮帮我......

这是我的代码

import React from 'react'
import { Map as LeafletMap, TileLayer, Marker, Popup } from 'react-leaflet';

class Mapp extends React.Component {
    componentDidMount() {

    }

    render() {
        return (
            <LeafletMap
                center={[35.755229,51.304470]}
                zoom={16}
                maxZoom={20}
                attributionControl={true}
                zoomControl={true}
                doubleClickZoom={true}
                scrollWheelZoom={true}
                dragging={true}
                animate={true}
                easeLinearity={0.35}
            >
                <TileLayer
                    url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
                />
                <Marker position={[35.755229,51.304470]}
                draggable={true}
                >
                    <Popup >
                        Popup for any custom information.
                    </Popup>

                </Marker>
            </LeafletMap>
        );
    }
}

export default Mapp;
reactjs leaflet react-leaflet
2个回答
3
投票

这是一次地图点击如何在弹出的显示器制造商位置上的例子:

class MapExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPos: null
    };
    this.handleClick = this.handleClick.bind(this);
  }


  handleClick(e){
    this.setState({ currentPos: e.latlng });
  }

  render() {
    return (
      <div>
        <Map center={this.props.center} zoom={this.props.zoom} onClick={this.handleClick}>
          <TileLayer
              url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
          />
          { this.state.currentPos && <Marker position={this.state.currentPos} draggable={true}>
            <Popup position={this.state.currentPos}>
              Current location: <pre>{JSON.stringify(this.state.currentPos, null, 2)}</pre>
            </Popup>
          </Marker>}
        </Map>
      </div>
    )
  }
}

说明:

  • currentPos状态是用来保持标记位置
  • event.latLng事件处理程序的Map.onClick属性返回鼠标事件位置

Here is a demo供你参考


1
投票

那你尝试做到这一点?

这将是开始:

使用点击(见https://leafletjs.com/reference-1.4.0.html#map-click)从LeafletMap组件事件并调用你的功能,如:

<LeafletMap
  center={[35.755229,51.304470]}
  zoom={16}
  maxZoom={20}
  attributionControl={true}
  zoomControl={true}
  doubleClickZoom={true}
  scrollWheelZoom={true}
  dragging={true}
  animate={true}
  easeLinearity={0.35}
  onclick={this.handleClick}>
>
...
</LeafletMap>

在你handleClick功能你得到的纬度和经度这样的信息:

handleClick = (e) => {
  const { lat, lng } = e.latlng;
  console.log(lat, lng);
}

从这里开始,你可以创建你所寻找的信息,请标记/弹出。

额外提示:请确保您的代码在您的文章正确包裹在..

© www.soinside.com 2019 - 2024. All rights reserved.