首頁  >  文章  >  web前端  >  簡單html5程式碼取得地理位置_html5教學技巧

簡單html5程式碼取得地理位置_html5教學技巧

WBOY
WBOY原創
2016-05-16 15:48:181322瀏覽
 

複製代碼
代碼如下:

/**
* 以下為html5程式碼,取得地理位置
*/
function getLocation() {
//檢查瀏覽器是否支援地理位置取得
if (navigator.geolocation) {
//若支援地理位置取得,成功呼叫showPosition(),失敗呼叫showError
// alert("正在努力取得位置...");
var config = { enableHighAccuracy: true, timeout: 5000, maximumAge: 30000 };
navigator.rentgeo. showPosition, showError, config);
} else {
//alert("Geolocation is not supported by this browser.");
alert("定位失敗,使用者已停用位置取得權限");
}
}
/**
* 取得位址位置成功
*/
function showPosition(position) {
//取得經度緯度
var x = position.coords.latitude; var y = position.coords.longitude;
//配置Baidu Geocoding API
var url = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b57?ak=C93b5178d7a8ebdb830b9b570 "&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 "]位址位置取得失敗,請手動選取位址");
}
});
}
/**
* 取得位址位置失敗[暫不處理]
*/
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert
alert ("定位失敗,使用者拒絕要求地理定位");
//x.innerHTML = "User denied the request for Geolocation.[使用者拒絕要求地理定位]"
break;
case error.POSITION_UNAVAILABLETION_UNAVAILABLE :
alert("定位失敗,位置資訊是無法使用");
//x.innerHTML = "Location information is unavailable.[位置資訊是無法使用]"
break;
case error.TIMEOUT:
alert("定位失敗,請求取得使用者位置逾時");
//x.innerHTML = "The request to get user location timed out.[請求取得使用者位置逾時]"
break;
case error.UNKNOWN_ERROR:
alert("定位失敗,定位系統失效");
//x.innerHTML = "An unknown error occurred.[未知錯誤]"
break ;
}
}
/**
* 設定位址
*/
function setAddress(json) {
var position = document.getElementById(""txtPosition");
// 省
var province = json.province;
//市
var city = json.city;
//區
var district = json.district;
province = province.replace ('市', '');
position.value = province "," city "," district;
position.style.color = 'black';
}

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn