html5中地理位置定位api接口开发应用小结

2019-01-28 19:34:38王旭


复制代码

function requestPosition() {
if (nav == null) {
nav = window.navigator;
}
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
geoloc.getCurrentPosition(successCallback);
}
else {
alert("Geolocation API is not supported in your browser");
}
}
else {
alert("Navigator is not found");
}
}

当获得地理位置成功后,会产生一个回调方法了,处理返回的结果,

复制代码

function setLocation(val, e) {
document.getElementById(e).value = val;
}
function successCallback(position)
{
setLocation(position.coords.latitude, "latitude"); setLocation(position.coords.longitude, "longitude");
}

3、一个很常见的问题,是如何跟踪用户不断变化的地理位置,这里小结下其中用到的两个api
1 watchPosition
例子如下:

复制代码

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 API is not supported in your browser");
}
} else {
alert("Navigator is not found");
}
}

然后在successCallback中,就可以设置显示最新的地理位置:

复制代码

function successCallback(position){
setText(position.coords.latitude, "latitude"); setText(position.coords.longitude, "longitude");
}

如果不希望实时跟踪,则可以取消之:
function clearWatch(watchID) {
window.navigator.geolocation.clearWatch(watchID);
}
4、如何处理异常
当遇到异常时,可以捕捉之:

复制代码

if (geoloc != null) {
geoloc.getCurrentPosition(successCallback, errorCallback);
}
function errorCallback(error) {
var message = "";
switch (error.code) {
case error.PERMISSION_DENIED:
message = "This website does not have permission to use "
+ "the Geolocation API";
break;
case error.POSITION_UNAVAILABLE:
message = "The current position could not be determined.";
break;
case error.PERMISSION_DENIED_TIMEOUT:
message = "The current position could not be determined "
+ "within the specified timeout period.";
break;
}
if (message == "") {
var strErrorCode = error.code.toString();
message = "The position could not be determined due to "
+ "an unknown error (Code: " + strErrorCode + ").";
}
alert(message);
}