微信获取地理位置

这个问题自己摸索了很久,不容易啊,哈哈。

            <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

            //获取地址

$("#dizhi").click(function(){
$.ajax({

type: "GET",

                                //这里是传入当前页面的url去获取微信配置信息

url: "${basePath}/index/WxConfig",
async: true,

dataType: "json",

                                //这是当前页面的地址,直接这样获取就可以了

data: {"locationUrl":location.href},
success: function(config){
wx.config({
              debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
              appId : config.appId, // 必填,公众号的唯一标识
              timestamp : config.timestamp, // 必填,生成签名的时间戳
              nonceStr : config.nonceStr, // 必填,生成签名的随机串
              signature : config.signature,// 必填,签名,见附录1
              jsApiList : ['chooseWXPay']// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
         });
wx.ready(function(){
wx.ready(function(){
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度

alert("latitude:"+latitude+"latitude:"+latitude+"longitude:"+longitude);

                                                                //这是获取到的经纬度传到后台处理成位置信息

location.href="${basePath}/groupPurchase/saveAddress?latitude="+latitude+"&longitude="+longitude;
}
});
});
wx.error(function (res) {
alert("调用微信jsapi返回的状态:"+res.errMsg);
});
});
}
});

});



//先获取微信公众号的参数

/**
* 微信js-sdk基本配置参数

* @param url
* @return
*/
public Map<String, String> WxConfigApi(String url) {
// jsapi_ticket
JsTicket jsapi_ticket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
// 随机串
String nonce_str = create_nonce_str();
// 时间戳
String timestamp = create_timestamp();
// 签名
String signature = "";
// 拼接字符串进行加密,获取签名
String sha1 = "jsapi_ticket=" + jsapi_ticket.getTicket() + "&noncestr=" + nonce_str + "&timestamp=" + timestamp
+ "&url=" + url;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(sha1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Map<String, String> configMap = new HashMap<String, String>();
String appId = "自己的appid";
configMap.put("url", url);
configMap.put("appId", appId);
configMap.put("jsapi_ticket", jsapi_ticket.getTicket());
configMap.put("nonceStr", nonce_str);
configMap.put("timestamp", timestamp);
configMap.put("signature", signature);
return configMap;

}


/**
* 随机加密

* @param hash
* @return
*/
public String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;

}


/**
* 产生随机串--由程序自己随机产生

* @return
*/
public static String create_nonce_str() {
return UUID.randomUUID().toString();

}


/**
* 由程序自己获取当前时间 时间戳

* @return
*/
public String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);

}



/**
* 获取地址保存地址
*/
public void saveAddress(){
String latitude = getPara("latitude");
String longitude = getPara("longitude");
String address = AddressUtil.getAddress(longitude, latitude);
        JSONObject jsonObject = JSONObject.fromObject(address);  
        JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("addrList"));  
        //***jsonArray***[{"type":"poi","status":1,"name":"成都曼豪香年广场店","id":"ANB001C8XLRS",
        //"admCode":"510107","admName":"四川省,成都市,武侯区,","addr":"天府大道中段吉泰五路88号",
        //"nearestPoint":[104.06702,30.5539],"distance":216.889}]
        JSONObject j_2 = JSONObject.fromObject(jsonArray.get(0));  
        //***j_2***{"type":"poi","status":1,"name":"成都曼豪香年广场店","id":"ANB001C8XLRS","admCode":"510107",
        //"admName":"四川省,成都市,武侯区,","addr":"天府大道中段吉泰五路88号",
        //"nearestPoint":[104.06702,30.5539],"distance":216.889}
        String allAdd = j_2.getString("admName"); 
        String name = j_2.getString("name");
        String addr = j_2.getString("addr");
        String arr[] = allAdd.split(",");  
        //省
        String provice=arr[0];
        //市
        String city=arr[1];
        //区
        String area=arr[2];
        log.error("省:"+provice+"\n市:"+city+"\n区:"+area);  
        renderJson(provice+" - "+city+" - "+area+" - "+name+" - "+addr);
}





import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;


import net.sf.json.JSONObject;


/**  地址获取工具类
 * @author ChenXb
 *
 * 2017年9月20日
 */
public class AddressUtil {
public static Map<String,Double> getLngAndLat(String address){
Map<String,Double> map=new HashMap<String, Double>();
String url = "http://api.map.baidu.com/geocoder/v2/?address="+address+"&output=json&ak=ZUtBCLA8dFeXmCXYbUUaeQzjswpw0De5";
        String json = loadJSON(url);
        JSONObject obj = JSONObject.fromObject(json);
        if(obj.get("status").toString().equals("0")){
        double lng=obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
        double lat=obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
        map.put("lng", lng);
        map.put("lat", lat);
        System.out.println("经度:"+lng+"---纬度:"+lat);
        }else{
        System.out.println("未找到相匹配的经纬度!");
        }
return map;
}

public static String loadJSON (String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                                        yc.getInputStream()));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }
 
public static String getAddress(String log, String lat ){  
        //lat 小  log  大  
        //参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)  
        String urlString = "http://gc.ditu.aliyun.com/regeocoding?l="+lat+","+log+"&type=010";  
        String res = "";     
        try {     
            URL url = new URL(urlString);    
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();    
            conn.setDoOutput(true);    
            conn.setRequestMethod("POST");    
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));    
            String line;    
           while ((line = in.readLine()) != null) {    
               res += line+"\n";    
         }    
            in.close();    
        } catch (Exception e) {    
            System.out.println("error in wapaction,and e is " + e.getMessage());    
        }   
        System.out.println(res);  
        return res;    
    }  
 
}


猜你喜欢

转载自blog.csdn.net/qq_33371766/article/details/80223702