0

我正在使用 google-maps-react 库添加一个带有标记的谷歌地图,这些标记会随着状态变化而更新。

我想在从 Google 的 place api 获取位置并将它们存储在状态后动态添加标记。我获取数据,将其添加到状态,然后调用 displayMarkers:

displayMarkers = () => {
    this.state.newStations.map((station, index) => {
      let lat = station.geometry.location.lat();
      let lng = station.geometry.location.lng();
      return (
        <Marker
          key={index}
          id={index}
          position={{
            lat: lat,
            lng: lng,
          }}
          onClick={() => console.log("You clicked me!")}
        />
      );
    });
  };

状态正在更新,但标记未出现在地图上。

阅读 google-maps-react 的文档,在我看来,标记必须是 map 的子级才能覆盖到地图上。

标记 要在地图上放置标记,请将其作为组件的子项包含在内。

有没有办法将 Marker 作为 Map 的子级返回?

在 google maps API 中,您似乎可以这样做:

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
  });

您传入值映射,这是您希望标记附加或覆盖到的映射。道具“地图”存在于 google-maps-react 但 Marker 中似乎没有接受地图的属性。

4

1 回答 1

0

你可以在 google-maps-react 中这样做。您需要在状态中有一个数组来保存结果数组。然后在获取 Places 结果时,创建一个数组变量,然后将结果推送到该 arrau 变量上。然后将标记数组状态值设置为数组变量。

然后在您的 Map 对象中,放置 Marker 对象,但是您需要添加条件来检查标记数组状态值是否不为空,并且您将每个标记数组状态值映射到标记对象中。

import React, { Component } from "react";
import { Map, GoogleApiWrapper, Marker } from "google-maps-react";

export class MapContainer extends Component {
  state = {
    center: {
      lat: 40.854885,
      lng: -88.081807
    },
    markers: null,
  };

  fetchPlaces = (mapProps, map) => {
    let coordinates = [];
    const { google } = mapProps;
    const service = new google.maps.places.PlacesService(map);
    var request = {
      location: this.state.center,
      radius: "500",
      query: "restaurant"
    };
    service.textSearch(request, (results, status) => {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          //console.log(results[i]);
          coordinates.push(results[i]);
        }
        this.setState({ markers: coordinates });
      }
    });
  };

  clickMarker = (props, marker) => {
    console.log(props.placeId);
  };

  render() {
    if (!this.props.loaded) return <div>Loading...</div>;

    return (
      <div>
        <Map
          className="map"
          google={this.props.google}
          center={{
            lat: this.state.center.lat,
            lng: this.state.center.lng
          }}
          onReady={this.fetchPlaces}
          style={{ height: "100%", position: "relative", width: "100%" }}
          zoom={8}
        >
          {this.state.markers != null &&
            this.state.markers.map(coords => (
              <Marker
                key={coords.place_id}
                position={coords.geometry.location}
                onClick={this.clickMarker}
                placeId={coords.place_id}
              />
            ))}
        </Map>
      </div>
    );
  }
}
export default GoogleApiWrapper({
  apiKey: "YOUR_API_KEY"
})(MapContainer);```
于 2021-04-26T04:09:21.613 回答