【问题标题】:React-Leaflet Search Box ImplementationReact-Leaflet 搜索框实现
【发布时间】:2018-01-16 22:03:36
【问题描述】:

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

我想让我的地图图钉填充到一个搜索结果中,以便查询和检索我现有的数据。

即:

const names = [

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

]

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

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

【问题讨论】:

    标签: javascript reactjs open-source react-leaflet


    【解决方案1】:

    看看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>
      );
    }
    

    【讨论】:

    • 非常感谢。我将开始实施这个
    • 谢谢,但是如何在此地图中附加搜索结果?
    • @QauseenMZ 这些是文档:smeijer.github.io/leaflet-geosearch 您可以阅读提供程序部分以了解如何实现搜索提供程序。
    【解决方案2】:

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

    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>
    
      )
    }
    

    【讨论】:

    • 这很棒,对我很有帮助。需要补充一点的是,如果使用 react-leaflet 的新 v3,则需要导入 useMap 而不是 useLeaflet(已弃用)。
    • @EricFurspan 你愿意分享你的代码吗?我无法使用 react-leaflet v3 完成这项工作。我还将&lt;Map /&gt; 替换为&lt;MapContainer /&gt;。它给了我错误map is undefined,指的是添加 mapControl 的行
    • @Phlame 我很乐意提供帮助。我只要求您将您的问题放入其自己的帖子中并将其链接发送给我,我将使用代码提供答案。这篇文章已经被回答了,所以我们不要污染它。
    • @EricFurspan 嗨,我终于想通了!感谢您愿意提供帮助!
    猜你喜欢
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 2021-09-21
    • 2022-07-27
    • 2022-12-08
    相关资源
    最近更新 更多