我正在编写一个在Map上绘制路线和2个标记的组件,我有一个循环,可以获取绘制标记的所有位置,但是我没有一次获取数组来渲染数据
我尝试设置条件,但似乎不起作用。问题在于状态,我将数组置于状态,但是由于异步过程,我无法及时渲染它。
import React, { useEffect, useState } from 'react';
import GoogleMapMaker from './GoogleMapMarker';
import GoogleMapReact from 'google-map-react';
const GoogleMapsComponent = (props) => {
const { blackboxLocation, showClaimLocation, showBlackboxLocation } = props;
const [locationState, setLocationState] = useState([]);
const [markerArray, setMarkerArray] = useState([]);
useEffect(() => {
setLocationState(blackboxLocation);
}, [blackboxLocation]);
useEffect(() => {
if(locationState) {
setMarkerArray([locationState[0], locationState[locationState.length]]);
}
}, [locationState]);
const mapProps = {
center: {
lat: 59,
lng: 30
},
zoom: 11
};
const handleGoogleMap = (google) => {
const routeProps = new google.maps.Polyline({
strokeColor: '#081E3E',
strokeOpacity: 0.8,
strokeWeight: 4,
});
routeProps.setMap(google.map);
drawLocationAndCenter(google, routeProps);
}
const drawLocationAndCenter = (google, routeProps) => {
if(showBlackboxLocation) {
const bounds = new google.maps.LatLngBounds();
const path = routeProps.getPath();
markerArray.then((marker) => console.log(marker));
locationState.then((locations) => {
locations.map((location) => {
const loc = new google.maps.LatLng(location.location.latitude, location.location.longitude);
path.push(loc);
bounds.extend(loc);
return google.map.fitBounds(bounds);
});
});
}
}
return (
<GoogleMapReact
bootstrapURLKeys={{ key: 'AIzaSyCHpeyXo9cKfdgjp-jfyRU52s70UB53D3E' }}
defaultCenter={mapProps.center}
defaultZoom={mapProps.zoom}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={handleGoogleMap}
>
{ markerArray.length > 0 &&
markerArray.map(location => (
<GoogleMapMaker
key={location.rowKey}
lat={location.location.latitude}
lng={location.location.longitude}
/>
))
}
</GoogleMapReact>
);
export default GoogleMapsComponent;
答案 0 :(得分:0)
Google地图提供了两个侦听器,您需要从中设置状态