使用react-google-maps

时间:2018-05-16 09:21:49

标签: reactjs google-maps google-maps-api-3 react-google-maps

react-google-maps与MarkerClusterer一起使用,如何在挂载地图后添加和删除地图/聚类器中的标记,例如。单击按钮时还是在onMarkerClusterer上点击?

我尝试过将地图设置为 refs.map

的新标记
      onMarkerClustererClick: () => (markerClusterer) => {
        const marker = new Marker({
          position: {lat: 56.565123, lng: 9.030908},
          map: refs.map,
          title: 'Hello World!'
        });
      },

以及在react-google-maps中使用用于MarkerClusterer的markerclustererplus中定义的 .addMarker()函数,但没有任何效果。

  onMarkerClustererClick: () => (markerClusterer) => {
    const marker = new Marker({
      position: {lat: 56.565123, lng: 9.030908},
      title: 'Hello World!'
    });

    refs.markerClusterer.addMarker(marker);
  },

两者都返回错误Uncaught TypeError: Cannot read property '__SECRET_MARKER_CLUSTERER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined

基于以下示例的代码:https://tomchentw.github.io/react-google-maps/#markerclusterer

const MapWithAMarkerClusterer = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=AIzaSyATVkXuYRZCkB73ZsPEJisDy74GnVusIJw",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div className="mapContainer" />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  withHandlers(() => {
    const refs = {
      map: undefined,
      markerClusterer: undefined,
    }

    return {
      onMapMounted: () => ref => {
        refs.map = ref
      },
      onMarkerClustererMounted: () => ref => {
        refs.markerClusterer = ref
      },
      onMarkerClustererClick: () => (markerClusterer) => {
        const marker = new Marker({
          position: {lat: 56.565123, lng: 9.030908},
          title: 'Hello World!'
        });

        refs.markerClusterer.addMarker(marker);
      },
    }
  }),
  withScriptjs,
  withGoogleMap
)(props =>
  <GoogleMap
    ref={props.onMapMounted}
    defaultZoom={3}
    defaultCenter={{ lat: 25.0391667, lng: 121.525 }}
  >
    <MarkerClusterer
      ref={props.onMarkerClustererMounted}
      onClick={props.onMarkerClustererClick}
      averageCenter
      enableRetinaIcons
      gridSize={60}
    >
      {props.hotels.results.map((item, index) => (
        <Marker
          key={index}
          position={{lat: parseFloat(item.latitude), lng: parseFloat(item.longitude) }}
        />
      ))}
    </MarkerClusterer>
  </GoogleMap>
);

1 个答案:

答案 0 :(得分:0)

您必须在集群附近添加带有state-lat和state-lon的标记,如果您尝试更改道具(它们是不可变的),则地图将不会更新。

这是一个如何动态添加标记的示例: SANDBOX EXAMPLE

以下示例:

import React from "react";
import {
  withGoogleMap,
  GoogleMap,
  Marker,
  withScriptjs
} from "react-google-maps";

const Markers = ({ places }) => {
  return places.map(place => {
    return (
      <Marker key={place.id} position={{ lat: place.lat, lng: place.lng }} />
    );
  });
};

const Map = ({ places, zoom, center }) => {
  return (
    <GoogleMap defaultZoom={zoom} defaultCenter={center}>
      <Markers places={places} />
    </GoogleMap>
  );
};

const getRandomInRange = (from, to, fixed) => {
  return (Math.random() * (to - from) + from).toFixed(fixed) * 1;
};

class MapWithMarker extends React.Component {
  constructor(props) {
    super(props);
    this.state = { places: this.props.places }; //initialize initial state from props
  }

  addPlace() {
    const newPlace = {
      id: this.state.places.length + 1,
      lat: getRandomInRange(-30.0, -35.0, 3),
      lng: getRandomInRange(110.0, 150.0, 3)
    };
    this.setState(prevState => ({
      places: [...prevState.places, newPlace]
    }));

    /*if(this.state.places.length > 10) { 
      clearInterval(this.intervalId)
    }*/
  }

  componentDidMount() {
    this.intervalId = setInterval(this.addPlace.bind(this), 1000);
  }
  componentWillUnmount() {
    clearInterval(this.intervalId);
  }

  render() {
    return (
      <Map
        center={this.props.center}
        zoom={this.props.zoom}
        places={this.state.places}
      />
    );
  }
}

export default withScriptjs(withGoogleMap(MapWithMarker));

告诉我这是否对您有帮助:)