cordova+vue+webapp使用html5获取地理位置的方法

2020-06-14 06:26:36易采站长站整理

4.使用Geolocation.getCurrentPosition()注意事项:

本地项目中在Chrome浏览器中运行时,无法获取到经纬度信息,原因是Chrome已不再支持非安全域的
浏览器定位请求,只有在https下才可使用定位。在IE、Eage、Firefox下亲测可以获取的经纬度信息。获取到的GPS经纬度信息在百度地图展示位置会与实际位置不同,是因为百度对外接口的坐标系为BD09
坐标系,并不是GPS采集的真实经纬度,在使用百度地图JavaScript API服务前,需先将非百度坐标通过坐标转换接口转换成百度坐标。(转换方法详见下文)

5.使用Geolocation.getCurrentPosition()获取经纬度信息,并转换为百度坐标并进行逆地址解析:

以Vue项目为例,首先根目录index.html中引入百度API文件,如下图:

获取位置,标记marker并进行逆地址解析代码如下:


// 1 查询当前位置信息
getPosition() {
navigator.geolocation.getCurrentPosition(this.getPositionSuccess, this.getPositionError, {"enableHighAccuracy": true, "timeout": 5000, "maximumAge": 5000})
},
// 1-1 查询当前位置信息成功
getPositionSuccess(position) {
this.latitude = String(position.coords.latitude)
this.longitude = String(position.coords.longitude)
let ggPoint = new BMap.Point(this.longitude, this.latitude)
let pointArr = [] pointArr.push(ggPoint)
let convertor = new BMap.Convertor()
// 坐标转换
convertor.translate(pointArr, 1, 5, this.translateCallback)
},
// 1-2 查询当前位置信息失败
getPositionError(error) {
this.$toast({
message: `获取地理位置失败请重试~`,
duration: 1000
})
},
// 坐标转换回调
translateCallback(data) {
if (data.status === 0) {
// 在地图上标注marker
let marker = new BMap.Marker(data.points[0])
map.addOverlay(marker)
map.panTo(data.points[0])
// 逆地址解析
let myGeo = new BMap.Geocoder()
let that = this
myGeo.getLocation(data.points[0], function(result){
if (result){
// 获取逆地址解析结果
that.clockSite = result.address
}
})
}
},

坐标转换convertor.translate()方法说明:

语法:


convertor.translate(coords, from, to, fn)

参数:

coords:需转换的源坐标
from: 源坐标类型 详见:[类型详情][4] to: 目标坐标类型 详见:[类型详情][5] fn: 转换结果回调