reactjs - 当位置改变时重新定位地图的中心?
问题描述
大家好,我正在使用react-google-maps
图书馆。每次我的位置发生变化时,我都会尝试重新定位我的地图(缩放标记所在的位置),但我对如何实现整个事情有点迷茫。我可以看到标记正在更新,但地图保持在其defaultCenter
位置。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
GoogleMap,
Marker,
withScriptjs,
withGoogleMap
} from 'react-google-maps';
import environment from '../../config/environment';
class Map extends Component {
static propTypes = {
defaultZoom: PropTypes.number,
center: PropTypes.shape({
lat: PropTypes.number,
lng: PropTypes.number
}),
location: PropTypes.shape({
lat: PropTypes.number,
lng: PropTypes.number
}),
onPositionChanged: PropTypes.func
};
static defaultProps = {
defaultZoom: 14,
center: {
lat: 60.1699,
lng: 24.9384
},
location: {},
onPositionChanged: () => {}
};
constructor(props) {
super(props);
this.mapRef = React.createRef((ref) => {
this.mapRef = ref;
});
}
componenDidUpdate() {
console.log(`I'm about to update with props: ${JSON.strongify(prevProps, undefined, 2)}`);
}
onPositionChanged = (location) => {
console.log(`This the new location onPositionChange:${JSON.stringify(location, undefined, 2)}`);
const newLocation = new window.google.maps.LatLng(location.lat, location.lng);
// [NOTE]: try using the panTo() from googleMaps to recenter the map ? but don't know how to call it.
return (
<Marker
position={newLocation}
/>
);
}
render() {
const {
center,
defaultZoom,
location,
onPositionChanged
} = this.props;
return (
<GoogleMap
className="google-map"
onClick={onPositionChanged(location)}
defaultZoom={defaultZoom}
defaultCenter={center}
ref={this.mapRef}
>
{/* <Marker
position={location}
/> */}
{ this.onPositionChanged(location) }
</GoogleMap>
);
}
}
const SchedulerGoogleMap = withScriptjs(withGoogleMap(Map));
const SchedulerMap = props => (
<SchedulerGoogleMap
googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${
environment.GOOGLE_MAPS_API_KEY
}&v=3`}
loadingElement={<div style={{ height: '20vh' }} />}
containerElement={<div style={{ height: '100%' }} />}
mapElement={<div style={{ height: '20vh', width: '100%' }} />}
{...props}
/>
);
export { Map, SchedulerMap, SchedulerGoogleMap };
解决方案
只需将center
道具传递给您的GoogleMap
组件而不是defaultCenter
道具。center
prop 是可变的,而defaultZoom is not
.
推荐阅读
- javascript - 在javascript(不是jquery)中返回父节点的类
- scala - Slick 结果集大小默认限制
- javascript - 我有基于日期输入的带有动态链接的 JS 表单,我需要以 DD-MM-YYYY 格式输出
- javascript - 如何将许多使用相同 javascript 的 html 按钮添加到循环结果中?
- excel - Conditional formatting, search formula
- c - GSL multiple error handler definition error when linking
- excel - Copying only new entries from a sheet that meet a criteria and adding at the end of a column in another sheet
- node.js - 在 Electron 应用程序中找不到节点模块
- angular - Ionic 3 - How to retrieve firebase data after facebook login
- python - Python IOError:[Errno 5] 输入/输出错误?