在React中使用高德地图

在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 就可以去得到然后看官网的案例就可以完成基本需求了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值