日期:2014-05-17  浏览次数:20650 次

HTML5 Geolocation小结

HTML5中 Geolocation主要包括2个重要函数。

1、获取经纬度函数:

function getMyLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(displayLocation,displayError);
}else{
alert("Oops,no geolocation support!");
}
}

其中displayLocation,displayError分别表示获取成功handler以及获取失败handler。

2、计算2坐标点间地表距离:

/**
* 计算2点间距离
*/
function computeDistance(startCoords, destCoords) {
var startLatRads = degreesToRadians(startCoords.latitude);
var startLongRads = degreesToRadians(startCoords.longitude);
var destLatRads = degreesToRadians(destCoords.latitude);
var destLongRads = degreesToRadians(destCoords.longitude);
var Radius = 6371; // radius of the Earth in km
var distance = Math.acos(Math.sin(startLatRads) * Math.sin(destLatRads) +
Math.cos(startLatRads) * Math.cos(destLatRads) *
Math.cos(startLongRads - destLongRads)) * Radius;
return distance;
}

function degreesToRadians(degrees) {
var radians = (degrees * Math.PI)/180;
return radians;
}

?

3、开启实时位置监控及取消:

function watchLocation() {
watchId = navigator.geolocation.watchPosition(
displayLocation,
displayError,
{enableHighAccuracy: true, timeout:3000});
}

function clearWatch() {
if (watchId) {
navigator.geolocation.clearWatch(watchId);
watchId = null;
}
}

?


?

需要注意的几项事宜:

1、你无法控制浏览器选择何种途径确定你的位置。

2、当开启位置跟踪时,你无法控制浏览器刷新页面的时间间隔。

3、计算两点距离时,计算结果为球面距离不是实际距离(考虑到城市马路规划)

4、当你保持不动的前提下,第一次加载页面时发现位置信息变化好多次。因为浏览器会自动根据几种不同的算法判断当前位置并最终给出精度最高的数据。