gpt4 book ai didi

javascript - 如何在 google-maps-react 中获取所有标记

转载 作者:行者123 更新时间:2023-12-05 06:32:00 24 4
gpt4 key购买 nike

我的项目中有 google-maps-react,但我不知道如何从 map 中获取所有标记?

import React, { Component } from "react";
import { Map, InfoWindow, Marker, GoogleApiWrapper } from "google-maps-react";
import "../Body/Map.css";
import marker_icon from "../../img/marker_icon.png";
import hover_icon from "../../img/hover_icon.png";
import { Grid, Row, Col } from "react-bootstrap";
/*global google*/

export class MapContainer extends Component {
constructor(props) {
super(props);

this.state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {}
};
}

onMarkerClick = (props, marker, e) => {
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
};

onMapClicked = props => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
});
}
};

addMarker = (mapProps, map) => {
var marker = new google.maps.Marker({
position: {},
map: map
});
};

render() {
const google = window.google;
const data = this.props.data;

return (
<div className="map-container">
<Map
google={this.props.google}
className={"map"}
zoom={1}
onClick={this.onMapClicked}
onReady={this.addMarker}
>
{data.map(item => (
<Marker
key={item.id}
title={item.name}
name={item.name}
position={{ lat: item.lat, lng: item.lng }}
onClick={this.onMarkerClick}
/>
))}
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
>
<div className="info">
<h1>{this.state.selectedPlace.name}</h1>
</div>
</InfoWindow>
</Map>
</div>
);
}
}

export default GoogleApiWrapper({
apiKey: "AIzaSyDLgdweTnvhPnUE5yzdxcMeK876cFtMaSk"
})(MapContainer);

最佳答案

我遇到了类似的问题。我想删除所有旧标记并添加新标记列表。这是我修复它的代码:

const MyMap = (props) => {

const [markers, setMarkers] = React.useState([])

React.useEffect(() => {
var markerArr = []
points.map(p => {
markerArr.push(<Marker position={{lat: p.lat, lng: p.lng}} />)
}
)
setMarkers(markerArr)
}, [])

const MarkerUpdater = (day) => {
var markerArr = []
points.map(p => {
markerArr.push(
<Marker position={{lat: p.lat, lng: p.lng}} />
)
}
)
setMarkers(markerArr)
}

return <Map> {markers} </Map>
}

注意

你应该在任何你想更新标记的地方调用MarkerUpdater

关于javascript - 如何在 google-maps-react 中获取所有标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51579671/

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