这次碰到的需求是:
根据IP定位后 显示具体在哪个地方,那么逻辑可以总结为:
Step1 根据IP定位得到具体的坐标点
Step2 根据坐标点来得到真实的地理位置
实现:
$.ajax({
type: "post",
url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=你的key',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
var location = result.location; //这里获取到坐标值
_map.panTo(location);
var strlocation = location.lat+','+location.lng;
getAddrFromLatLng(strlocation,function(address){
//这里的address就是转换后的真实地址 某某市某某区某某街道
}
});
getAddrFromLatLng的实现
/*
*功能:使用Google地图的API 根据坐标得到具体的位置
*参数:坐标,GoogleKey
*返回值:字符串 位置
*/
function getAddrFromLatLng(latlng,callback){
var pos = latlng;
$.ajax({
url: "https://maps.googleapis.com/maps/api/geocode/json?latlng="+pos+"&key="+GoogleKey,
type: "POST",
data:{},
dataType: "json",
success: function(data){
var status = data["status"];
var addr;
if (status === 'OK'){
addr = data["results"][0].formatted_address;
}else{
addr = "";
}
callback(addr);
},
error:function(err){
console.log(err.statusText);
console.log('异常');
}
});
}
通过这种方式就可以根据坐标得到真实的地理位置。