地理定位API有一个watchPosition方法,这个方法会监视你的移动,并在位置改变时项你报告位置。
实验
我们更新htm,增加一个表单和两个按钮:一个用来监视你的位置,另一个用来停止监视
<form>
<input type="button" id="watch" value="Watch me">
<input type="button" id="clearWatch" value="Clear watch">
</form>
<div id="location">
your location will go here
</div>
<div id="distance">
Distance from ...
</div>
现在需要为2个按钮增加点击处理程序:watchLocation对应监视按钮,clearWatch对应清除按钮:
function getMyLocation(){
// 如果navigator.geolocation对象存在,说明浏览器支持这个API
if (navigator.geolocation) {
var watchButton = document.getElementById("watch");
watchButton.onclick = watchLocation; // 调用watchLocation启动监视
var clearWatchButton = document.getElementById("clearWatch");
clearWatchButton.onclick = clearWatch; // 调用clearWatch停止监视
}else{
alert("你的浏览器不支持地理定位");
}
}
编写watchLocation处理程序
用户点击监视按钮时,开始跟踪他们的位置。使用navigator.geolocation.watchPosition方法开始监视他们的位置。这个方法有两个参数,一个成功处理程序一个错误处理程序。它还会返回一个watchId,可以在任何时候使用这个id取消监视
// 在文件最上面增加watchId作为全局变量,以后还需要这个变量清除监视
var watchId = null;
function watchLocation(){
watchId = navigator.geolocation.watchPosition(displayLocation,displayError);
}
编写clearWatch处理程序
// 清除监视
function clearWatch(){
if (watchId) {
// 调用geolocation.clearWatch方法,传入这个watchId,这会停止监视
navigator.geolocation.clearWatch(watchId);
watchId = null;
}
}
最后全部代码如下:
<!DOCTYPE html>
<html>
<head>
<title>地理定位跟踪</title>
</head>
<body>
<form>
<input type="button" id="watch" value="Watch me">
<input type="button" id="clearWatch" value="Clear watch">
</form>
<div id="location">
your location will go here
</div>
<div id="distance">
Distance from ...
</div>
</body>
<script type="text/javascript">
window.onload = getMyLocation;
function getMyLocation(){
// 如果navigator.geolocation对象存在,说明浏览器支持这个API
if (navigator.geolocation) {
var watchButton = document.getElementById("watch");
watchButton.onclick = watchLocation; // 调用watchLocation启动监视
var clearWatchButton = document.getElementById("clearWatch");
clearWatchButton.onclick = clearWatch; // 调用clearWatch停止监视
}else{
alert("你的浏览器不支持地理定位");
}
}
// 在文件最上面增加watchId作为全局变量,以后还需要这个变量清除监视
var watchId = null;
function watchLocation(){
watchId = navigator.geolocation.watchPosition(displayLocation,displayError);
}
// 清除监视
function clearWatch(){
if (watchId) {
// 调用geolocation.clearWatch方法,传入这个watchId,这会停止监视
navigator.geolocation.clearWatch(watchId);
watchId = null;
}
}
// 成功处理程序
function displayLocation(position){
// 从position.coords得到纬度和经度
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
div.innerHTML = "你在纬度: " + latitude +",经度: " + longitude;
}
// 错误处理程序
function displayError(error){
var errorTypes = {
0: "UnKnow error",
1: "Permission denied by user",
2: "Position is no available",
3: "Request timed out"
};
var errorMessage = errorTypes[error.code];
if (error.code == 0 || error.code == 2) {
errorMessage = errorMessage + "" + error.message;
}
var div = document.getElementById("location");
div.innerHTML = errorMessage;
}
</script>
</html>