网上找到的一个使用高德API把地址转为经纬度的API

原创
2015/10/08 22:00
阅读数 4.1K
import com.fengyunhe.helper.http.HttpClientHelper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 焱 on 2015/9/28.
 */
public class TestGaode {
    private static String API = "http://restapi.amap.com/v3/geocode/geo?key=<key>&s=rsv3&address=<address>";

    private static String KEY = "aa4a48297242d22d2b3fd6eddfe62217";

    private static Pattern pattern = Pattern.compile("\"location\":\"(\\d+\\.\\d+),(\\d+\\.\\d+)\"");

    static {
        init();
    }

    private static void init() {
        System.out.println("高德地图工具类初始化");
        System.out.println("api: {}"+API);
        System.out.println("key: {}"+KEY);
        API = API.replaceAll("<key>", KEY);
    }

    public static double[] addressToGPS(String address) throws IOException {
        try {
            String requestUrl = API.replaceAll("<address>", URLEncoder.encode(address, "UTF-8"));
            System.out.println("请求地址: {}" + requestUrl);
            requestUrl = HttpClientHelper.INSTANCE.get(requestUrl);
            if (requestUrl != null ) {
                Matcher matcher = pattern.matcher(requestUrl);
                if (matcher.find() && matcher.groupCount() == 2) {
                    double[] gps = new double[2];
                    gps[0] = Double.valueOf(matcher.group(1));
                    gps[1] = Double.valueOf(matcher.group(2));
                    System.out.println("gps: {}" + Arrays.toString(gps));
                    return gps;
                }
            }
        } catch (UnsupportedEncodingException e) {
        }

        return null;
    }

    public static void main(String[] args) {
        try {
            System.out.println(TestGaode.addressToGPS("陕西省西安市雁塔区徐家庄村"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}





上面代码是在网上找到的,用到的HttpClientHelper可以在开源项目中看到源代码: http://git.oschina.net/277160299/helper

展开阅读全文
打赏
0
15 收藏
分享
加载中
更多评论
打赏
0 评论
15 收藏
0
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部