我正在使用 google-map-react 并希望能够动态更改位置和半径。目前选择的半径存储在数据库中,并使用 getRadius() 函数获取,但我不知道如何以及何时调用它,因此半径始终显示为 1000 米。
我试过使用 setRadius 方法,但我不知道如何从 apiIsLoaded 函数外部访问它。请帮忙!
import React, { useRef } from 'react';
import GoogleMapReact from 'google-map-react';
import Marker from './MapMarker';
import {getUserInfo} from '../firebaseConfig'
class SimpleMap extends React.Component {
constructor(props){
super(props);
this.googleMapCircle = React.createRef();
this.state = {
lat: "",
lng: "",
userPos: "",
radius: 1000,
};
}
static defaultProps = {
center: {
lat: 59.8,
lng: 17.63889
},
zoom: 11
};
componentDidMount = () => {
if (navigator.geolocation){
navigator.geolocation.watchPosition(this.currentCoords)
this.getRadius();
}
};
currentCoords = (position) => {
const latitude = position.coords.latitude
const longitude = position.coords.longitude
this.setState(prevState => ({
userPos: {...prevState.userPos,
lat: latitude, lng: longitude
}
})
)
};
getRadius = () => {
getUserInfo().then((result) => {
this.setState({
radius: result.radius
})
});
};
componentDidUpdate = (prevState) => {
if (prevState.radius !== this.state.radius) {
//This is where I want to update radius
}
};
apiIsLoaded = (map, maps, setUserPos, setUserRadius) => {
var circle = new maps.Circle({
ref:this.googleMapCircle,
strokeColor: "001e57",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#bbd0ff",
fillOpacity: 0.3,
map:map,
center: setUserPos,
radius: setUserRadius
});
};
render() {
const setCenter = this.state.userPos;
const setUserPos = this.state.userPos;
const setUserRadius = this.state.radius;
return (
<div style={{ height: '100%', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: 'API_KEY' }}
defaultCenter={this.props.center}
center={setCenter}
defaultZoom={this.props.zoom}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps}) => this.apiIsLoaded(map, maps, setUserPos, setUserRadius)}
>
<Marker
lat={setUserPos.lat}
lng={setUserPos.lng}
color="blue"
/>
</GoogleMapReact>
</div>
);
}
}
export default SimpleMap;