這篇文章主要介紹了使用html5代碼來獲取地理位置,具體實(shí)現(xiàn)代碼如下并附有截圖,需要的朋友可以參考下
代碼如下:
/**
* 以下為html5代碼,獲取地理位置
*/
function getLocation() {
//檢查瀏覽器是否支持地理位置獲取
if (navigator.geolocation) {
//若支持地理位置獲取,成功調(diào)用showPosition(),失敗調(diào)用showError
// alert("正在努力獲取位置...");
var config = { enableHighAccuracy: true, timeout: 5000, maximumAge: 30000 };
navigator.geolocation.getCurrentPosition(showPosition, showError, config);
} else {
//alert("Geolocation is not supported by this browser.");
alert("定位失敗,用戶已禁用位置獲取權(quán)限");
}
}
/**
* 獲取地址位置成功
*/
function showPosition(position) {
//獲得經(jīng)度緯度
var x = position.coords.latitude;
var y = position.coords.longitude;
//配置Baidu Geocoding API
var url = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b" +
"&callback=renderReverse" +
"&location=" + x + "," + y +
"&output=json" +
"&pois=0";
$.ajax({
type: "GET",
dataType: "jsonp",
url: url,
success: function (json) {
if (json == null || typeof (json) == "undefined") {
return;
}
if (json.status != "0") {
return;
}
setAddress(json.result.addressComponent);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("[x:" + x + ",y:" + y + "]地址位置獲取失敗,請(qǐng)手動(dòng)選擇地址");
}
});
}
/**
* 獲取地址位置失敗[暫不處理]
*/
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("定位失敗,用戶拒絕請(qǐng)求地理定位");
//x.innerHTML = "User denied the request for Geolocation.[用戶拒絕請(qǐng)求地理定位]"
break;
case error.POSITION_UNAVAILABLE:
alert("定位失敗,位置信息是不可用");
//x.innerHTML = "Location information is unavailable.[位置信息是不可用]"
break;
case error.TIMEOUT:
alert("定位失敗,請(qǐng)求獲取用戶位置超時(shí)");
//x.innerHTML = "The request to get user location timed out.[請(qǐng)求獲取用戶位置超時(shí)]"
break;
case error.UNKNOWN_ERROR:
alert("定位失敗,定位系統(tǒng)失效");
//x.innerHTML = "An unknown error occurred.[未知錯(cuò)誤]"
break;
}
}
/**
* 設(shè)置地址
*/
function setAddress(json) {
var position = document.getElementById("txtPosition");
//省
var province = json.province;
//市
var city = json.city;
//區(qū)
var district = json.district;
province = province.replace('市', '');
position.value = province + "," + city + "," + district;
position.style.color = 'black';
}