我有渲染标记的方法,如下所示。我从道具传递标记数组,并在每次componentDidUpdate触发时渲染它。问题是我的旧标记没有从地图上删除。例如,如果我在父组件中有1个坐标,并用新坐标更新,则出现新坐标,而旧坐标静止不动。
`
import React from 'react';
const google = window.google;
export class GMap extends React.Component {
mapRef = React.createRef();
directionsService
directionsRenderer
map;
componentDidMount() {
this.initMap();
const { onClick } = this.props;
onClick && this.onMapClick();
}
componentDidUpdate() {
const { markers } = this.props;
this.calcRoute();
if (markers && markers.length > 0) {
this.clear(markers);
this.renderMarkers(markers);
}
}
initMap() {
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
const mapOptions = {
zoom: 13,
center: { lat: 40.386119, lng: 49.860925 }
}
const map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.map = map;
this.directionsRenderer.setMap(map);
}
onMapClick() {
this.map.addListener('click', (e) => {
this.props.onClick(e);
})
}
renderMarkers(markers) {
markers.forEach(position => {
const marker = new google.maps.Marker({ position });
marker.setMap(this.map);
})
}
calcRoute() {
const { directions } = this.props;
if (directions) {
const [{ lat: fLat, lng: fLng }, { lat: tLat, lng: tLng }] = directions;
if (fLat && fLng && tLat && tLng) {
var request = {
origin: { lat: fLat, lng: fLng },
destination: { lat: tLat, lng: tLng },
travelMode: 'DRIVING'
};
this.directionsService.route(request, (result, status) => {
if (status === 'OK') {
this.directionsRenderer.setDirections(result);
}
});
}
}
}
render() {
return (
<div id='map' ref={this.mapRef} />
)
}
}
`
您如何删除标记?我在发布的代码中只能看到this.clear(markers)
,而没有引用clear
。尝试做这样的事情:
clear(markers) {
for(let i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
希望这会有所帮助!