最近做一個公眾號頁面開發(fā),需要獲取用戶地理位置信息,獲取到經(jīng)緯度后,找了很多地方都沒找到騰訊地圖將經(jīng)緯度轉(zhuǎn)換成具體位置的方法,所以就只能調(diào)用百度地圖api轉(zhuǎn)一次,現(xiàn)在將其中部分代碼貼在上面,以便下次使用:
首先需要去百度api申請秘鑰,鏈接:獲取百度api秘鑰
$.ajax({
method:"GET",
url:url,//替換網(wǎng)址,xxx根據(jù)自己jssdk文件位置修改
success:function(res) {
alert(res.code);
if(res.code==200){
//將簽名轉(zhuǎn)換為utf-8
wx.config({
debug:true,//調(diào)式模式,設(shè)置為ture后會直接在網(wǎng)頁上彈出調(diào)試信息,用于排查問題
appId:res.data.appId,
timestamp:res.data.timestamp,
nonceStr:res.data.nonceStr,
signature:res.data.signature,
jsApiList: [//所有要調(diào)用的API都要加到這個列表中
'checkJsApi',
'openLocation',
'getLocation'
]
});
wx.ready(function() {
wx.checkJsApi({
jsApiList: [
'getLocation'
],
success:function(res) {
// alert(JSON.stringify(res));
// alert(JSON.stringify(res.checkResult.getLocation));
if(res.checkResult.getLocation==false) {
alert('你的微信版本太低,不支持微信JS接口,請升級到最新的微信版本!');
return;
}
}
});
wx.getLocation({
success:function(res) {
varlatitude=res.latitude;//緯度,浮點數(shù),范圍為90 ~ -90
varlongitude=res.longitude;//經(jīng)度,浮點數(shù),范圍為180 ~ -180。
varspeed=res.speed;//速度,以米/每秒計
varaccuracy=res.accuracy;//位置精度
varlocation=latitude+','+longitude;
getBaiduLocation(longitude,latitude);
getAddrs(location);
//轉(zhuǎn)換百度坐標
functiongetBaiduLocation(longitude,latitude) {
$.ajax({
type:"GET",
url:'http://api.map.baidu.com/geoconv/v1/?coords='+longitude+','+latitude+'&from=1&to=5&output=json&ak= 你的百度ak ',
dataType:'jsonp',
success:function(msg) {
try{
varresult=msg.result;
varlat=result[0].y;//緯度
varlng=result[0].x;//經(jīng)度
navi(result[0]);//導航
}catch(e) {
alert(e.message);
}
}
});
};
//調(diào)用百度地圖api執(zhí)行地址逆編碼
functiongetAddrs(jwd) {
$.ajax({
type:"GET",
url:'http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='+jwd+'&output=json&pois=1&ak=你的百度ak',
dataType:'jsonp',
success:function(msg) {
//獲取地址成功后的回調(diào),我這里只需要獲取省市區(qū)信息
if(msg.status==0){
varprovMsg=msg.result.addressComponent.province;
varcityMsg=msg.result.addressComponent.city;
varareaMsg=msg.result.addressComponent.district;
varpca=provMsg+'-'+cityMsg+'-'+areaMsg;
}
}
})
}
},
cancel:function(res) {
alert('用戶拒絕授權(quán)獲取地理位置');
}
});
});
wx.error(function(res) {
alert(res.errMsg);//打印錯誤消息。及把debug:false,設(shè)置為debug:ture就可以直接在網(wǎng)頁上看到彈出的錯誤提示
});
}
}
});