博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
H5 Notes:Navigator Geolocation
阅读量:7026 次
发布时间:2019-06-28

本文共 8214 字,大约阅读时间需要 27 分钟。

H5的地理位置API可以帮助我们来获取用户的地理位置,经纬度、海拔等,因此我们可以利用该API做天气应用、地图服务等。

Geolocation对象是我们获取地理位置用到的对象。

首先判断浏览器是否支持该对象

if('geolocation' in navigator){    navigator.geolocation.getCurrentPosition(success,fail,options);}else{    alert('浏览器不支持获取地理位置!');}

获取用户地理位置getCurrentPosition,该方法可以传三个参数success[, error[, options]],

获取成功就执行success回调函数并传递position参数,该参数包涵了coords对象,该对象内容如下所示

latitude :纬度longitude:经度altitude :海拔高度accuracy :精度altitudeAccuracy :海拔精度speed :外部环境的移动速度

失败则执行error回调并带上error参数,该参数有个code属性,用以指示失败的原因,如下所示:

Value    Associated constant    Description1    PERMISSION_DENIED    没有权限2    POSITION_UNAVAILABLE    位置不可用3    TIMEOUT    获取超时

,最后一个参数options是一个对象,可以有三个属性,如下所示

enableHighAccuracy: true,  是否启用高精度 timeout: 5000, 超时时间 maximumAge: 0 应用的缓存时间

下面是一个利用百度地图的API根据经纬度获取城市信息的小例子,由于百度API需要key,自己需要申请一个。

var url = "http://api.map.baidu.com/geocoder/v2/?ak=cPnGmGz3euAuMCVklyz73Qa1",    options = {         enableHighAccuracy:true,        timeout: 5000,        maximumAge: 0    };var script = document.createElement('script');script.type = "text/javascript";function dealResult(data){    alert(JSON.stringify(data));}function success(position){    var latitude = position.coords.latitude;    var longitude = position.coords.longitude;    url = url + '&location=' + latitude + ',' + longitude + '&output=json&pois=1&callback=dealResult';    script.src = url;    document.getElementsByTagName('head')[0].appendChild(script);}function fail(error){    switch(error.code){        case error.PERMISSION_DENIED:            console.log('没有获取位置信息的权限');            break;        case error.POSITION_UNAVAILABLE:            console.log('位置信息不可用');            break;        case error.TIMEOUT:            console.log('获取位置信息超时');            break;    }}if('geolocation' in navigator){    navigator.geolocation.getCurrentPosition(success,fail,options);}else{    alert('浏览器不支持获取地理位置!');}

获取到的城市信息如下所示:

{    "status": 0,    "result": {        "location": {            "lng": 114.05751299999999,            "lat": 22.64580900174618        },        "formatted_address": "广东省深圳市宝安区东环二路50",        "business": "民治,龙华,潜龙花园",        "addressComponent": {            "country": "中国",            "country_code": 0,            "province": "广东省",            "city": "深圳市",            "district": "宝安区",            "adcode": "440306",            "street": "东环二路",            "street_number": "50",            "direction": "西北",            "distance": "57"        },        "pois": [            {                "addr": "东环二路49号附近",                "cp": " ",                "direction": "附近",                "distance": "27",                "name": "靖轩龙华工业园",                "poiType": "公司企业",                "point": {                    "x": 114.05727565178965,                    "y": 22.64585864640103                },                "tag": "公司企业;园区",                "tel": "",                "uid": "51b3387b26aed6235fd4fe81",                "zip": ""            },            {                "addr": "富豪新村二巷附近",                "cp": " ",                "direction": "西南",                "distance": "200",                "name": "水斗富豪新村",                "poiType": "房地产",                "point": {                    "x": 114.058515313393,                    "y": 22.647201155091143                },                "tag": "房地产;住宅区",                "tel": "",                "uid": "141109be59d277b83686f44c",                "zip": ""            },            {                "addr": "深圳市宝安区",                "cp": " ",                "direction": "附近",                "distance": "45",                "name": "阳光蕾幼儿园",                "poiType": "教育培训",                "point": {                    "x": 114.05716785512848,                    "y": 22.646017079794483                },                "tag": "教育培训;幼儿园",                "tel": "",                "uid": "56c496efcbce5bdcbabd63e0",                "zip": ""            },            {                "addr": "深圳市龙华新区东环一路",                "cp": " ",                "direction": "南",                "distance": "75",                "name": "凤天大厦",                "poiType": "房地产",                "point": {                    "x": 114.05729361789984,                    "y": 22.646408993183947                },                "tag": "房地产;写字楼",                "tel": "",                "uid": "ec7ce450995433ffc1f1cf04",                "zip": ""            },            {                "addr": "深圳市龙岗区东环二路",                "cp": " ",                "direction": "西北",                "distance": "115",                "name": "国安村镇银行",                "poiType": "金融",                "point": {                    "x": 114.0579853131423,                    "y": 22.644949735465907                },                "tag": "金融;银行",                "tel": "",                "uid": "26739d57c4af8c836fa3ccbc",                "zip": ""            },            {                "addr": "深圳龙华新区大浪商业中心",                "cp": " ",                "direction": "西北",                "distance": "114",                "name": "华盛大厦",                "poiType": "房地产",                "point": {                    "x": 114.05802124536268,                    "y": 22.644983090103185                },                "tag": "房地产;写字楼",                "tel": "",                "uid": "63f36ce15aefa373b64f5407",                "zip": ""            },            {                "addr": "富豪新村二巷附近",                "cp": " ",                "direction": "南",                "distance": "221",                "name": "强记百货厨具行",                "poiType": "购物",                "point": {                    "x": 114.05808412674835,                    "y": 22.647576388065445                },                "tag": "购物;家居建材",                "tel": "",                "uid": "7bf3c226751022e60a5cb36f",                "zip": ""            },            {                "addr": "油松东环一路一号一楼好荟品旗舰店(近和谐修车)",                "cp": " ",                "direction": "东南",                "distance": "251",                "name": "好荟品深圳旗舰店",                "poiType": "美食",                "point": {                    "x": 114.05573056631299,                    "y": 22.647101092789494                },                "tag": "美食;外国餐厅",                "tel": "",                "uid": "54ebc6e9fe4c7610095cb3d4",                "zip": ""            },            {                "addr": "宝安区东环二路蓝调酒吧旁",                "cp": " ",                "direction": "西北",                "distance": "284",                "name": "水斗星幼儿园",                "poiType": "教育培训",                "point": {                    "x": 114.05889260170707,                    "y": 22.64380733419285                },                "tag": "教育培训;幼儿园",                "tel": "",                "uid": "0727de0c15a3e427077ce8a9",                "zip": ""            },            {                "addr": "龙华新区东环一路1号",                "cp": " ",                "direction": "东南",                "distance": "217",                "name": "一汽大众(龙华安进誉隆店)",                "poiType": "汽车服务",                "point": {                    "x": 114.05583836297416,                    "y": 22.646742535602986                },                "tag": "汽车服务;汽车销售",                "tel": "",                "uid": "7a3c6d6322de3dce11882495",                "zip": ""            }        ],        "poiRegions": [],        "sematic_description": "靖轩龙华工业园附近27米",        "cityCode": 340    }}

Geolocation还有两个方法watchPosition和clearWatch,前者可以用来检测用户位置的改变,只要改变便会调用该函数注册的回调函数,并返回一个watchId,后者用于清除前者注册的事件处理函数。

watchPosition的参数和getCurrentPosition一致,使用方法如下

id = navigator.geolocation.watchPosition(success, error, options);

clearWatch使用方法如下

navigator.geolocation.clearWatch(id);

 

 

Value Associated constant Description
1 PERMISSION_DENIED The acquisition of the geolocation information failed because the page didn't have the permission to do it.
2 POSITION_UNAVAILABLE The acquisition of the geolocation failed because at least one internal source of position returned an internal error.
3 TIMEOUT The time allowed to acquire the geolocation, defined by information was reached before the information was obtained.

转载于:https://www.cnblogs.com/zmxmumu/p/6073945.html

你可能感兴趣的文章
一道简单的数学题
查看>>
为什么 执行typeof null时会返回字符串“object”?
查看>>
JavaScript关于闭包的理解和实例
查看>>
jquery-ui-widget
查看>>
VC Error spawning cl.exe
查看>>
IIS连接数据库:数据库连接出错,请检查连接字串
查看>>
centos7救援模式--rescue模式
查看>>
C++ 输出到文本文件
查看>>
sql Lloader
查看>>
使用python学习【机器学习】需要安装的库~
查看>>
第一次作业+105032014098
查看>>
Codeforces 832B: Petya and Exam
查看>>
axios链接带参数_VUE升级(全面解析vuecil3/vuecil4的vue.config.js等常用配置,配置axios)...
查看>>
vue warning如何去掉_详解vue组件三大核心概念
查看>>
qt mysql md5加密_Qt 给密码进行MD5加密
查看>>
用java swing做连连看_java基于swing实现的连连看代码
查看>>
java关键字定义字符变量_Java 关键字和标识符
查看>>
java并发编程核心方法与框架_Java并发编程核心方法与框架-CompletionService的使用...
查看>>
java开源api网关_常用的几个开源 API网关管理系统
查看>>
java 数据结构 快速入门_Java 数据结构
查看>>