最近做项目,需要用到html5获取地理位置,用到函数,navigator.geolocation.getCurrentPosition,由于该方法是异步的,参照:http://stackoverflow.com/questions/21074572/get-current-position-with-html-and-use-it-with-javascript
故用变量无法直接获取到经纬度,用到localStorage,实现如下:
/****获取当前位置*********************************/
var defer = $.Deferred();
function geolocError(){
alert("您的设备不允许访问地理位置或未开启");
}
function getPositon() {
navigator.geolocation.getCurrentPosition(function (position) {
defer.resolveWith(position.coords);
}, geolocError);
return defer;
}
$(document).ready(function () {
if (navigator.geolocation) {
getPositon().done(function () {
console.info(this);
var map = "{mapx:" + this.latitude+ ",mapy:" + this.longitude + "}";
localStorage.setItem("cPosMap",map);
});
};
});
这样就可以在需要的地方使用了。