var city;
function getCity() {
//判斷瀏覽器是否支持geolocation
if(navigator.geolocation){
// getCurrentPosition支持三個參數
// getSuccess是執行成功的回調函數
// getError是失敗的回調函數
// getOptions是一個對象,用于設置getCurrentPosition的參數
// 后兩個不是必要參數
var getOptions = {
//是否使用高精度設備,如GPS。默認是true
enableHighAccuracy:true,
//超時時間,單位毫秒,默認為0
timeout:50000,
//使用設置時間內的緩存數據,單位毫秒
//默認為0,即始終請求新數據
//如設為Infinity,則始終使用緩存數據
maximumAge:0
};
//成功回調
function getSuccess(position){
// getCurrentPosition執行成功后,會把getSuccess傳一個position對象
// position有兩個屬性,coords和timeStamp
// coords是一個對象,包含了地理位置數據
console.log(position.coords.latitude);
var gg_lon = position.coords.longitude;
var gg_lat =? position.coords.latitude;
// 估算的經度
console.log(position.coords.longitude);
// 所得經度和緯度的估算精度,以米為單位
console.log(position.coords.accuracy);
var gc = new BMap.Geocoder();
var pointAdd = new BMap.Point(gg_lon, gg_lat);
gc.getLocation(pointAdd, function(rs){
// 百度地圖解析城市名
city = rs.addressComponents.city;
alert(city)
localStorage.clear();
//或者任何你想要的其他信息
// if(localStorage){
//? ? localStorage.clear();
//? ? localStorage.setItem('mycity',city)
//? ? }
})
}
//失敗回調
function getError(error){
// 執行失敗的回調函數,會接受一個error對象作為參數
// error擁有一個code屬性和三個常量屬性TIMEOUT、PERMISSION_DENIED、POSITION_UNAVAILABLE
// 執行失敗時,code屬性會指向三個常量中的一個,從而指明錯誤原因
switch(error.code){
case error.TIMEOUT:
console.log('超時');
break;
case error.PERMISSION_DENIED:
console.log('用戶拒絕提供地理位置');
break;
case error.POSITION_UNAVAILABLE:
console.log('地理位置不可用');
break;
default:
break;
}
}
navigator.geolocation.getCurrentPosition(getSuccess, getError, getOptions);
// watchPosition方法一樣可以設置三個參數
// 使用方法和getCurrentPosition方法一致,只是執行效果不同。
// getCurrentPosition只執行一次
// watchPosition只要設備位置發生變化,就會執行
var watcher_id = navigator.geolocation.watchPosition(getSuccess, getError, getOptions);
//clearwatch用于終止watchPosition方法
navigator.geolocation.clearWatch(watcher_id);
}
}
getCity();