【发布时间】:2019-09-29 13:15:58
【问题描述】:
我正在使用 react-google-maps 组件制作带有一个标记的地图。我做到了,它运行良好,但问题是我希望该标记始终居中。
我在 google 上进行了研究,并找到了几种解决方案:一个是通过 google API,但我不知道如何实现 react-google-maps,第二个 - 在地图上添加假标记 - 我认为不是很好的解决方案。
import React from 'react';
import { GoogleMap, withScriptjs, withGoogleMap, Marker} from 'react-google-maps';
function Map() {
return(
<GoogleMap
defaultZoom={13}
defaultCenter={{lat:54.68916, lng:25.2798}}
>
<Marker
position={{lat:54.68916, lng:25.2798}}
draggable={true}
onDragEnd={(e) => markerDrop(e)}
/>
</GoogleMap>
);
}
function markerDrop(event){
//get values of marker
let lat = event.latLng.lat();
let lng = event.latLng.lng();
//insert values to forms
document.getElementById('location_latitude').value = lat;
document.getElementById('location_longitude').value = lng;
return
}
const WrappedMap = withScriptjs(withGoogleMap(Map));
export default function PickLocation(){
return(
<div>
<WrappedMap
googleMapURL={'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=AIzaSy'}
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
)
}
和结果必须与uber拾取地图相似,其中标记位于地图中间,并且地图正在移动。
【问题讨论】:
-
您可以通过将
GoogleMap组件的center属性设置为与标记相同的lat lng 来实现。例如:<GoogleMap center={{lat: this.props.markerLat, lng: this.props.markerLng}} ....> -
我之前尝试过这个解决方案,但后来我在控制台中收到错误 TypeError: Cannot read property 'props' of undefined
-
要做到这一点,您必须更改
Map的组件属性或标记位置更改时的状态。您必须将Map更改为类组件或接收属性作为参数的函数。
标签: javascript reactjs google-maps react-google-maps