我有以下代码可在React Google Maps地图上呈现多个标记,而这些标记并非总是呈现。如果我注释掉第1条和第2条的信息,请保存并取消注释该信息,标记将呈现80%的时间。如果仅对当前位置进行硬编码,则标记将始终呈现。我不知道我在做什么错,很可能是我的ID-10-T错误。预先感谢您对此事的任何帮助。
/* global google */
import React from "react"
import { compose, withProps, withStateHandlers } from "recompose"
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
InfoWindow,
} from "react-google-maps"
const MyMapComponent = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=[api key goes here]&v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `600px` }} />,
mapElement: <div style={{ height: `75vh`, width: '50vw' }} />,
}),
withStateHandlers(() => ({
isOpen: false,
}), {
onToggleOpen: ({ isOpen }) => () => ({
isOpen: !isOpen,
})
}),
withScriptjs,
withGoogleMap
)((props) =>
<GoogleMap
zoom={15}
center={props.currentLocation}
>
{props.markerList.map((marker, index) => {
return (
<Marker
position={{
lat: marker.lat,
lng: marker.lng
}}
onClick={props.onToggleOpen}
title={marker.name}
key={marker.name}
>
{props.isOpen && <InfoWindow onCloseClick={props.onToggleOpen}>
<div>
<h3>Info Window</h3>
<h4>Testing</h4>
</div>
</InfoWindow>}
</Marker>
)
})};
</GoogleMap>
);
const markers = [
{
lat: 38.3332416,
lng: -95.63961839999999,
name: "bar 1"
},
{
lat: 38.0332416,
lng: -95.63971639999999,
name: "bar 2"
}
];
class MyFancyComponent extends React.PureComponent {
state = {
isMarkerShown: false,
}
componentWillMount() {
this.getGeoLocation()
}
getGeoLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
this.setState({
currentLatLng: {
lat: position.coords.latitude,
lng: position.coords.longitude,
name: "current location"
}
})
markers.unshift(this.state.currentLatLng);
}
)
} else {
error => console.log(error)
}
}
render() {
return (
<MyMapComponent
currentLocation={this.state.currentLatLng}
markerList={markers}
/>
)
}
}
export default MyFancyComponent;
答案 0 :(得分:0)
问题的关键是确定位置(执行Geolocation.getCurrentPosition()
的回调函数)MyMapComponent
组件时,这很可能是标记呈现不一致的原因。
要消除此行为,可以考虑采用以下解决方案。
由于MyFancyComponent
已经是有状态的组件,因此我建议引入markers
状态并像这样设置初始值:
class MyFancyComponent extends React.PureComponent {
state = {
isMarkerShown: false,
markers: markers
};
//...
}
然后,一旦确定了当前位置,就可以像这样更新状态:
getGeoLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
let latLng = {
lat: position.coords.latitude,
lng: position.coords.longitude,
name: "current location"
};
this.setState( prevState => ({
currentLatLng: latLng,
markers: [latLng,...prevState.markers]
}));
});
} else {
error => console.log(error);
}
};
并最终传递给MyMapComponent
组件作为道具:
<MyMapComponent
currentLocation={this.state.currentLatLng}
markerList={this.state.markers}
/>