element ui -- 高德webAPI根据地址信息获取经纬度坐标

需求:根据省市加地址信息 获取经纬度

实现前提: 具备高德申请好的密钥

代码实现:(这里根据外链引入形式实现高德webapi提供的开放接口)

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你的密钥"></script>

先在index.html中引入文件路径。

其次在需要用到获取坐标方法的页面直接定义方法

//获取当前地点坐标
        getCoordinate() {
            let vm = this
            var map = new AMap.Map("container");
            var geocoder;
            var address = '';
            //地址和经纬度之间进行转换服务
            map.plugin(["AMap.Geocoder"], () => {
            geocoder = new AMap.Geocoder({
                city: ''
            });
            var address = vm.departmentForm.province + vm.departmentForm.city + vm.departmentForm.receivingAddress
          //对指定地址进行解析
            geocoder.getLocation(address, (status, result) => {
                    if (status === 'complete' && result.info === 'OK') {
                            console.log(result)
                        // return;
                        //TODO:获得了有效经纬度,可以做一些展示工作
                        //比如在获得的经纬度上打上一个Marker
                            vm.departmentForm.storeCoordinate = result.geocodes[0].location.lat + ',' + result.geocodes[0].location.lng
                            vm.departmentForm.longitude = result.geocodes[0].location.lng;
                            vm.departmentForm.latitude = result.geocodes[0].location.lat;
                            vm.$forceUpdate();
                    } else {
                    //获取经纬度失败
                        vm.$message.error('出错了,请输入正确的地址!!!');
                    }
                });
            })
        },

其中  var address = vm.departmentForm.province + vm.departmentForm.city + vm.departmentForm.receivingAddress 地址信息换上自己定义的省市区详细地址信息即可。

<el-button  type="primary"@click.stop="getCoordinate()">获取坐标</elbutton>

在html中点击直接获取地址坐标。

posted @ 2022-06-30 16:54  巫小婆  阅读(653)  评论(0编辑  收藏  举报