【问题标题】:Add markers to map/clusterer after mount using react-google-maps使用 react-google-maps 挂载后向 map/clusterer 添加标记
【发布时间】:2018-10-26 06:37:07
【问题描述】:

将react-google-maps 与 MarkerClusterer 一起使用,我如何在安装地图后从地图/集群中添加和删除标记,例如。当一个按钮被点击或在 onMarkerClustererClick 中?

我尝试过简单地制作一个新的标记,并将 map 设置为 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>
);

【问题讨论】:

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


    【解决方案1】:

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

    以下是如何动态添加标记的示例: 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));
    

    如果这对你有帮助,请告诉我:)

    【讨论】:

    • 准备好了,我举个例子,反正我已经提供了codebox的链接
    猜你喜欢
    • 2020-12-03
    • 2020-08-20
    • 1970-01-01
    • 2017-12-18
    • 2019-08-11
    • 2017-05-15
    • 1970-01-01
    • 2013-01-19
    • 2020-10-06
    相关资源
    最近更新 更多