码迷,mamicode.com
首页 > 其他好文 > 详细

百度GPSutil

时间:2015-06-03 19:41:11      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:gps

=================================================

package com.qcar.benz.biz.common;

import com.alibaba.citrus.util.StringUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 地图查询相关工具类
 */
public class GPSUtil {

    private final static String url = "http://api.map.baidu.com/geocoder/v2/";

    private final static String ak = "1b7NAfBZKaHuGnRgtD6wfloL";
    private final static String sk = "zsHUBnMvE4KHzSEuYrXV1Hb46HtuCTXq";

    /**
     * 根据经纬度只获取所在省份
     *
     * @param location 【字符串类型,格式:"经度,纬度"】
     * @return
     */
    public static String getProvinceByGps(String location) {
        String province = "";
        Map map = getDetail(location);
        if (!CollectionUtils.isEmpty(map)) {
            if (!CollectionUtils.isEmpty((Map) map.get("addressComponent"))) {
                Map am = (Map) map.get("addressComponent");
                if (!CollectionUtils.isEmpty(am)) {
                    province = (String) am.get("province");
                }
            }
        }
        return province;

    }

    /**
     * 根据经纬度得到详细信息
     *
     * @param location 【字符串类型,格式:"经度,纬度"】
     * @return
     */
    public static Map getDetail(String location) {
        if (StringUtil.isBlank(location)) {
            return null;
        }
        String[] arr = location.split(",");
        if (arr.length != 2) {
            return null;
        }
        Map map = new HashMap();
        HttpClient client = new HttpClient();
        try {
            String wholeUrl = new String(url + "?ak=" + ak + "&location=" + arr[1] + "," + arr[0] + "&output=json");
            GetMethod get = new GetMethod(wholeUrl);
            if (client.executeMethod(get) == HttpServletResponse.SC_OK) {
                String str = new String(get.getResponseBody(), "UTF-8");
                Map m = (Map) JSON.parse(str);
                map = (Map) m.get("result");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 转换经纬度顺序
     * @return
     */
    public static String reverseLocation(Map map) {
        if (null == map) {
            return "";
        }
        Map location = (Map) map.get("location");
        return location.get("lng").toString() + "," + location.get("lat").toString();
    }

    /**
     * 根据具体地址获取经纬度,
     *
     * @param address
     * @return
     */
    public static Map getLocation(String address) {
        if (StringUtil.isBlank(address)) {
            return null;
        }
        Map map = new HashMap();
        try {
            Map paramsMap = new LinkedHashMap<String, String>();
            paramsMap.put("address", address);
            paramsMap.put("output", "json");
            paramsMap.put("ak", GPSUtil.ak);
            // 调用下面的toQueryString方法,对LinkedHashMap内所有value作utf8编码,拼接返回结果address=%E7%99%BE%E5%BA%A6%E5%A4%A7%E5%8E%A6&output=json&ak=yourak
            String paramsStr = toQueryString(paramsMap);

            // 对paramsStr前面拼接上/geocoder/v2/?,后面直接拼接yoursk得到/geocoder/v2/?address=%E7%99%BE%E5%BA%A6%E5%A4%A7%E5%8E%A6&output=json&ak=yourakyoursk
            String wholeStr = new String(url + "?" + paramsStr);

            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(wholeStr);
            if (client.executeMethod(get) == HttpServletResponse.SC_OK) {
                String str = new String(get.getResponseBody(), "UTF-8");
                Map m = (Map) JSON.parse(str);
                map = (Map) m.get("result");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 对Map内所有value作utf8编码,拼接返回结果
     *
     * @param data
     * @return
     * @throws java.io.UnsupportedEncodingException
     */
    public static String toQueryString(Map<?, ?> data)
            throws UnsupportedEncodingException {
        StringBuffer queryString = new StringBuffer();
        for (Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(URLEncoder.encode((String) pair.getValue(),
                    "UTF-8") + "&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }

    /**
     * 来自stackoverflow的MD5计算方法,调用了MessageDigest库函数,并把byte数组结果转换成16进制
     *
     * @param md5
     * @return
     */
    public String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
        }
        return null;
    }


    public static void main(String[] args) {
        //根据位置获取经纬度
        System.out.println("location-新加坡:" + GPSUtil.getLocation("新加坡"));
        System.out.println("省份-新加坡:" + getProvinceByGps("105.96171430209,26.258323531902"));


        System.out.println("location-贵州:" + GPSUtil.getLocation("贵州"));
        System.out.println("省份-贵州:" + getProvinceByGps("106.7349961033,26.902825927797"));


        System.out.println("location-日本:" + GPSUtil.getLocation("日本"));
        System.out.println("省份-日本:" + getProvinceByGps("99.778748988728,32.798321975722"));
//======================以下为根据逆地理信息获取===================================================
        //根据经纬度获取国家、省、市、街道等详细信息
        // System.out.println("gps:" + GPSUtil.getDetail("120.15759598139,30.252902354484"));

        //根据经纬度只获取省份
        System.out.println("location-内蒙古自治区:" + GPSUtil.getLocation("内蒙古自治区"));
        System.out.println("省份:" + getProvinceByGps(reverseLocation(GPSUtil.getLocation("内蒙古自治区"))));

        System.out.println("location-新疆维吾尔自治区:" + GPSUtil.getLocation("新疆维吾尔自治区"));
        System.out.println("省份:" + getProvinceByGps(reverseLocation(GPSUtil.getLocation("新疆维吾尔自治区"))));

        System.out.println("location-广西壮族自治区:" + GPSUtil.getLocation("广西壮族自治区"));
        System.out.println("省份:" + getProvinceByGps(reverseLocation(GPSUtil.getLocation("广西壮族自治区"))));

        System.out.println("location-西藏自治区:" + GPSUtil.getLocation("西藏自治区"));
        System.out.println("省份:" + getProvinceByGps(reverseLocation(GPSUtil.getLocation("西藏自治区"))));

        System.out.println("location-台湾省:" + GPSUtil.getLocation("高雄"));
        System.out.println("省份:" + getProvinceByGps(reverseLocation(GPSUtil.getLocation("高雄"))));
    }

}

百度GPSutil

标签:gps

原文地址:http://blog.csdn.net/chichengit/article/details/46349021

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!