是否有任何资源显示带有react-leaflet的搜索框实现?
我希望将地图引脚填充到搜索结果上,以查询和检索我现有的数据。
即:
const names = [
{name: 'Joe', location: '40.734621, -73.989341 '},
{name: 'Seth', location: '45.77621, -73.789654 '},
]
然后,在搜索Joe或Seth之后,地图将填充位置坐标。
我找到了leaflet.js的例子,但是找不到反应传单的任何例子。
答案 0 :(得分:4)
使用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>
);
}
答案 1 :(得分:1)
我认为我发现了一种无需创建和扩展类的简单方法。
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>
)
}