Rom*_*nas 2 javascript google-maps reactjs react-google-maps
我正在使用 react-google-maps 组件制作带有一个标记的地图。我做到了,它运行良好,但问题是我希望该标记始终居中。
我对谷歌进行了研究,并找到了几种解决方案:一个是通过谷歌 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>
)
}
Run Code Online (Sandbox Code Playgroud)
结果必须与 uber 拾取地图类似,其中标记位于地图中间,并且地图四处移动。
以下是在地图移动时保持标记居中的更改列表:
1)引入center状态以保持标记位置:
const [center, setCenter] = useState(null);
Run Code Online (Sandbox Code Playgroud)
2)在地图移动(通过bounds_changed或drag事件监听器)更新当前center:
const handleBoundsChanged = () => {
const mapCenter = refMap.current.getCenter(); //get map center
setCenter(mapCenter);
};
Run Code Online (Sandbox Code Playgroud)
在哪里
<GoogleMap
ref={refMap}
onBoundsChanged={handleBoundsChanged}
...
/>
Run Code Online (Sandbox Code Playgroud)
3)通过center状态定位标记:
<Marker position={center} />
Run Code Online (Sandbox Code Playgroud)
例子
function Map() {
const [center, setCenter] = useState({ lat: 54.68916, lng: 25.2798 });
const refMap = useRef(null);
const handleBoundsChanged = () => {
const mapCenter = refMap.current.getCenter(); //get map center
setCenter(mapCenter);
};
return (
<GoogleMap
ref={refMap}
defaultZoom={13}
defaultCenter={{ lat: 54.68916, lng: 25.2798 }}
onBoundsChanged={useCallback(handleBoundsChanged)}
>
<Marker position={center} />
</GoogleMap>
);
}
Run Code Online (Sandbox Code Playgroud)
注意:由于使用Hooks 需要React 版本
16.8或以上
| 归档时间: |
|
| 查看次数: |
5110 次 |
| 最近记录: |