复制代码代码如下:
/**
* 以下为html5代码,获取地理位置
*/
function getlocation() {
//检查浏览器是否支持地理位置获取
if (navigator.geolocation) {
//若支持地理位置获取,成功调用showposition(),失败调用showerror
// alert("正在努力获取位置...");
var config = { enablehighaccuracy: true, timeout: 5000, maximumage: 30000 };
navigator.geolocation.getcurrentposition(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=c93b5178d7a8ebdb830b9b557abce78b" +
"&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("定位失败,用户拒绝请求地理定位");
//x.innerhtml = "user denied the request for geolocation.[用户拒绝请求地理定位]"
break;
case error.position_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';
}