1.检测浏览器是否支持地理位置API
//检测浏览器是否支持地理位置API(navigator.geolocation)
if (navigator.geolocation) {
}else{
alert("Your browser does not support Geolocation!");
}
2.地理位置API支持的方法getCurrentPosition
getCurrentPosition(successHandler,errorHandler,options)
参数:
1.successHandler是函数,成功确定位置则调用这个函数
2.errorHandler是函数,若不能成功确定位置则调用此函数,可选
3.options参数允许定制地理定位方法,可选
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successHandler,errorHandler,options)
}else{
alert("Your browser does not support Geolocation!");
}
//地理位置API传入成功处理程序的对象POSITION
function successHandler(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
}
//地理位置API会向它传入一个错误
function errorHandler(error){
switch(error.code) {
case error.TIMEOUT:
showError("A timeout occured! Please try again!");
break;
case error.POSITION_UNAVAILABLE:
showError('We can\'t detect your location. Sorry!');
break;
case error.PERMISSION_DENIED:
showError('Please allow geolocation access for this to work.');
break;
case error.UNKNOWN_ERROR:
showError('An unknown error occured!');
break;
}
}
//timeout在这个时间内没找到位置,就会调用错误处理程序
var options = {
enableHighAccuracy:false,
timeout:Infinity