【微信开发】-JSSDK获取地理位置坐标及转换成百度坐标和腾讯坐标

这里是用JSSDK获取地理位置坐标,然后调用腾讯地图或百度地图时,会发现位置有偏差,JSSDK中通过wx.getLocation获得是GPS坐标,需要转换成百度坐标或腾讯坐标(高德地图目前没有学习),一般都是调用百度坐标,但JSSDK中的wx.openLocation是直接调用腾讯地图,所以也一起研究一下,原理都一样,这里面会涉及到JSSDK的配置参数和一些WEUI样式库,这里就不过多说明了,具体参见相关文章,以后我再补充。
一、最基本的JSSDK的获取地理位置接口和使用微信内置地图查看位置接口


//以下是标准的JSSDK的票证
require_once "jssdk_test.php";
$jssdk = new JSSDK("AppID", "AppSecret");
$signPackage = $jssdk->getSignPackage();
?>

<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"/>
<link rel="stylesheet" href="weui/example.css" />
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js">script>
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">
                  <button class="weui_btn weui_btn_primary" id="getLocationId">getLocationbutton>
      div>
              <div class="weui_cell">
                  <button class="weui_btn weui_btn_primary" id="openLocationId">openLocationbutton>
            div>
 div>
   div>
body>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js">script>
<script> 
  //JSSDK配置参数 通过config接口注入权限验证配置
  wx.config({
      debug: false,
      appId: '',
      timestamp:  echo $signPackage["timestamp"];?>,
      nonceStr: ' echo $signPackage["nonceStr"];?>',
      signature: ' echo $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('#getLocationId').onclick = function () {

   wx.getLocation({
      success: function (res) {
         alert(JSON.stringify(res)); 
var latitude = res.latitude; //纬度
var longitude = res.longitude; //经度
var speed = res.speed; //速度
var accuracy = res.accuracy; //位置精度
var errMsg = res.errMsg; //结果状态
var locationStr = "latitude:"+latitude+","+"longitude:"+longitude+","+"speed:"+speed+","+"accuracy:"+accuracy+","+"errMsg:"+errMsg;
alert(locationStr);
$("#locationText").text(locationStr);
      },
      cancel: function (res) {
        alert('用户拒绝授权获取地理位置');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });//end wx.getLocation

  };//end document

  document.querySelector('#openLocationId').onclick = function(){

     wx.openLocation({
 latitude: 39.914139,
 longitude: 116.466881,
          name: "国贸", //要写引号
 address: "北京市朝阳区建国门外大街国贸桥", //要写引号
 scale: 15,
 infoUrl: "http://www.baidu.com" //要写引号
     }); //end wx.openLocation

  };//end document

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

测试说明:微信JSSDK获得的地理位置不准,getLocation是基于GPS的即type: ‘wgs84’,在调用百度地图或是腾讯地图会发生偏移所以需要进行相应的坐标转换

二、通过JSSDK的获取地理位置,转换腾讯地图坐标


//以下是标准的JSSDK的票证
require_once "jssdk_test.php";
$jssdk = new JSSDK("AppID", "AppSecret");
$signPackage = $jssdk->getSignPackage();
?>

<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"/>
<link rel="stylesheet" href="weui/example.css" />
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js">script>
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">
            <button class="weui_btn weui_btn_primary" id="getLocationId">getLocationbutton>
div>
         <div class="weui_cell">
            <button class="weui_btn weui_btn_primary" id="openLocationId">openLocationbutton>
div>
 div>
   div>
body>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js">script>
<script> 
  //JSSDK配置参数 通过config接口注入权限验证配置
  wx.config({
      debug: false,
      appId: '',
      timestamp:  echo $signPackage["timestamp"];?>,
      nonceStr: ' echo $signPackage["nonceStr"];?>',
      signature: ' echo $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('#getLocationId').onclick = function () {
   wx.getLocation({
      success: function (res) {
         alert(JSON.stringify(res)); 
var latitude = res.latitude; //纬度
var longitude = res.longitude; //经度
var locationStr = "latitude:"+latitude+","+"longitude:"+longitude;

         $.ajax({
            url: "test.php",
            type: "POST",
data: JSON.stringify(res),
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);
},
error: function(){
               alert("有错误!");
}
});//end ajax  
      },
      cancel: function (res) {
        alert('用户拒绝授权获取地理位置');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });//end wx.getLocation

  };//end document

  document.querySelector('#openLocationId').onclick = function(){
   wx.getLocation({
      success: function (res) {
         alert(JSON.stringify(res)); 
var latitude = res.latitude; //纬度
var longitude = res.longitude; //经度
var locationStr = "latitude:"+latitude+","+"longitude:"+longitude;

         $.ajax({
            url: "test.php",
            type: "POST",
data: JSON.stringify(res),
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);


               wx.openLocation({
            latitude: latitudeNew,
            longitude: longitudeNew,
                 name: "名称", //要写引号,这里需要动态引用此经纬度的名称
            address: "地址", //要写引号,这里需要动态引用此经纬度的地址信息
            scale: 15,
            infoUrl: "http://lbs.qq.com" //要写引号
              }); //end wx.openLocation


},
error: function(){
               alert("有错误!");
}
});//end ajax  
      },
      cancel: function (res) {
        alert('用户拒绝授权获取地理位置');
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });//end wx.getLocation

  };//end document

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

    //这是ajax调用的test.php

    header('Content-type:text/json'); 

    $data = file_get_contents('php://input');

$newData = json_decode($data,true);
$latitude = $newData["latitude"];
$longitude = $newData["longitude"];


    //腾讯地图坐标转换官网:http://lbs.qq.com/webservice_v1/guide-convert.html

    $q = "http://apis.map.qq.com/ws/coord/v1/translate?locations=".$latitude.",".$longitude."&type=1&key=yourKey";
    $resultQ = json_decode(file_get_contents($q),true);


    $latitudeNew = $resultQ["locations"][0]["lat"];
$longitudeNew = $resultQ["locations"][0]["lng"];

    $returnDataArray = array("latitudeNew"=>$latitudeNew,"longitudeNew"=>$longitudeNew);
    $returnData = json_encode($returnDataArray);

    echo $returnData; //只有输出才能回传到$.ajax中的success,这样ajax中的success:function(data)中的data就收到数据了


?>

测试说明:现在getLocation获得的坐标,通过腾讯地图坐标转换就准确,下面是百度地图坐标转换

三、通过JSSDK的获取地理位置,转换百度地图坐标,并测试直接打开百度地图导航


//以下是标准的JSSDK的票证
require_once "jssdk_test.php";
$jssdk = new JSSDK("AppID", "AppSecret");
$signPackage = $jssdk->getSignPackage();
?>

<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"/>
<link rel="stylesheet" href="weui/example.css" />
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js">script>
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>
<script> 
  //JSSDK配置参数 通过config接口注入权限验证配置
  wx.config({
      debug: false,
      appId: '',
      timestamp:  echo $signPackage["timestamp"];?>,
      nonceStr: ' echo $signPackage["nonceStr"];?>',
      signature: ' echo $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) {
         alert(JSON.stringify(res)); 
var latitude = res.latitude; //纬度
var longitude = res.longitude; //经度
var locationStr = "latitude:"+latitude+","+"longitude:"+longitude;

         $.ajax({
            url: "test.php",
            type: "POST",
data: JSON.stringify(res),
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®ion=北京&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>.


    //这是ajax调用的test.php

    header('Content-type:text/json'); 

    $data = file_get_contents('php://input');

$newData = json_decode($data,true);
$latitude = $newData["latitude"];
$longitude = $newData["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=yourBaiduAK";
    $resultQ = json_decode(file_get_contents($q),true);

    $latitudeNew = $resultQ["result"][0]["y"];
$longitudeNew = $resultQ["result"][0]["x"];

    $returnDataArray = array("latitudeNew"=>$latitudeNew,"longitudeNew"=>$longitudeNew);
    $returnData = json_encode($returnDataArray);

    echo $returnData; //只有输出才能回传到$.ajax中的success,这样ajax中的success:function(data)中的data就收到数据了

?>

测试说明:如果打开百度导航起点就是你所在位置的话就是坐标转换是对的,如果起点位置与你的实际位置有一些偏差那就是不正常

你可能感兴趣的:(微信开发)