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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。