首先,在静态页面中,添加微信的配置文件,通过js获取。
<script type="text/javascript">
wx.config({
debug: false,
appid: '{$signpackage.appid}',
timestamp: '{$signpackage.timestamp}',
noncestr: '{$signpackage.noncestr}',
signature: '{$signpackage.signature}',
jsapilist: [
// 所有要调用的 api 都要加到这个列表中
'checkjsapi',
'openlocation',
'getlocation',
'scanqrcode'
]
});
wx.ready(function () {
$('#scan').click(function(){
wx.scanqrcode({
needresult: 0,
});
});
wx.checkjsapi({
jsapilist: [
'getlocation'
],
success: function (res) {
if (res.checkresult.getlocation == false)
{
alert('你的微信版本太低,不支持微信js接口,请升级到最新的微信版本!');
return;
}
}
});
wx.getlocation({
success: function (res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var geoconv = 'http://api.map.baidu.com/geoconv/v1/?callback=coordinatetransformation&coords=' + longitude + ',' + latitude + '&from=1&to=5&ak=5bfnbsgnvf5g2o72npvtdxfm';
var script = document.createelement('script');
script.src = geoconv;
document.head.appendchild(script);
},
cancel: function (res) {
alert('用户拒绝授权获取地理位置');
}
});
});
function coordinatetransformation(data)
{
var latlng = data.result[0].y + ',' + data.result[0].x;
var url = 'http://api.map.baidu.com/geocoder/v2/?callback=getcurrentlocation&ak=5bfnbsgnvf5g2o72npvtdxfm&location=' + latlng + '&output=json&pois=1';
var script = document.createelement('script');
script.src = url;
document.head.appendchild(script);
}
function getcurrentlocation(data)
{
if(data.status === 0)
{
var address = data.result.formatted_address,
x = data.result.location.lng,
y = data.result.location.lat,
city = data.result.addresscomponent.city,
street = data.result.addresscomponent.street || data.result.formatted_address,
reqdata = 'street=' + address + '&name=' + street + '&lng=' + x + '&lat=' + y + '&city=' + city;
var url = "{:u('index/saveposition')}";
$.getjson(url,{'name':street,'lng':x,'lat': y,'city':city},function(data)
{
if(data.returncode) { }
});
}
}
</script>
其次,在控制器中接收ajax传递的地理坐标,然后保存到session中。
public function saveposition() {
$city = ii('get.city','','trim');
$addr = ii('get.name','','trim');
$lng = ii('get.lng','','trim');
$lat = ii('get.lat','','trim');
$mylocation = array(
'city' =>$city,
'addr' =>$addr,
'lng' =>$lng,
'lat' =>$lat, );
$_session['mylocation'] = $mylocation;
$data['returncode'] = 1;
$data['returninfo'] = '获取位置成功!';
$this->ajaxreturn($data);
return;
}
注:用的是thinkphp框架,ii是自定义的方法,获取get或post传递的值,和 i 函数一样。
以上就是如何通过微信获取当前地理位置并将其存到session中的详细内容。