在react中使用套的地图
1.标题在react中使用道德地图首先需要去npm 下载 然后引用import { Map, Marker} from react-amap;
2.引入之后需要在一些简单的配置如下
render() {
let mapStyle = {
boxSizing: border-box,
width: this.props.width || 400px,
height: this.props.height || 300px
}
return (
<div>
<div className=container id=container style={
mapStyle}>
<Map events={
this.amapEvents} amapkey=可以自己申请 version=1.4.15>
<Marker position={
this.state.position} events={
this.markerEvents}/>
</Map>
</div>
</div>
);
}
3. 然后配置一下相对应的事件如下
this.state = {
currentLocation: ,
position: {
longitude: 120, latitude: 30},
}
this.amapEvents = {
created: (mapInstance) => {
window.AMap.plugin(AMap.Geocoder, () => {
this.geocoder = new window.AMap.Geocoder({
city: "010"//城市,默认:“全国”
});
})
},
click: (e) => {
const _this = this;
const lnglat = e.lnglat;
_this.setState({
//通过点击的经纬度来进行添加定位符号
position: lnglat,
});
this.geocoder.getAddress && this.geocoder.getAddress(lnglat, (status, result) => {
if (status === complete) {
if (result.regeocode) {
_this.props.detial(result.regeocode.formattedAddress || 未知地点, e.lnglat)
} else {
_this.props.detial(result.regeocode.formattedAddress || 未知地点, e.lnglat)
}
} else {
_this.props.detial(result.regeocode.formattedAddress || 未知地点, e.lnglat)
}
})
}
};
this.markerEvents = {
created: (markerInstance) => {
}
}
4.这样就可以通过传入经纬度然后拿到相对应的信息,值得一提的是在组件下载完成后在window上会有一个AMap 的变量,我搜索了一些文章大家都是找不到AMap 那么这里提一下 在react 里直接写AMap 会报错所以我们要写全 写成window.AMap 就可以去得到然后看官网的案例就可以完成基本需求了