突袭HTML5之Javascript API扩展2—地理信息服务及地理位置API学习

2019-01-28 19:13:23王冬梅

开启/取消持续定位
使用navigator.geolocation的watchPosition()方法可以定期轮询用户的位置,查看用户的位置是否发生改变。这个方法有三个参数:这三个参数和getCurrentPosition()方法一样,一个成功后的回调,一个失败后的回调,和一个获取位置信息的选项;这个方法有一个返回值watchID,用于取消持续定位。
使用navigator.geolocation的clearWatch()方法可以终止正在进行的watchPosition(),该方法只带一个参数watchID。
看下面的例子:

复制代码

<!DOCTYPE html>
<html>
<head>
<title>Geolocation API Example: Listening for Location Updates</title>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script type="text/javascript">
function setText(val, e) {
document.getElementById(e).value = val;
}
var nav = null;
var watchID;
function listenForPositionUpdates() {
if (nav == null) {
nav = window.navigator;
}
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
watchID = geoloc.watchPosition(successCallback);
}
else {
alert("geolocation not supported");
}
}
else {
alert("Navigator not found");
}
}
function clearWatch(watchID) {
window.navigator.geolocation.clearWatch(watchID);
}
function successCallback(position)
{
setText(position.coords.latitude, "latitude");
setText(position.coords.longitude, "longitude");
}
</script>
</head>
<body>
<label for="latitude">Latitude: </label><input id="latitude" />

<label for="longitude">Longitude: </label><input id="longitude" />

<input type="button" value="Watch Latitude and Longitude" onclick="listenForPositionUpdates()" />
<input type="button" value="Clear watch" onclick="clearWatch()" />
</body>
</html>

实用参考:
官方文档:http://www.w3schools.com/html5/html5_geolocation.asp
易采站长站:https://www.jb51.net/w3school/html5/
微软帮助:http://msdn.microsoft.com/zh-cn/library/gg589502(v=vs.85)
百度地图API:http://dev.baidu.com/wiki/static/index.htm