微信公眾號 獲取地理位置坐標并轉換成百度坐標 再通過經緯度及百度接口查詢出詳細地理位置

前提:




百度地圖新建ak
網址:http://lbsyun.baidu.com/apiconsole/key

我這兒用的是tp3.2做的



WechatJs 是用到的類

JSSDK配置參數獲取: 標準的JSSDK的票證

public function map(){
        $appid = C ( "WX_APPID" ); //appid
        $appsecret = C ( "WX_CRYPT" ); //appscrypt
        $jssdk = new WechatJs($appid, $appsecret);
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage',$signPackage);
        $this->display();
}

//前端頁面 map.html
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <title></title>
<link rel="stylesheet" href="weui/weui.min.css"/><!--這是WEUI樣式庫文件自行官網下載使用-->
<link rel="stylesheet" href="weui/example.css" /><!--這是WEUI樣式庫文件自行官網下載使用-->
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script><!--調用jQuery-->
</head>
<body>
   <div class="bd">
      <div class="weui_cells">
    <div class="weui_cell_bd weui_cell_primary">
            <span id="locationText"></span>
</div>
<div class="weui_cell">
            <a href="javascript:;" class="weui_btn weui_btn_primary" id="btnToLocation">通過getLocation再轉換百度坐標后直接打開百度導航</a>
</div>
 </div>
   </div>
</body>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script><!--調用JSSDK-->
<script> 
  //JSSDK配置參數 通過config接口注入權限驗證配置
  wx.config({
      debug: false,
      appId: '{$signPackage.appId}',
      timestamp: '{$signPackage.timestamp}',
      nonceStr: '{$signPackage.nonceStr}',
      signature: '{$signPackage.signature}',
      jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'hideMenuItems',
        'showMenuItems',
        'hideAllNonBaseMenuItem',
        'showAllNonBaseMenuItem',
        'translateVoice',
        'startRecord',
        'stopRecord',
        'onRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'getNetworkType',
        'openLocation',
        'getLocation',
        'hideOptionMenu',
        'showOptionMenu',
        'closeWindow',
        'scanQRCode',
        'chooseWXPay',
        'openProductSpecificView',
        'addCard',
        'chooseCard',
        'openCard'
      ]
  });
</script>
<script> 
  //通過ready接口處理成功驗證,加載直接調用的程序放在ready中,這里目前為空
  wx.ready(function () {

  });

  //這塊是用jQuery來把wx.getLocation獲取到的值顯示在頁面中的id=LocationText的位置
  //document.querySelector('#btnToLocation').onclick = function () {
  $(document).on("click","#btnToLocation",function(){
        gotoLocation();
  });

  function gotoLocation(){
   wx.getLocation({
      success: function (res) {
         var latitude = res.latitude; //緯度
         var longitude = res.longitude; //經度
         var locationStr = "latitude:"+latitude+","+"longitude:"+longitude;
         $.ajax({
            url: "{:U('Demo/test')}",
            type: "POST",
            data: {Latitude:latitude,Longitude:longitude},
            dataType: "json",
            success: function(json){
                  var latitudeNew = json.latitudeNew;
                  var longitudeNew = json.longitudeNew;
                  var locationNewStr = "latitudeNew:"+latitudeNew+","+"longitudeNew:"+longitudeNew;
                    alert(locationStr + ";" + locationNewStr);
                  $("#locationText").text(locationStr + ";" + locationNewStr);
                  location.;
                  //百度地圖坐標拾取網址:http://api.map.baidu.com/lbsapi/getpoint/index.html,獲得測試地址國貿地鐵站的經緯度
                  //百度地圖路線規劃WebAPI網址:http://lbsyun.baidu.com/index.php?title=webapi/direction-api
            },
            error: function(){
                   alert("有錯誤!");
            }
         });//end ajax  
      },
      cancel: function (res) {
        alert('用戶拒絕授權獲取地理位置');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });//end wx.getLocation

 }//end function

  wx.error(function (res) {
     alert(res.errMsg);
  });
</script>
</html>

Demo/test 是轉換為百度坐標的方法

/**
      * 轉換成百度坐標 
     */
    public function test()
    {
        $latitude = $_POST['Latitude'];
        $longitude = $_POST['Longitude'];
//      //百度地圖坐標轉換官網:http://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition
        $q = "http://api.map.baidu.com/geoconv/v1/?coords=".$longitude.",".$latitude."&from=1&to=5&ak=CVwQRrOiPCBuNgjWU3fNRvaYhkMBaI4A";
        $resultQ = json_decode(file_get_contents($q),true);
        $latitudeNew = $resultQ["result"][0]["y"];
        $longitudeNew = $resultQ["result"][0]["x"];
        $returnDataArray = array("latitudeNew"=>$latitudeNew,"longitudeNew"=>$longitudeNew);
        $this->ajaxReturn($returnDataArray);
    }

通過轉換過的百度坐標(經緯度)來獲取當前位置詳細信息

/**
      * 獲取當前位置詳細信息
     */
    public function test_two()
    {
        $latitude = '38.054662894458';
        $longitude = '114.48129456957';
        $q = "http://api.map.baidu.com/geocoder/v2/?location=".$latitude.",".$longitude."&output=json&pois=0&ak=CVwQRrOiPCBuNgjWU3fNRvaYhkMBaI4A";
        $result = $this->http_request($q);
        $resultArry = json_decode($result,true);
        dump($resultArry);
        dump($resultArry['result']['formatted_address']);
        die;
    }
    /**
     * curl
     */
    protected function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

使用百度地圖逆地址解析遇到的一個小坑: 轉載自:https://blog.csdn.net/xiaolong20081/article/details/79604476
區別于上述代碼的一個請求地址:

http://api.map.baidu.com/geocoder/v2/?ak=xxx&coordtype=wgs84ll&callback=renderReverse&location=37.58585,118.8889&output=xml&pois=1

用百度地圖官網給的請求地址會多出一個 renderReverse&&renderReverse
拿到值很開心的用上json_decode,結果刷新查看返回NULL,竟然是空,不甘心的我以特么刷新了幾遍,還是空,這是逗我嗎?又跑去檢查代碼,代碼沒錯啊。最后通過百度找到了正確的解決辦法,原來是多了callback=renderReverse這個javascript函數名,去掉這個就行了。另一種方法是通過正則來匹配出json格式數據,

$str= 'renderReverse&&renderReverse({"status":0,"result":{"location":{"lng":116.32298703399,"lat":39.983424051248},"formatted_address":"北京市海淀區中關村大街27號1101-08室","business":"中關村,人民大學,蘇州街","addressComponent":{"adcode":"110108","city":"北京市","country":"中國","direction":"附近","distance":"7","district":"海淀區","province":"北京市","street":"中關村大街","street_number":"27號1101-08室","country_code":0},"pois":[{"addr":"北京北京海淀海淀區中關村大街27號(地鐵海淀黃莊站A1","cp":"NavInfo","direction":"內","distance":"0","name":"北京遠景國際公寓(中關村店)","poiType":"房地產","point":{"x":116.3229458916,"y":39.983610361549},"tag":"房地產","tel":"","uid":"35a08504cb51b1138733049d","zip":""},{"addr":"海淀區中關村北大街27號","cp":"NavInfo","direction":"附近","distance":"25","name":"中關村大廈","poiType":"房地產","point":{"x":116.32285606105,"y":39.983568897877},"tag":"房地產;寫字樓","tel":"","uid":"06d2dffdaef1b7ef88f15d04","zip":""},{"addr":"中關村大街29","cp":"NavInfo","direction":"北","distance":"62","name":"海淀醫院激光整形美容部","poiType":"醫療","point":{"x":116.32317046798,"y":39.983016046485},"tag":"醫療;專科醫院","tel":"","uid":"b1c556e81f27cb71b4265502","zip":""},{"addr":"中關村大街27號中關村大廈1層","cp":"NavInfo","direction":"附近","distance":"1","name":"中國人民財產保險中關村營業部","poiType":"金融","point":{"x":116.32298182382,"y":39.983416864194},"tag":"金融;投資理財","tel":"","uid":"060f5e53137d20d7081cc779","zip":""},{"addr":"北京市海淀區","cp":"NavInfo","direction":"東北","distance":"58","name":"北京市海淀醫院-輸血科","poiType":"醫療","point":{"x":116.322685383,"y":39.983092063819},"tag":"醫療;其他","tel":"","uid":"cf405905b6d82eb9b55f1e89","zip":""},{"addr":"北京市海淀區中關村大街27號中關村大廈二層","cp":"NavInfo","direction":"附近","distance":"0","name":"眉州東坡酒樓(中關村店)","poiType":"美食","point":{"x":116.32298182382,"y":39.983423774823},"tag":"美食","tel":"","uid":"2c0bd6c57dbdd3b342ab9a8c","zip":""},{"addr":"北京市海淀區中關村大街29號(海淀黃莊路口)","cp":"NavInfo","direction":"東北","distance":"223","name":"海淀醫院","poiType":"醫療","point":{"x":116.32199368776,"y":39.982083099537},"tag":"醫療;綜合醫院","tel":"","uid":"fa01e9371a040053774ff1ca","zip":""},{"addr":"北京市海淀區中關村大街28號","cp":"NavInfo","direction":"西北","distance":"229","name":"海淀劇院","poiType":"休閑娛樂","point":{"x":116.32476945179,"y":39.982622137118},"tag":"休閑娛樂;電影院","tel":"","uid":"edd64ce1a6d799913ee231b3","zip":""},{"addr":"海淀黃莊地鐵站旁","cp":"NavInfo","direction":"西北","distance":"375","name":"中發電子市場(中關村大街)","poiType":"購物","point":{"x":116.32529945204,"y":39.981537146849},"tag":"購物;家電數碼","tel":"","uid":"69130523db34c811725e8047","zip":""},{"addr":"北京市海淀區知春路128號","cp":"NavInfo","direction":"西北","distance":"434","name":"泛亞大廈","poiType":"房地產","point":{"x":116.32600013033,"y":39.981516414381},"tag":"房地產;寫字樓","tel":"","uid":"d24e48ebb9991cc9afee7ade","zip":""}],"poiRegions":[],"sematic_description":"北京遠景國際公寓(中關村店)內0米","cityCode":131}})';
preg_match('/\(.*\)/', $str, $result);
var_dump($result);

第三辦法是用str_replace和substr和strlen解決,這里就不給出具體的寫法了,有需要的可以去百度一下用法。

注意事項:
1.獲取微信地理位置時 要保證JS安全域名 網址不帶http/https

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,065評論 25 708
  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網絡請求組件 FMDB本地數據庫組件 SD...
    陽明AGI閱讀 16,003評論 3 119
  • 不管一開始多么整潔空蕩的抽屜,我都能在一個月之內迅速讓其變得充實雜亂,而且能迅速找到我需要的東西,除我以外的人都很...
    張莫默閱讀 259評論 0 0
  • 這么多年不見,早就沒了你的消息,忽然聯絡,滿滿的相思,我卻沒勇氣見你。 大學畢業后,宿舍的六個姐妹各奔東西,再沒有...
    搔耳朵的貓閱讀 1,110評論 4 7
  • “焦慮、害怕真的是讓人很煎熬,我之所以和它斗爭,是因為我真的很想擺脫它,可是老師您卻教我們要戰略性認慫,放棄和焦慮...
    經年小花閱讀 270評論 0 0