gpt4 book ai didi

reactjs - 当位置改变时重新定位 map 中心?

转载 作者:行者123 更新时间:2023-12-03 13:41:01 24 4
gpt4 key购买 nike

大家好,我正在使用 react-google-maps 库。每次我的位置发生变化时,我都会尝试重新调整 map (缩放标记所在的位置),但我对如何实现整个过程有点迷失。我可以看到标记正在更新,但 map 仍保持在其 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 属性是可变的,而 defaultZoom 则不然

关于reactjs - 当位置改变时重新定位 map 中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52259634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com