【发布时间】:2018-11-01 10:37:25
【问题描述】:
我正在尝试根据用户单击 google-maps-react npm 的地图添加标记。目前,下面的代码将生成标记并将它们添加到this.state = { markers:[ ] },我想将它们映射到地图组件上。但是,position:event.latLng, 不会注册 lat 和 lng,并且只会创建标记并将其插入到具有 key: Date.now() 和 defaultAnimation: 2 的状态中。代码下方:
import React, { Component } from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
export class MapContainer2 extends Component {
constructor(props){
super(props);
this.state={
lat:null,
lng:null,
markers:[]
}
}
componentDidMount(){
navigator.geolocation.getCurrentPosition(position=>
this.setState({
lat:position.coords.latitude,
lng:position.coords.longitude,
}));
}
mapClicked = (event) =>{
const { markers } = this.state;
this.setState({
markers:[
{
position:event.latLng,
key: Date.now(),
defaultAnimation: 2,
},
...markers
]
})
}
render() {
if (!this.props.loaded) {
return <div>Loading...</div>
}
const style = {
width: '100%',
height: '100vh'
}
return (
<Map
google={this.props.google}
zoom={11}
style={style}
initialCenter={{
lat: this.state.lat,
lng: this.state.lng
}}
center={{
lat: this.state.lat,
lng: this.state.lng
}}
onClick={this.mapClicked}
>
<Marker
title={'Geolocation'}
position={{
lat:this.state.lat,
lng:this.state.lng,
}}
/>
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: ('AIzaSyCZ7rgMN34kWkGvr8Pzkf_8nkT7W6gowBA')
})(MapContainer2)
【问题讨论】:
-
this 是您正在使用的库吗?
-
是的,浏览了文档,不知道如何处理这个......
-
你的问题解决了吗?
-
是的,请看下面我的回复。
标签: reactjs google-maps-api-3 google-maps-markers