使用上一篇进行基础配置,测试公众号的申请,jssdk的引入,configz的初始化
通过jssdk获取经纬度,调用高德接口根据经纬度获取地址信息
代码测试说明 完整代码在文章末尾
function configInfo() {
var apiList = ["getLocation"];
//获取wx jsdk信息
var url = "url=" + location.href.split('#')[0];
$.ajax({
url: "../../wechat/getWXSign",
type: "POST",
data: url,
dataType: "json",
success: function (result) {
console.log("微信鉴权参数==>");
console.log(result.map);
if (result.code == "success") {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: result.map.appId, // 必填,公众号的唯一标识
timestamp: result.map.timestamp, // 必填,生成签名的时间戳
nonceStr: result.map.nonceStr, // 必填,生成签名的随机串
signature: result.map.signature,// 必填,签名
jsApiList: apiList
// 必填,需要使用的JS接口列表
});
// 处理成功后回调
wx.ready(function () {
wx.getLocation({
type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var location = "location=" + res.longitude + "," + res.latitude;
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
$.ajax({
url: "../../wechat/getAddress",
type: "POST",
data: location,
dataType: "json",
success: function (result) {
debugger;
if (result.code == "success") {
$('input[name="ext_location_address_KUT"]').val(result.map.address);
}
},
error: function (err) {
alert("responseText is " + err.responseText)
common.comPopGo('系统错误!');
$('.container_text').fadeOut();
}
})
},
fail(err) {
alert(err.errMsg)
}
});
});
} else {
common.comPopGo(result.msg);
$('.container_text').fadeOut();
}
},
error: function () {
common.comPopGo('系统错误!');
$('.container_text').fadeOut();
}
})
}
后端高德接口
public static String GaoDeKey="a81b608760b66e7e7315b7eacabbfc41";
public static String GaoDeUrl="https://restapi.amap.com/v3/geocode/regeo?key="+GaoDeKey+"&location=";
@RequestMapping(value = "/getAddress")
public @ResponseBody ResponseData getAddress(HttpServletRequest request, String location) {
logger.info("====> getAddress location is " + location);
ResponseData responseData = new ResponseData();
String address = null;
HttpGet get = new HttpGet(Config.GaoDeUrl + location);
String res = HttpClientUtil.get(get, "");
logger.info("====>getAddress resulet 是 " + "\n" + res);
if (StringUtils.isNotBlank(res)) {
JSONObject json = JSONObject.fromObject(res);
Object regeocode = json.get("regeocode");
JSONObject jsonRegeo = JSONObject.fromObject(regeocode);
Object addressObj = jsonRegeo.get("formatted_address");
if (null != addressObj) {
address = addressObj.toString();
}
logger.info("====> getAddress address is " + address);
}
responseData.getMap().put("address", address);
return responseData;
}
里面使用到的工具类代码见微信-jsSDK使用