高德地图获取当前位置信息

839 阅读2分钟

首先 需要注册高德开发者服务

  1. 高德开发者平台官网
  2. 申请应用 点击左上角的头像,选择下拉框
image.png
选择应用管理

image.png

按照流程申请应用....

申请完成页面 image.png

在网页上使用高德API

在网页头部位置声明

window._AMapSecurityConfig = {
    securityJsCode: 'your certificate Detail'
}
//注意这个一定是在引入amap脚本前声明

引入script

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

编写调用方法(只获取当前位置信息,不需要地图)

function geoFindMe() {
    let amp;
    var map;
    AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默认:true
            timeout: 10000,          //超过10秒后停止定位,默认:5s
        });

        geolocation.getCurrentPosition(function (status, result) {
            if (status === 'complete') {
                onComplete(result)
            } else {
                onError(result)
            }
        });
    });

    //解析定位结果
    function onComplete(data) {
        var geocoder = new AMap.Geocoder()
        geocoder.getAddress(data.position, function (status, result) {
            if (status === 'complete' && result.regeocode) {
                const address = `${result.regeocode.addressComponent.province}${result.regeocode.addressComponent.city}${result.regeocode.addressComponent.district}`
                console.log(address)
                console.log(result.regeocode.formattedAddress)
                document.getElementById('address').value = result.regeocode.formattedAddress;
            } else {
                log.error('根据经纬度查询地址失败')
            }
        });
    }

    //解析定位错误信息
    function onError(data) {
        console.log(data)
    }
}

ps: result.regeocode.formattedAddres和result.regeocode.addressComponent.province+result.regeocode.addressComponent.city+result.regeocode.addressComponent.district的区别

formattedAddres是高德响应给出的绝对地理地址("XX省xx市"),其他的是通过各个部分拼接起来的(如xxx省 + xx市)

参考响应

image.png

对比web Geolocation_API的区别

web Geolocation

使用web Geolocation_API 获取的内容 image.png

可以发现两者给出的地理位置坐标并不相同

探究原因: 国内地图都是经过偏移的坐标,其值保密。 需要获取在各个坐标系下的一致性坐标,就需要将坐标系进行统一。

常见互联网地图使用什么坐标系?

百度地图:BD09

腾讯地图:GCJ02

高德地图:GCJ02

谷歌中国地图:GCJ02

微信小程序图:GCJ02

各家API公司坐标转换接口的申请

一般需要将您的公司名称、项目名称、项目简介、联系人和联系方式,发邮件至地图API公司的商务部,经过申请,才能使用。
下面是他们的联系方式:
高德地图
api@autonavi.com
百度地图
mapapi@baidu.com
腾讯地图
mapapi@vip.qq.com

warn

根据《中华人民共和国测绘法》,国内互联网地图必须至少使用GCJ02进行首次加密,不允许直接使用WGS84坐标下的地理数据,同时任何坐标系均不可转换为WGS84坐标。未经允许暴露,泄露或者提供非法转换服务的承担法律责任。

此外,所有的电子地图、导航设备都需要加入国家保密插件,以确保地图的加密和发布符合国家标准。