gpt4 book ai didi

reactjs - react-google-maps 标记点击事件

转载 作者:行者123 更新时间:2023-12-03 13:40:07 24 4
gpt4 key购买 nike

我正在使用 react-google-maps 文档中发布的聚类 map 的库存代码。我尝试通过为标记添加单击事件来扩展代码,该事件将从 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

最佳答案

您可以为标记创建自定义组件,并通过附加参数来标识它 - 例如 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;

关于reactjs - react-google-maps 标记点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47378069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com