本文已参与「新人创作礼」活动,一起开启掘金创作之路。
需求内容:将经纬度信息(38.88323,121.52051)转换成位置信息(辽宁省大连市甘井子区修远路)
需求背景:项目中有很多其他相关方发送的数据信息,其中部分的数据中只记录了其经纬度信息,未记录其行政区划等信息,当进行前台展示时,就会存在用户体验不好的问题,所以需要将该部分经纬度转换为实际的地理信息。
需提前准备内容:
1.百度地图API的账号(账号注册:lbsyun.baidu.com/ )该方法为调用百度的API获取数据,所以需要提前准备好百度地图API的账号信息。
2.百度地图的服务端AK(申请地址:lbsyun.baidu.com/apiconsole/… ) 目前创建服务之前需要进行实名制认证(吐槽一下,环节中的人脸识别还得手机下载百度APP),且账号有企业号和个人号的区别,若个人学习使用,建议个人号就可以。
以下为代码的样例
/**
*
*/
package idt.six.utils;
import com.alibaba.fastjson.JSON;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class LatLonToPlaceName {
private final static String AK = "";// 百度地图密钥
public static void main(String[] args) {
String lng="38.88323";//116.42 39.93
String lat="121.52051";
String reverseGeocode = reverseGeocode(lng,lat);
System.out.println(reverseGeocode);
}
/**
*
* @param lng 经度
* @param lat 纬度
* @return
*/
public static String reverseGeocode(String lng,String lat){
String location=lng+","+lat;
String url="http://api.map.baidu.com/reverse_geocoding/v3/?ak="+AK+"&output=json&coordtype=wgs84ll&location="+location;
System.out.println(url);
String res=doGet(url);
String Addresslocation= JSON.parseObject(res).getJSONObject("result").getString("formatted_address");
// System.out.println(Addresslocation);
return Addresslocation;
}
public static String doGet(String url) {
//创建一个Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//创建一个get请求
HttpGet httpGet = new HttpGet(url);
//响应模型
CloseableHttpResponse response = null;
try {
//由客户端发送get请求
response = httpClient.execute(httpGet);
//从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
return EntityUtils.toString(responseEntity);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}