React-Leaflet 搜索框实现

React-Leaflet Search Box Implementation

是否有任何资源显示使用 react-leaflet 实现的搜索框?

我想让我的 map pins 填充到 search 结果上,该结果将查询和检索我的现有数据。

即:

const names = [

  {name: 'Joe', location: '40.734621, -73.989341 '},
  {name: 'Seth', location: '45.77621, -73.789654 '},

]

然后,在搜索 Joe 或 Seth 之后,地图将填充位置坐标。

我找到了 leaflet.js 的示例,但找不到任何使用 react-leaflet 制作的示例。

看看leaflet-geosearch

使用 npm install --save leaflet-geosearch

安装

然后你只需要用它构建一个组件:

import { GeoSearchControl, OpenStreetMapProvider } from 'leaflet-geosearch';

class Search extends MapControl {

  createLeafletElement() {
    return GeoSearchControl({
      provider: new OpenStreetMapProvider(),
      style: 'bar',
      showMarker: true,
      showPopup: false,
      autoClose: true,
      retainZoomLevel: false,
      animateZoom: true,
      keepResult: false,
      searchLabel: 'search'
    });
  }
}

export default Search;

并在您的地图中使用您的组件:

render() {
  return (
    <Map>
      (...)
      <Search />
    </Map>
  );
}

我想我找到了一种更简单的方法,无需创建和扩展 class。

import { Map, useLeaflet } from 'react-leaflet'
import { OpenStreetMapProvider, GeoSearchControl } from 'leaflet-geosearch'

// make new leaflet element
const Search = (props) => {
    const { map } = useLeaflet() // access to leaflet map
    const { provider } = props

    useEffect(() => {
        const searchControl = new GeoSearchControl({
            provider,
        })

        map.addControl(searchControl) // this is how you add a control in vanilla leaflet
        return () => map.removeControl(searchControl)
    }, [props])

    return null // don't want anything to show up from this comp
}


export default function Map() {
  return (
    <Map {...otherProps}>
      {...otherChildren}
      <Search provider={new OpenStreetMapProvider()} />
    </Map>

  )
}