分享下微信是如何定位的:
本文主要講解如何利用微信定位,如何將定位到的經(jīng)緯度轉(zhuǎn)換為百度地圖對(duì)應(yīng)的經(jīng)緯度,以及處理定位失敗、取消及錯(cuò)誤時(shí)的默認(rèn)做法。
//獲取地理位置信息start//封裝成一個(gè)函數(shù) function getPosition() { //用ajax請(qǐng)求 $.ajax({ url: "/wechat/jssdk",//請(qǐng)求地址 type: 'post',//post請(qǐng)求 dataType: 'json', contentType: "application/x-www-form-urlencoded; charset=utf-8", data: { 'url': location.href.split('#')[0]//將第一個(gè)#號(hào)前的地址傳遞 },//請(qǐng)求成功的函數(shù) success: function (data) { wx.config({ // debug: true, appId: data.data.appId, timestamp: data.data.timestamp, nonceStr: data.data.nonceStr, signature: data.data.signature, jsApiList: ['checkJsApi', 'getLocation'] }); wx.ready(function () { wx.getLocation({ //獲得定位成功 success: function (res) { //這是微信返回的真正經(jīng)緯度 var oldLat = res.latitude; // 緯度,浮點(diǎn)數(shù),范圍為90 ~ -90 var oldLng = res.longitude; // 經(jīng)度,浮點(diǎn)數(shù),范圍為180 ~ -180。 /*下面是為了將獲得的真正經(jīng)緯度轉(zhuǎn)換為對(duì)應(yīng)的百度經(jīng)緯度,因?yàn)槭抢冒俣鹊貓D的經(jīng)緯度去查詢數(shù)據(jù)的,數(shù)據(jù)庫(kù)中存的也是百度的經(jīng)緯度*/ //創(chuàng)建一個(gè)百度地圖的點(diǎn) var customerPoint = new BMap.Point(oldLng, oldLat); // var convertor = new BMap.Convertor(); var pointArr = [];//創(chuàng)建一個(gè)數(shù)組 pointArr.push(customerPoint);//將剛才的點(diǎn)放進(jìn)去 convertor.translate(pointArr, 1, 5, initMap); //轉(zhuǎn)換坐標(biāo) function initMap(data) { if (data.status === 0) {//轉(zhuǎn)換成功 var point = data.points[0];//得到后的點(diǎn) var lng = point.lng;//獲得轉(zhuǎn)換后的經(jīng)度 var lat = point.lat;//獲得轉(zhuǎn)換后的緯度 toDoFunction(lng, lat);//將經(jīng)緯度傳入到要運(yùn)用的函數(shù)中 } else { //下面兩行是默認(rèn)定位到西湖的經(jīng)緯度 lng = 120.141375; lat = 30.257806; toDoFunction(lng, lat);//將經(jīng)緯度傳入到要運(yùn)用的函數(shù)中 } } }, //取消定位 cancel: function () { //下面兩行是默認(rèn)定位到西湖的經(jīng)緯度 var lng = 120.141375; var lat = 30.257806; toDoFunction(lng, lat);//將經(jīng)緯度傳入到要運(yùn)用的函數(shù)中 }, //定位失敗 fail: function () { //下面兩行是默認(rèn)定位到西湖的經(jīng)緯度 var lng = 120.141375; var lat = 30.257806; toDoFunction(lng, lat);//將經(jīng)緯度傳入到要運(yùn)用的函數(shù)中 } }); //定位發(fā)生錯(cuò)誤 wx.error(function () { //下面兩行是默認(rèn)定位到西湖的經(jīng)緯度 var lng = 120.141375; var lat = 30.257806; toDoFunction(lng, lat);//將經(jīng)緯度傳入到要運(yùn)用的函數(shù)中 }); }); } }); }以上代碼,如果可以定位到就用定位到的真正的經(jīng)緯度,再轉(zhuǎn)換成百度地圖對(duì)應(yīng)的經(jīng)緯度,如果定位失敗或者是點(diǎn)擊取消或者發(fā)生錯(cuò)誤,則默認(rèn)定位到西湖的經(jīng)緯度。
新聞熱點(diǎn)
疑難解答
圖片精選