我正在尝试使用leaflet-geosearch
将搜索栏添加到React中的Leaflet Map(react-leaflet
)
import { Map, TileLayer, MapControl } from 'react-leaflet'
import { GeoSearchControl, OpenStreetMapProvider } from 'leaflet-geosearch'
class Search extends MapControl {
createLeafletElement() {
return GeoSearchControl({
provider: new OpenStreetMapProvider(),
style: 'bar'
})
}
}
...
export class MapContainer extends Component {
render() {
return (
<div>
<Map
ref={m => { this.leafletMap = m; }}
center={this.state.position}
zoom={this.state.zoom}
>
<TileLayer
attribution={tilesAttr}
url={tilesUrl}
/>
<Search />
</Map>
</div>
)
}
}
当我运行它时,我得到一个TypeError:
TypeError:无法读取未定义的Search.componentDidMount的属性“map”
}; MapControl.prototype.componentDidMount = function componentDidMount() { -> this.leafletElement.addTo(this.props.leaflet.map); }; MapControl.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
有没有人成功在他们的传单地图中添加搜索栏?
const GeoSearch = withLeaflet(Search)
使用“withLeaflet”
这里回答https://github.com/smeijer/leaflet-geosearch/issues/167#issuecomment-403107336
在这里https://react-leaflet.js.org/docs/en/custom-components.html
*import ...unrelated imports*
import { Map, TileLayer, Marker, MapControl, Popup, ZoomControl, withLeaflet } from 'react-leaflet';
import { GeoSearchControl, OpenStreetMapProvider } from 'leaflet-geosearch';
class SearchMap extends MapControl {
createLeafletElement() {
return GeoSearchControl({
provider: new OpenStreetMapProvider(),
style: 'bar',
showMarker: true,
showPopup: false,
autoClose: true,
retainZoomLevel: false,
animateZoom: true,
keepResult: false,
searchLabel: 'search'
});
}
}
class MapContainer extends React.Component {
render() {
const SearchBar = withLeaflet(SearchMap); {/* this part is needed */}
return(
<Map>
<SearchBar />
{/* rest of your map elements */}
</Map>
);
}
}
export default MapContainer;
变更清单:
withLeaflet
HOC包装你的组件,以确保在加载地图后控件被初始化,例如export default withLeaflet(GeoSearch);
componentDidMount
函数中leaflet-geosearch
css,例如通过public/index.html
例
class Search extends MapControl {
createLeafletElement(opts) {
const provider = new OpenStreetMapProvider();
const searchControl = new GeoSearchControl({
provider: provider,
//position: "topleft",
style: "bar"
});
return searchControl;
}
componentDidMount() {
const { map } = this.props.leaflet;
map.addControl(this.leafletElement);
}
}
这是a demo