geo.js:
var GPS = {
// 定位
geolocation: function(okFn, errFn){
var me = this;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(r){
if(!r || !r.coords){
typeof errFn == "function" && errFn(err);
return;
}
console.log(r);
var lat = r.coords.latitude;
var lon = r.coords.longitude;
var url = 'https://api.map.baidu.com/geocoder/v2/?coordtype=*******&ak=*********&callback=_callback&location=' + (lat + ',' + lon) + '&output=json&pois=0';
$.ajax({
url: url,
type: "POST",
dataType: 'jsonp',
success: function(res) {
typeof okFn == "function" && okFn(res.result);
console.log('geo success')
},
error: function(err){
console.log('geo error')
typeof errFn == "function" && errFn(err);
}
});
}, function() {
location.assign('city.html' + location.search);
});
}else{
typeof errFn == "function" && errFn(err);
}
var obj = JSON.parse(window.sessionStorage.getItem("cityItem"));
console.log(obj);
}
}
export default GPS;
调用:
GPS.geolocation(
function (res) {
//successFun
console.log('baidudingwei', res);
let _province = res.addressComponent.province,
_city = res.addressComponent.city;
//特殊城市规则化
let filterProvince = ["上海市", "北京市", "天津市", "重庆市"];
if (filterProvince.indexOf(_province) != -1) {
_province = _province.substring(0, _province.length - 1);
}
},
function () {
//errFun
}
);