1.在html5中使用geolocation.getcurrentposition()方法来获取地理位置。
语法:
navigator.geolocation.getcurrentposition(success, error, options)
参数:
2.success - 成功得到位置信息时的回调函数
navigator.geolocation.getcurrentposition(function(position)) {
// 获取成功时的的处理
//参数position是地理位置对象
}
position中返回的信息如下图:

3.error - 获取位置信息失败时的回调函数
navigator.geolocation.getcurrentposition(function(position){
// 获取成功时的的处理;
//参数position是地理位置对象
},function(error)) {
// 获取失败时的的处理;
}
error中返回的信息如下图

code属性有以下值:
- 1 地理位置信息的获取失败,因为该页面没有获取地理位置信息的权限。
- 2 地理位置获取失败,因为至少有一个内部位置源返回一个内部错误。
- 3 获取地理位置超时,通过定义positionoptions.timeout 来设置获取地理位置的超时时长。
message 返回一个开发者可以理解的 domstring 来描述错误的详细信息。
4.使用geolocation.getcurrentposition()注意事项:
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)
参数:
6.使用cordova vue开发webapp中定位解决方法:
在cordova中安装geolocation插件后,方可在生成的app中获取到地理位置信息,运行如下命令即可:
cordova plugin add cordova-plugin-geolocation
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。