HTML5地理定位

位置定位

地理位置(Geolocation)是 HTML5 的重要特性之一,提供了确定用户位置的功能,借助这个特性能够开发基于位置信息的应用。

检测浏览器是否支持

1
2
3
4
5
6
if (navigator.geolocation) {
//console.log("浏览器支持!");
}
else {
// console.log("浏览器不支持!");
}
1
2
3
4
5
6
7
8
9
// 1、获取用户当前位置
void getCurrentPosition(onSuccess,onError,options);

// 2、持续获取当前用户位置
int watchCurrentPosition(onSuccess,onError,options);

// 3、watchId 为watchCurrentPosition返回的值
void clearWatch(watchId);
// 取消监控

示例代码

PS:也可以调用百度地图、谷歌地图、高德地图等,只需要将HTML5 Geolocation API获取到的值传入到相应的地图接口中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
<meta name="format-detection"content="telephone=no">
<title>基于浏览器的HTML5地理定位</title>
<link rel="stylesheet" href="style/style.css">
</head>
<body>
<div id="container"></div>
<div id="info"></div>
<script src="http://map.qq.com/api/js?v=2.exp" type="text/javascript"></script>
<script>
var clientWidth = document.documentElement.clientWidth,
clientHeight = document.documentElement.clientHeight;
var container = document.getElementById('container');
container.style.width = clientWidth + 'px';
container.style.height = clientHeight + 'px';

function getLocation(){

var options={
enableHighAccuracy:true, //boolean 是否要求高精度的地理信息,默认为false
maximumAge:1000 //应用程序的缓存时间
}

if(navigator.geolocation){
//浏览器支持geolocation
navigator.geolocation.getCurrentPosition(onSuccess,onError,options);

}else{
//浏览器不支持geolocation
console.log("浏览器不支持!");
}
}

//成功时
function onSuccess(position){
//返回用户位置
//经度
var longitude =position.coords.longitude;
//纬度
var latitude = position.coords.latitude;

//腾讯地图的中心地理坐标
var center = new qq.maps.LatLng(latitude, longitude);

//使用腾讯地图API
var map = new qq.maps.Map(document.getElementById("container"), {
//地图的中心地理坐标
center: center,
//初始化地图缩放级别
zoom: 16
});

//在地图中创建信息提示窗口
var infoWin = new qq.maps.InfoWindow({
map: map
});
//打开信息窗口
infoWin.open();
//设置信息窗口显示区的内容
infoWin.setContent('<div style="width:200px;padding:10px;">'+
'您在这里<br/>纬度:'+ latitude+ '<br/>经度:'+longitude);
//设置信息窗口的位置
infoWin.setPosition(center);
}


//失败时
function onError(error){
switch(error.code){
case error.PERMISSION_DENIED:
alert("用户拒绝对获取地理位置的请求");
break;

case error.POSITION_UNAVAILABLE:
alert("位置信息是不可用的");
break;

case error.TIMEOUT:
alert("请求用户地理位置超时");
break;

case error.UNKNOWN_ERROR:
alert("未知错误");
break;
}

}

window.onload=getLocation;
</script>
</body>
</html>