我正在使用react google location将某个图钉放在可以工作的特定区域上,您只需在中输入一个位置即可,它会更新该图钉的位置。但是,当我在地图上拖动此图钉并放开鼠标单击时,图钉位置未处于更新状态,因此我的位置保持在通过Google响应位置更新的位置。
import React, { Component } from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
import { GoogleComponent } from 'react-google-location'
import { Container } from 'reactstrap'
import './styles/GoogleMaps.css'
const apiKey = 'AIzaSyDysvmNwccnv7MkNHYRdLkfZc7KKtHYFkQ'
const google = window.google
class MapContainer extends Component {
constructor(props) {
super(props);
this.state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {},
markers: [
{
place: 'Colorado, USA',
position: {
lat: 39.5500507,
lng: -105.7820674,
}
}
]
};
}
// grab users location after selection and set it to state
searchLocation = (e) => {
this.setState({
place: e,
lat: e.coordinates.lat,
lng: e.coordinates.lng,
zoom: 12,
})
}
//save marker lat and lng if user moves it
onMarkerMoved = (coord, index) => {
const { latLng } = coord;
const lat = latLng.lat();
const lng = latLng.lng();
this.setState(prevState => {
const markers = [...this.state.markers];
markers[index] = { ...markers[index], position: { lat, lng } };
return { markers };
});
}
onMapClicked = (props) => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
})
}
};
onMarkerClick = (props, marker, e) => {
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
}
render() {
console.log(this.state.place);
return (
<div>
<Container className="maps-container">
<div className="col-md-8">
<div className="input">
<GoogleComponent
apiKey={apiKey}
language={'en'}
country={'country:us'}
coordinates={true}
onChange={this.searchLocation}/>
</div>
<div className="map">
<Map
google={this.props.google}
zoom={4}
onClick={this.onMapClicked}
>
{this.state.markers.map((marker, index) => (
<Marker
key={index}
name={this.state.place}
position={marker.position}
draggable={true}
onDragend={(e, map, coord) => this.onMarkerMoved(coord, index)}
onClick={this.onMarkerClick}
name={marker.name}
/>
))}
<InfoWindow
marker={this.state.activeMarker}
onOpen={this.windowHasOpened}
onClose={this.onInfoWindowClose}
visible={this.state.showingInfoWindow}
>
<div>
<h1></h1>
</div>
</InfoWindow>
</Map>
</div>
</div>
</Container>
</div>
);
}
}
const LoadingContainer = (props) => (
<div>Fishtopia!</div>
)
export default GoogleApiWrapper({
apiKey: (apiKey),
LoadingContainer: LoadingContainer
})(MapContainer)