[微信开发] 微信JSAPI - 获取用户地理位置信息

 

参考博客

http://blog.csdn.net/u013142781/article/details/50503299

 

主要JS 方法

wx.getLocation

获取地理位置信息传递参数

成功后返回参数

 

根据返回经纬度打开地理位置网页

wx.openLocation 参数设置


关键代码:

后台 - 构造微信验证消息

private static String appId = PropertiesUtil.getValue("common.properties", "app.id");
   
@RequestMapping(value = "/get_jsapi_ticket") @ResponseBody public Map<String, Object> getJsapiTicket( HttpServletRequest request, HttpServletResponse response, HttpSession session, String url) throws IOException { Map<String, Object> jsapiSignature = createJsapiSignature(url); jsapiSignature.put("appId", appId); return jsapiSignature; } public Map<String, Object> createJsapiSignature(String url) { Map<String, Object> map = new HashMap<String, Object>(); //准备参数 String base_access_token = redisService.getBaseTokenFromRedis(appId, appSecret); JSONObject jsApiTicket = WeixinUtil.getJsApiTicket(base_access_token); String ticket = jsApiTicket.get("ticket").toString(); String timestamp = Long.toString(System.currentTimeMillis() / 1000); String nonceStr = createNonceStr(16); //sha1加密 String requesturl = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url; log.info("requesturl=" + requesturl); String signature = SHA1(requesturl); log.info("signature=" + signature); map.put("timestamp", timestamp); map.put("nonceStr", nonceStr); map.put("signature", signature); return map; } /** * SHA、SHA1加密 * * @param str * @return */ public static String SHA1(String str) { try { MessageDigest digest = java.security.MessageDigest .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可 digest.update(str.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexStr = new StringBuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexStr.append(0); } hexStr.append(shaHex); } return hexStr.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } /** * 构造随机字符串 * * @param length * @return */ private static String createNonceStr(int length) { String baseStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; StringBuffer temp = new StringBuffer(); Random random = new Random(); for (int i = 0; i < length; i++) { int number = random.nextInt(baseStr.length()); temp.append(baseStr.charAt(number)); } return temp.toString(); }

 

前端 - 发送请求并解析地理位置信息

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>绑定页</title>
</head>

<body>
<a href="javascript:;" onclick="getLocation()">获取我的位置信息</a>

<script src="${ctx}/assets/jquery-1.10.2.min.js"></script>
<script src="${ctx}/assets/jweixin-1.2.0.js"></script>
<script type="text/javascript">
    $(function(){
        configWx();
    });

    function configWx() {
        var thisPageUrl = location.href.split('#')[0];
        $.get(
                "${ctx}/oauth/get_jsapi_ticket",
                {url:thisPageUrl},
                function(data){
                    console.log(data);
                    if(data!=null){
                        configWeiXin(data.appId, data.timestamp, data.nonceStr,
                                data.signature);
                    }else {
                        console.log("配置weixin jsapi失败");
                    }
                }
        );
    }

    function configWeiXin(appId, timestamp, nonceStr, signature) {
        wx.config({
            debug : true,// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId : appId,
            timestamp : timestamp,
            nonceStr : nonceStr,
            signature : signature,
            jsApiList : [ 'chooseImage', 'uploadImage', 'downloadImage',
                'previewImage', 'openLocation', 'getLocation',
                'scanQRCode', 'checkJsApi', 'onMenuShareTimeline',
                'onMenuShareAppMessage', 'onMenuShareQQ',
                'onMenuShareWeibo', 'onMenuShareQZone' ]
        });
        console.log("wx");
        console.log(wx);
    }

    function getLocation() {
        wx.getLocation({
            type : 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
            success : function(res) {
                //使用微信内置地图查看位置接口
                wx.openLocation({
                    latitude : res.latitude, // 纬度,浮点数,范围为90 ~ -90
                    longitude : res.longitude, // 经度,浮点数,范围为180 ~ -180。
                    name : '我的位置', // 位置名
                    address : '中国海洋大学', // 地址详情说明
                    scale : 28, // 地图缩放级别,整形值,范围从1~28。默认为最大
                    infoUrl : 'http://www.haiyangdaxue.com' // 在查看位置界面底部显示的超链接,可点击跳转(测试好像不可用)
                });
            },
            cancel : function(res) {

            }
        });
    }
</script>
</body>
</html>

 

posted @ 2018-01-08 12:00  Aviva_ye  阅读(7756)  评论(0编辑  收藏  举报