use*_*058 2 javascript leaflet reactjs react-leaflet
所以我对反应和传单真的很陌生,但我想做的基本上就是让用户输入一些输入,然后在他们按回车键后,触发一个事件,然后该事件飞到从该输入生成的坐标。我正在使用地理编码,经纬度坐标已成功生成。但是我不知道如何使地图飞到那个位置。这是我到目前为止所拥有的:
import './App.css';
import * as React from "react";
import { ChakraProvider } from "@chakra-ui/react";
import { MapContainer, TileLayer, Marker, Popup, useMapEvents } from 'react-leaflet'
import 'leaflet/dist/leaflet.css'
import Geocode from "react-geocode";
import SearchBar from './SearchBar';
class App extends React.Component {
constructor(props){
super(props)
this.state = {
position: [43.653225, -79.383186]
}
}
mapRef = React.createRef();
changePos (pos) {
this.setState({position: pos});
this.mapRef.current.flyTo(pos);
}
render () {
return (
<ChakraProvider resetCSS = {false}>
<div className = "App">
<div id="title">
<h1>
CovidStopSpots
</h1>
<p>A responsive tracker for Covid-19.</p>
<SearchBar changePos = {this.changePos.bind(this)}></SearchBar>
</div>
<div id="map">
<MapContainer center={this.state.position} zoom={13} scrollWheelZoom={false} ref={this.mapRef}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[43.653225, -79.383186]}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
</div>
</div>
</ChakraProvider>
)
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
当前的代码也会生成此错误:
Unhandled Rejection (TypeError): Cannot read property 'flyTo' of null
Run Code Online (Sandbox Code Playgroud)
在react-leaflet版本3中,您可以使用prop获取地图实例whenCreated,然后当您不想将其用于子组件时使用它飞到另一个位置MapContainer's。
this.state = {
position: [43.653225, -79.383186],
map: null
}
Run Code Online (Sandbox Code Playgroud)
删除 ref 并使用whenCreatedprop
<MapContainer center={this.state.position} zoom={13} scrollWheelZoom={false} whenCreated={map => this.setState({ map })}>
Run Code Online (Sandbox Code Playgroud)
然后在你的changePos事件中使用this.state.map来飞行
changePos (pos) {
this.setState({position: pos});
const {map} = this.state;
if (map) map.flyTo(pos);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8570 次 |
| 最近记录: |