//根据经纬度定位用户所在城市
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition, showErr);
}
function showPosition(position){
//alert(position.coords.latitude+','+position.coords.longitude);
// ak = appkey 访问次数流量有限制
var xy = window.location.protocol.split(':')[0] === 'https' ? 'https' : 'http';
$.getJSON(xy+'://api.map.baidu.com/geocoder/v2/?location='+position.coords.latitude+','+position.coords.longitude+'&output=json&pois=1&ak=您的ak', function(res){
//addressComponent => {city: "广州市", district: "天河区", province: "广东省", street: "广州大道", street_number: "中922号-之101-128"}
console.log(res.result.addressComponent.city);
})
}
function showErr(error){
var result;
switch(error.code)
{
case error.PERMISSION_DENIED:
result="User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
result="Location information is unavailable.";
break;
case error.TIMEOUT:
result="The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
result="An unknown error occurred.";
break;
}
alert(result);
}
//百度API : http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
转载于:https://www.cnblogs.com/mbyund/p/7151384.html