跳到主要内容

使用微信公众号和百度地图获取位置

· 阅读需 4 分钟
lzw.

1、引入地图 jsSdk

<script src="//res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script src="//api.map.baidu.com/api?v=3.0&ak=ak"></script>

注意:微信公众号需要appID和appSecret,百度地图需要申请ak

微信jsSdk配置:

wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '', // 必填,公众号的唯一标识
timestamp: , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名
jsApiList: ['getLocation'] // 必填,需要使用的JS接口列表
});

2、获取地理位置

  • 首先判断是否微信
  • 获取微信获取经纬度转为百度地图的经纬度
  • 或者直接使用百度地图获取
  • 通过函数回调,使用经纬度位置

判断是微信:

//判断是否是微信浏览器的函数
function isWeiXin() {
//window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息,这个属性可以用来判断浏览器类型
var ua = window.navigator.userAgent.toLowerCase();
//通过正则表达式匹配ua中是否含有MicroMessenger字符串
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
return true;
} else {
return false;
}
}

获取经纬度:

//获取我的位置经纬度
function myLngLat(callback) {
//默认市民中心
var longitude = 114.052031, latitude = 22.54639;
var myLng = sessionStorage.getItem('myLng'), myLat = sessionStorage.getItem('myLat');
if (myLng && myLat) {
callback(myLng, myLat)
} else {
if (isWeiXin()) {
wx.ready(function () {
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
// 转成百度地图
$.ajax({
url: 'http://api.map.baidu.com/geoconv/v1/?coords=' + longitude + ',' + latitude + '&from=1&to=5&ak=ak',
type: 'GET',
dataType: 'jsonp',
processData: false,
success: function (res) {
console.log(res)
if (res.status == 0) {
longitude = res.result[0].x;
latitude = res.result[0].y;
}
//经纬度
callback(longitude, latitude);
}
})
}
})
})
}
else {
// 百度地图API功能
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function (r) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
var mk = new BMap.Marker(r.point);
console.log(r.point.lng, r.point.lat);
//alert('您的位置:'+r.point.lng+','+r.point.lat);
longitude = r.point.lng;
latitude = r.point.lat;
//经纬度
sessionStorage.setItem('myLng', longitude)
sessionStorage.setItem('myLat', latitude)
} else {
alert('定位失败,请允许地图获取您的位置!');
console.log('failed' + this.getStatus());
}
callback(longitude, latitude);
}, {enableHighAccuracy: true});
}
}
}

3、使用地理位置

myLngLat(function(myLng,myLat){
console.log(myLng,myLat)
})

在微信中使用公号的接口获取地理位置会更准确些