react-google-maps Marker Click Event

时间:2017-11-19 14:38:05

标签: reactjs google-maps

我正在使用react-google-maps文档中发布的聚集地图的股票代码。我正在尝试通过为标记添加点击事件来扩展代码,该事件将从API中获取标记URL,然后调用window.location来更改页面。

以下是从我的API返回的其中一个标记的示例:

{
  id: 1,
  name: "Oxford",
  slug: "oxford",
  lat: 51.752021,
  lng: -1.257726,
}

我已在标记中添加了一个事件onMarkerClick,并且正在调用该方法。我硬编码window.location并调用它,我只是不知道如何获取slug值。

我假设我必须以不同于下面示例中的方式存储slug值。我是React的新手,所以我可能遗漏了一些非常明显的东西

import React from 'react'

const fetch = require("isomorphic-fetch");
const { compose, withProps, withHandlers } = require("recompose");
const {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker
} = require("react-google-maps");
const { MarkerClusterer } = require("react-google-maps/lib/components/addons/MarkerClusterer");

const MapWithAMarkerClusterer = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyCvakAjEUpqfnucJu-CoClBD1CtTKZUGxQ&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: 'calc(100vh - 56px)' }} />,
    containerElement: <div style={{ height: 'calc(100vh - 56px)' }} />,
    mapElement: <div style={{ height: 'calc(100vh - 56px)' }} />,
  }),
  withHandlers({
    onMarkerClustererClick: () => (markerClusterer) => {
      console.log('Clicked a cluster')
    },
    onMarkerClick: () => (marker) => {
      // link to post view page
      //
      //
      //
      //
      //
      console.log('Go to the marker post page')
      window.location = '/post/oxford';
    }
  }),
  withScriptjs,
  withGoogleMap
)(props =>
  <GoogleMap
    defaultZoom={3}
    defaultCenter={{ lat: 12.2637937, lng: 75.947508 }}
  >
    <MarkerClusterer
      onClick={props.onMarkerClustererClick}
      averageCenter
      enableRetinaIcons
      gridSize={60}
    >
      {props.markers.map(marker => (
        <Marker
          onClick={props.onMarkerClick}
          key={marker.id}
          position={{ lat: marker.lat, lng: marker.lng }}
          slug={marker.slug}
        />
      ))}
    </MarkerClusterer>
  </GoogleMap>
);

class TestMap extends React.PureComponent {
  componentWillMount() {
    this.setState({ markers: [] })
  }

  componentDidMount() {
    const url = '/api/posts';
    fetch(url)
      .then(res => res.json())
      .then(data => {
        this.setState({ markers: data });
      });
  }

  render() {
    return (
      <MapWithAMarkerClusterer markers={this.state.markers} />
    )
  }
}

export default TestMap

2 个答案:

答案 0 :(得分:4)

在这个例子中

<Marker
      onClick={props.onMarkerClick}
      key={marker.id}
      position={{ lat: marker.lat, lng: marker.lng }}
      slug={marker.slug}
/>

onMarkerClick: () => (marker) => {  //<- event object, not a marker object!  
   //.. 
}

特定的Google地图event对象将传递到onMarkerClick事件处理程序而非marker对象。

您可以利用.bindmarker对象作为参数传递:

<Marker
      key={marker.photo_id}
      position={{ lat: marker.latitude, lng: marker.longitude }}
      onClick={props.onMarkerClick.bind(this,marker)}
/>

然后给出marker对象的结构:

{
  id: 1,
  name: "Oxford",
  slug: "oxford",
  lat: 51.752021,
  lng: -1.257726,
}

onMarkerClick事件可以像这样初始化:

onMarkerClick: () => (marker) => {
  window.location = '/post/' + marker.slug;
}

答案 1 :(得分:4)

您可以为标记创建自定义组件,并通过其他参数进行标识 - 例如id

import React from 'react';
import {Marker} from 'react-google-maps';

const CustomMarker = (props) => {
    const {id} = props;

    const onMarkerClick = (evt) => {
        console.log(id);
    };

    return (
        <Marker
            onClick={onMarkerClick}
            {...props}
        />
    );
};

export default CustomMarker;