如何使用地图作为反应中的位置输入?

How to use maps as location input in react?

我正在尝试制作一个用户可以搜索其位置或固定其位置的表单。我使用 react-leaflet 加载地图,使用 react-leaflet-search 添加搜索功能。 搜索功能运行良好。下面你可以看到代码。

<Map center={position} zoom={zoom}  onDragEnd = {function(e){ console.log(e);}} >
  <TileLayer
    attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    url='https://{s}.tile.osm.org/{z}/{x}/{y}.png'/>
  <Search 
    position="topright" 
    showPopup={false} 
    provider="OpenStreetMap" 
    showMarker={true} 
    openSearchOnLoad={true} 
    closeResultsOnClick={true} 
    providerOptions={{ region: "np" }}/>
</Map>

我想做的是访问用户输入的位置或用户选择位置后显示的标记的经纬度。我试图搜索事件侦听器,但找不到。目前我正在尝试使用 onDragEnd 事件,但我还没有成功。谁能告诉我如何实现我想要做的事情?

很遗憾,react-leaflet-search 没有正确的方法来检索搜索结果。我们可以使用 mapStateModifier 回调来获取搜索结果坐标 LatLng 对象,但我们还必须设置地图 flyTo 调用:

render() {
  const position = [51.505, -0.09];
  const zoom = 13;

  return (
    <div>
      <Map 
        ref={ref => this.mapRef = ref}
        center={position} 
        zoom={zoom}
      >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='https://{s}.tile.osm.org/{z}/{x}/{y}.png' />

        <ReactLeafletSearch 
          ref={ref => this.mapSearchRef = ref}
          mapStateModifier={(latLng) => {

            // Do work with result latitude, longitude
            console.log('Search Latitude:', latLng.lat);
            console.log('Search Longitude:', latLng.lng);

            if (this.mapRef) {
              // Because we have a custom mapStateModifier callback,
              // search component won't flyTo coordinates
              // so we need to do it using our refs
              this.mapRef.contextValue.map.flyTo(
                latLng,
                this.mapSearchRef.props.zoom,
                this.mapSearchRef.props.zoomPanOptions
              );
            }
          }}
          position="topright" 
          showPopup={false} 
          provider="OpenStreetMap" 
          showMarker={true} 
          openSearchOnLoad={true} 
          closeResultsOnClick={true} 
          providerOptions={{ region: "np" }}
        />
      </Map>
    </div>
  );
}

您可以查看此示例 Stackblitz 以查看它是否正常工作。