HTML5浏览器返回地理位置信息
浏览器借助百度地图API返回地理位置信息
1、判断设备是否支持地理位置
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "该浏览器不支持获取地理位置。";
}
}
2、获取地理位置经纬度
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
3、通过百度将经纬度转化成地理位置信息
function showPosition(position) {
var latlon = position.coords.latitude+','+position.coords.longitude;
//baidu
var url = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&callback=renderReverse&location="+latlon+"&output=json&pois=0";
$.ajax({
type: "GET",
dataType: "jsonp",
url: url,
beforeSend: function(){
$("#demo").html('正在定位...');
},
success: function (json) {
if(json.status==0){
$("#demo").html(json.result.addressComponent.city);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#demo").html(latlon+"地址位置获取失败");
}
});
}
4、百度地图API返回的json示例:
{
"status": 0,
"result": {
"location": {
"lng": 116.30235223778,
"lat": 39.979262964719
},
"formatted_address": "北京市海淀区巴沟村87号",
"business": "万柳,苏州桥,万泉河",
"addressComponent": {
"adcode": "110108",
"city": "北京市",
"country": "中国",
"direction": "东南",
"distance": "59",
"district": "海淀区",
"province": "北京市",
"street": "巴沟村",
"street_number": "87号",
"country_code": 0
},
"poiRegions": [],
"sematic_description": "北京华联(万柳购物中心)东69米",
"cityCode": 131
}
}