最近做一個(gè)公眾號(hào)頁(yè)面開(kāi)發(fā)程梦,需要獲取用戶(hù)地理位置信息罩息,獲取到經(jīng)緯度后荞胡,找了很多地方都沒(méi)找到騰訊地圖將經(jīng)緯度轉(zhuǎn)換成具體位置的方法拼缝,所以就只能調(diào)用百度地圖api轉(zhuǎn)一次,現(xiàn)在將其中部分代碼貼在上面彰亥,以便下次使用:
首先需要去百度api申請(qǐng)秘鑰咧七,鏈接:獲取百度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后會(huì)直接在網(wǎng)頁(yè)上彈出調(diào)試信息猪叙,用于排查問(wèn)題
appId:res.data.appId,
timestamp:res.data.timestamp,
nonceStr:res.data.nonceStr,
signature:res.data.signature,
jsApiList: [//所有要調(diào)用的API都要加到這個(gè)列表中
'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接口仁卷,請(qǐng)升級(jí)到最新的微信版本穴翩!');
return;
}
}
});
wx.getLocation({
success:function(res) {
varlatitude=res.latitude;//緯度,浮點(diǎn)數(shù)锦积,范圍為90 ~ -90
varlongitude=res.longitude;//經(jīng)度芒帕,浮點(diǎn)數(shù),范圍為180 ~ -180丰介。
varspeed=res.speed;//速度背蟆,以米/每秒計(jì)
varaccuracy=res.accuracy;//位置精度
varlocation=latitude+','+longitude;
getBaiduLocation(longitude,latitude);
getAddrs(location);
//轉(zhuǎn)換百度坐標(biāo)
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]);//導(dǎo)航
}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('用戶(hù)拒絕授權(quán)獲取地理位置');
}
});
});
wx.error(function(res) {
alert(res.errMsg);//打印錯(cuò)誤消息哮幢。及把debug:false,設(shè)置為debug:ture就可以直接在網(wǎng)頁(yè)上看到彈出的錯(cuò)誤提示
});
}
}
});