react-google-maps
のドキュメントに掲載されているクラスターマップのストックコードを使用しています。私は、APIからマーカーURLを取得するマーカーのクリックイベントを追加し、ページを変更するためにwindow.location
を呼び出して、コードを拡張しようとしています。ここでreact-google-mapsマーカークリックイベント
は私のAPIから返されたマーカーの一つの例である:
{
id: 1,
name: "Oxford",
slug: "oxford",
lat: 51.752021,
lng: -1.257726,
}
私はマーカーにイベントonMarkerClick
を追加したとメソッドが正常に呼び出されてきています。私はwindow.locationをハードコードし、呼び出されると、私はちょうどスラグの値を取得する方法を知らない。
私は、以下の例で私がそれをやっている方法とは異なる方法でスラグ値を保存しなければならないと仮定しています。私は、この例
<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
イベントハンドラーに渡さなっているでは
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