如何添加标记onClick并在google-maps-react中显示我的地理位置? [英] How to add marker onClick and show my geolocation in google-maps-react?
本文介绍了如何添加标记onClick并在google-maps-react中显示我的地理位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Google地图文档中发现了很多有用的信息,但是在react
的情况下,我只是简单地在html中使用js,所以我不理解.
I found a lot of useful information on google maps documentation but with simple use of js in html, in case of react
honestly I don't understand it.
源代码:
import React, { Component } from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
export class MainMap extends Component {
render() {
return (
<div>
<h1 className="text-center">My Maps</h1>
<Map google={this.props.google}
style={{width: '80%', margin: 'auto'}}
className={'map'}
zoom={14}>
<Marker
title={'The marker`s title will appear as a tooltip.'}
name={'SOMA'}
position={{lat: 37.778519, lng: -122.405640}} />
<Marker
name={'Dolores park'}
position={{lat: 37.759703, lng: -122.428093}} />
<Marker />
<Marker
name={'Your position'}
position={{lat: 46.475640, lng: 30.759497}}/>
</Map>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: (MY-API-KEY)
})(MainMap);
我想通过单击地图来添加标记,但不知道如何... 请帮忙!
i want to add marker by clicking on map and don't know how... help please!
推荐答案
地图上有一个onClick
道具,您可以为其提供一个功能来处理对地图的点击.该函数的第三个参数包括点击的坐标.
The map has an onClick
prop which you can give a function to handle clicks on the map. The third argument to this function includes the coordinates of the click.
您可以使用这些坐标将标记添加到在render
方法中使用的状态.
You could use these coordinates to add a marker to your state that you use in the render
method.
示例
class MainMap extends Component {
constructor(props) {
super(props);
this.state = {
markers: [
{
title: "The marker`s title will appear as a tooltip.",
name: "SOMA",
position: { lat: 37.778519, lng: -122.40564 }
}
]
};
this.onClick = this.onClick.bind(this);
}
onClick(t, map, coord) {
const { latLng } = coord;
const lat = latLng.lat();
const lng = latLng.lng();
this.setState(previousState => {
return {
markers: [
...previousState.markers,
{
title: "",
name: "",
position: { lat, lng }
}
]
};
});
}
render() {
return (
<div>
<h1 className="text-center">My Maps</h1>
<Map
google={this.props.google}
style={{ width: "80%", margin: "auto" }}
className={"map"}
zoom={14}
onClick={this.onClick}
>
{this.state.markers.map((marker, index) => (
<Marker
key={index}
title={marker.title}
name={marker.name}
position={marker.position}
/>
))}
</Map>
</div>
);
}
}
const App = GoogleApiWrapper({
apiKey: (MY-API-KEY)
})(MainMap);
这篇关于如何添加标记onClick并在google-maps-react中显示我的地理位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文