欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用百度API获取地址的经纬度

程序员文章站 2022-06-04 13:38:05
...

文档地址:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

package com.jackrain.nea.cp.utility;

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

/**
 * @Author: wangqiang
 * @Date: 2019/1/29 9:04
 * @Version 1.0
 * lat 纬度值
 * lng 经度值
 * AK 过期自行申请
 * 	gcj02ll(国测局坐标)、bd09mc(百度墨卡托坐标)
 */
public class GetLatAndLngByAddress {
    public static  Map<String, BigDecimal> getLatAndLngByAddress(String addr){
        String address = "";
        //纬度值
        String lat = "";
        //经度值
        String lng = "";
        try {
            address = java.net.URLEncoder.encode(addr,"UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String url = String.format("http://api.map.baidu.com/geocoder/v2/?"
                +"ak=uWR5t7n00V7KohEwLOK7ffIk40GziUUy&output=json&address=%s&ret_coordtype=gcj02ll",address);
        URL myURL = null;
        URLConnection httpsConn = null;
        //进行转码
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {

        }
        try {
            httpsConn = (URLConnection) myURL.openConnection();
            if (httpsConn != null) {
                InputStreamReader insr = new InputStreamReader(
                        httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                String data = null;
                if ((data = br.readLine()) != null) {
                    lat = data.substring(data.indexOf("\"lat\":")
                            + ("\"lat\":").length(), data.indexOf("},\"precise\""));
                    lng = data.substring(data.indexOf("\"lng\":")
                            + ("\"lng\":").length(), data.indexOf(",\"lat\""));
                }
                insr.close();
            }
        } catch (IOException e) {

        }
        Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
        map.put("latitudu", new BigDecimal(lat));
        map.put("longitude", new BigDecimal(lng));
        return map;
    }

    public static void main(String[] args) {
        Map<String, BigDecimal> decimalMap = getLatAndLngByAddress("上海市闵行区黎安路999号大虹桥国际5F");
        System.out.println(decimalMap);
    }
}

 

相关标签: API