H5之后自带有获取地位功能,但是只能在有定位功能的设备上使用,例如手机与平板,
一般电脑不具备GPS定位,即使允许访问地理位置,失准严重
HTML5 Geolocation API 用于获得用户的地理位置。
鉴于该特性可能侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的。
Navigator 对象包含有关浏览器的信息。
使用 getCurrentPosition() 方法来获得用户的位置。
var x=document.getElementById("demo");
function getLocation()
{
//检测是否支持地理定位
if (navigator.geolocation){
//如果 getCurrentPosition() 运行成功,则向参数showPosition中规定的函数返回一个 coordinates 对象
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else{
alert("浏览器不支持地理定位。");
}
}
function showPosition(position){
var lat = position.coords.latitude; //纬度
var lag = position.coords.longitude; //经度
alert('纬度:'+lat+',经度:'+lag);
}
function showError(error){
switch(error.code) {
case error.PERMISSION_DENIED:
alert("定位失败,用户拒绝请求地理定位");
break;
case error.POSITION_UNAVAILABLE:
alert("定位失败,位置信息是不可用");
break;
case error.TIMEOUT:
alert("定位失败,请求获取用户位置超时");
break;
case error.UNKNOWN_ERROR:
alert("定位失败,定位系统失效");
break;
}
}