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    Description
1 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 byPositionOptions.timeout information was reached before the information was obtained.

H5 Notes:Navigator Geolocation的更多相关文章

  1. H5 Notes:PostMessage Cross-Origin Communication

    Javascript中要实现跨域通信,主要有window.name,jsonp,document.domain,cors等方法.不过在H5中有一种新的方法postMessage可以安全实现跨域通信,并 ...

  2. H5学习系列之Geolocation API

    获取位置信息途径: 1.IP地址地理定位数据 2.GPS地理定位数据 3.WI-FI地理定位数据 4.手机地理定位数据 无废话直接上重点:navigator.geolocation对象就是获取地理位置 ...

  3. JS新API标准 地理定位(navigator.geolocation)/////////zzzzzzzzzzz

    在新的API标准中,可以通过navigator.geolocation来获取设备的当前位置,返回一个位置对象,用户可以从这个对象中得到一些经纬度的相关信息. navigator.geolocation ...

  4. JS新API标准 地理定位(navigator.geolocation)

    在新的API标准中,可以通过navigator.geolocation来获取设备的当前位置,返回一个位置对象,用户可以从这个对象中得到一些经纬度的相关信息. navigator.geolocation ...

  5. 使用navigator.geolocation来获取用户的地理位置信息

    使用navigator.geolocation来获取用户的地理位置信息 W3C 中新添加了一个名为 Geolocation的 API 规范,Geoloaction API的作用就是通过浏览器获取用户的 ...

  6. js定位navigator.geolocation

    一.简介 html5为window.navigator提供了geolocation属性,用于获取基于浏览器的当前用户地理位置. window.navigator.geolocation提供了3个方法分 ...

  7. js地理定位对象 navigator.geolocation

    浏览器信息的存储对象(navigator): 在新的API标准中,可以通过navigator.geolocation来获取设备的当前位置,返回一个位置对象,用户可以从这个对象中得到一些经纬度的相关信息 ...

  8. 【H5】 经纬度位置获取navigator.geolocation.getCurrentPosition

    navigator.geolocation.getCurrentPosition(function(){})经度 : coords.longitude 纬度 : coords.latitude 准确度 ...

  9. HTML5编程之旅系列一:HTML5 Geolocation 初探

    让我们假设这样一个场景,有一个web应用程序,它可以向用户提供附近不远处某商场的打折优惠信息.使用HTML5 Geolocation API(地理定位 API),可以请求用户共享他们的位置信息. HT ...

随机推荐

  1. [PHP内核探索]PHP中的哈希表

    在PHP内核中,其中一个很重要的数据结构就是HashTable.我们常用的数组,在内核中就是用HashTable来实现.那么,PHP的HashTable是怎么实现的呢?最近在看HashTable的数据 ...

  2. LeetCode: 3Sum

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  3. nodejs创建http服务器

    之前有简单介绍nodejs的一篇文章(http://www.cnblogs.com/fangsmile/p/6226044.html) HTTP服务器 Node内建有一个模块,利用它可以很容易创建基本 ...

  4. jQuery之Deferred源码剖析

    一.前言 大约在夏季,我们谈过ES6的Promise(详见here),其实在ES6前jQuery早就有了Promise,也就是我们所知道的Deferred对象,宗旨当然也和ES6的Promise一样, ...

  5. python与c互相调用

    虽然python开发效率很高,但作为脚本语言,其性能不高,所以为了兼顾开发效率和性能,通常把性能要求高的模块用c或c++来实现或者在c或c++中运行python脚本来处理逻辑,前者通常是python中 ...

  6. PHP类和对象之重载

    PHP中的重载指的是动态的创建属性与方法,是通过魔术方法来实现的.属性的重载通过__set,__get,__isset,__unset来分别实现对不存在属性的赋值.读取.判断属性是否设置.销毁属性. ...

  7. 编写高质量代码:改善Java程序的151个建议(第8章:多线程和并发___建议126~128)

    建议126:适时选择不同的线程池来实现 Java的线程池实现从根本上来说只有两个:ThreadPoolExecutor类和ScheduledThreadPoolExecutor类,这两个类还是父子关系 ...

  8. C#各种同步方法 lock, Monitor,Mutex, Semaphore, Interlocked, ReaderWriterLock,AutoResetEvent, ManualResetEvent

    看下组织结构: System.Object System.MarshalByRefObject System.Threading.WaitHandle System.Threading.Mutex S ...

  9. c++ pair 使用

    1. 包含头文件: #include <utility> 2. pair 的操作: pair<T1,T2> p; pair<T1,T2> p(v1,v2); pai ...

  10. 微信小程序开发日记——高仿知乎日报(上)

    本人对知乎日报是情有独钟,看我的博客和github就知道了,写了几个不同技术类型的知乎日报APP 要做微信小程序首先要对html,css,js有一定的基础,还有对微信小程序的API也要非常熟悉 我将该 ...