Java(百度地图API)使用坐标的经纬度得到具体的城市信息

百度API中的全球逆地理编码服务提供将坐标点(经纬度)转换为对应位置信息(所在行政区划,周边地标点分布)功能。

百度API全球逆地理编码服务网页链接

 访问的URL是:

http://api.map.baidu.com/reverse_geocoding/v3/?ak=您的ak&output=json&coordtype=wgs84ll
&location=纬度,经度  //GET请求

因为使用百度地图的API就要申请AK,申请链接如下 

 申请百度地图AK的链接

//JSON转化为MAP函数中需要
<dependency>
	<groupId>net.sf.json-lib</groupId>
	<artifactId>json-lib</artifactId>
	<version>2.4</version>
	<classifier>jdk15</classifier>
</dependency>

//通过经纬度获得城市信息中需要
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.11</version>
</dependency>

 通过经纬度得到具体城市信息

public static Map<String,Object> getcitydetailbyjingwei(double jing ,double wei)
    { 
        Map<String, Object> map = null; 
        String url = "http://api.map.baidu.com/reverse_geocoding/v3/?" 
+ "ak=你的AK&output=json&coordtype=wgs84ll&location="
                +wei+","+jing;
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            JSONObject res = JSONObject.fromObject(content);
            map = JsonUtil.parseJSON2Map(res); //通过下面的函数将json转化为map
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("获取地址失败"); 
        }
        return map;
    }

通过下面的方法将JSON转化为Map


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
public class JsonUtil {
    public static Map<String, Object> parseJSON2Map(JSONObject json) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 最外层解析
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            // 如果内层还是数组的话,继续解析
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                @SuppressWarnings("unchecked")
                Iterator<JSONObject> it = ((JSONArray) v).iterator();
                while (it.hasNext()) {
                    JSONObject json2 = it.next();
                    list.add(parseJSON2Map(json2));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }
}

输入经度和纬度:118.46566         36.55001

得到的结果

发布了183 篇原创文章 · 获赞 26 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/SEVENY_/article/details/104475054