Java根据经纬度获取城市

1. 在百度地图开发平台里面创建应用,获取ak值

Java根据经纬度获取城市_第1张图片

2. 调用百度地图接口采用httpClient技术: 

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

public class HttpClientUtils {

    //传入经纬度, 返回查询的地区, lng: 纬度, lat: 经度
    public static String findByLatAndLng(String lng, String lat) {
        try {
            //移除坐标前后的 空格
            /*lng = lng.trim();
            lat = lat.trim();*/

            CloseableHttpClient httpClient = HttpClients.createDefault();
            // url中的ak值要替换成自己的:
            String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=百度地图ak值&output=json&coordtype=wgs84ll&location=" + lng + "," + lat;
            //System.out.println(url);
            HttpGet httpGet = new HttpGet(url);

            CloseableHttpResponse response = httpClient.execute(httpGet);

            HttpEntity httpEntity = response.getEntity();

            String json = EntityUtils.toString(httpEntity);

            Map result = JSONObject.parseObject(json, Map.class);
            if (result.get("status").equals(0)) {
                Map resultMap = (Map) result.get("result");
                resultMap = (Map) resultMap.get("addressComponent");
                String country = (String) resultMap.get("country");
                String province = (String) resultMap.get("province");
                String city = (String) resultMap.get("city");
                return country + province + city;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

3. 测试该工具类是否能用

Java根据经纬度获取城市_第2张图片

 

public static void main(String[] args) {
    //124.802554,51.132573  前边是纬度,  后边经度.
    //49.146493,126.568695
    String address = HttpClientUtils.findByLatAndLng("51.132573", "124.802554");
    System.out.println("地址是: " + address);
}

你可能感兴趣的:(java,开发语言,后端)