微信公众号 获取地理位置坐标并转换成百度坐标 再通过经纬度及百度

2018-08-14  本文已影响2141人  geeooooz

前提:




百度地图新建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.href="http://api.map.baidu.com/direction?origin="+latitudeNew+","+longitudeNew+"&destination=国贸地铁站&mode=driving&region=北京&output=html&ak=yourBaiduAK";
                  //百度地图坐标拾取网址: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

上一篇下一篇

猜你喜欢

热点阅读