最近的项目中需要使用定位功能,并且获取当前位置的经纬度,查阅资料了整理了如下代码:
function locationPosition(){
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r){
var city_lat = r.latitude;
var city_lng = r.longitude;
Cookies.set("save_city_latitude",city_lat);
Cookies.set("save_city_longitude",city_lng);
// console.log(city_lat);
// console.log(city_lng);
if(this.getStatus() == BMAP_STATUS_SUCCESS){
var geoc = new BMap.Geocoder();
var pt = r.point;
geoc.getLocation(pt, function(rs){
// 获取经纬度
var addComp = rs.addressComponents;
// alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
$city =$(".head-left > a > span");
// var city_name = $.fn.cookie('location_city');
var city_name = Cookies.get('location_city');
//console.log(addComp.city);
if (city_name == addComp.city){
// TODO 定位城市和cookie值一致, 则不操作
$city.text(addComp.city);
$(".city-now").text(addComp.city);
} else {
$city.text(city_name);
if (confirm('当前位置和定位城市不一致, 是否更改成当前位置?')) {
$city.text(addComp.city);
$(".city-now").text(addComp.city);
// $.fn.cookie('location_city', addComp.city);
// Cookies.set('location_city', addComp.city);
// setLocation();
}
}
var city = Cookies.set('location_city',addComp.city);
currount_city_name = addComp.city;
getData(1,city_lat,city_lng,currount_city_name);
getArea(currount_city_name);
});
}
else {
alert('定位失败');
}
},{enableHighAccuracy: true});
}
locationPosition();
其中:
var city_lat = r.latitude;
var city_lng = r.longitude;
可以获得当前经纬度。