输入地址计算出经纬度一次实践
注意:
1、提供的地址尽量标准、精确;
2、先到天地图官网注册账号,申请应用,拿到tk,只能计算国内的地址;
3、本文使用的计算接口为“天地图”提供,百度也有类似的接口
package com.test.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
public class HttpClientUtils {
private HttpClientUtils() {
}
/**
* 封装HTTP POST方法
*
* @param
* @param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String post(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpPost.setConfig(requestConfig);
List<NameValuePair> formParams = setHttpParams(paramMap);
UrlEncodedFormEntity param = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(param);
HttpResponse response = httpClient.execute(httpPost);
log.info("************{}", response);
String httpEntityContent = getHttpEntityContent(response);
log.info("************{}", httpEntityContent);
httpPost.abort();
log.info("************{}", httpEntityContent);
return httpEntityContent;
}
/**
* 封装HTTP POST方法
*
* @param
* @param (如JSON串)
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String post(String url, String data) throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "text/json; charset=utf-8");
httpPost.setEntity(new StringEntity(URLEncoder.encode(data, "UTF-8")));
HttpResponse response = httpClient.execute(httpPost);
String httpEntityContent = getHttpEntityContent(response);
httpPost.abort();
return httpEntityContent;
}
/**
* 封装HTTP GET方法
*
* @param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String get(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet();
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpGet.setConfig(requestConfig);
httpGet.setURI(URI.create(url));
HttpResponse response = httpClient.execute(httpGet);
String httpEntityContent = getHttpEntityContent(response);
httpGet.abort();
return httpEntityContent;
}
/**
* 封装HTTP GET方法
*
* @param
* @param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String get(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet();
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpGet.setConfig(requestConfig);
List<NameValuePair> formparams = setHttpParams(paramMap);
String param = URLEncodedUtils.format(formparams, "UTF-8");
httpGet.setURI(URI.create(url + "?" + param));
HttpResponse response = httpClient.execute(httpGet);
String httpEntityContent = getHttpEntityContent(response);
httpGet.abort();
return httpEntityContent;
}
/**
* 封装HTTP PUT方法
*
* @param
* @param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String put(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpPut.setConfig(requestConfig);
List<NameValuePair> formparams = setHttpParams(paramMap);
UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPut.setEntity(param);
HttpResponse response = httpClient.execute(httpPut);
String httpEntityContent = getHttpEntityContent(response);
httpPut.abort();
return httpEntityContent;
}
/**
* 封装HTTP DELETE方法
*
* @param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String delete(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete();
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpDelete.setConfig(requestConfig);
httpDelete.setURI(URI.create(url));
HttpResponse response = httpClient.execute(httpDelete);
String httpEntityContent = getHttpEntityContent(response);
httpDelete.abort();
return httpEntityContent;
}
/**
* 封装HTTP DELETE方法
*
* @param
* @param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String delete(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete();
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpDelete.setConfig(requestConfig);
List<NameValuePair> formparams = setHttpParams(paramMap);
String param = URLEncodedUtils.format(formparams, "UTF-8");
httpDelete.setURI(URI.create(url + "?" + param));
HttpResponse response = httpClient.execute(httpDelete);
String httpEntityContent = getHttpEntityContent(response);
httpDelete.abort();
return httpEntityContent;
}
/**
* 设置请求参数
*
* @param
* @return
*/
private static List<NameValuePair> setHttpParams(Map<String, String> paramMap) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> set = paramMap.entrySet();
for (Map.Entry<String, String> entry : set) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return formparams;
}
/**
* 获得响应HTTP实体内容
*
* @param response
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = br.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line + "\n");
line = br.readLine();
}
return sb.toString();
}
return "";
}
}
package com.test.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 根据地址计算经纬度的工具类
* 地址尽量为:省市县区直到街道的精确地地址,这样避免计算出来的经纬度相差太大
*/
@Slf4j
public class AddrToLatAndLngUtil {
private static final Logger log = LoggerFactory.getLogger(AddrToLatAndLngUtil.class);
/**
* 使用天地图的API
*/
private static final String URL = "http://api.tianditu.gov.cn/geocoder?ds=%7B";
/**
* 需要先到天地图的官网注册地址,然后获取到tk
*/
private static final String TK = "dbf034b94da323053c0fcedb3adfaec5";
public static String calculateLatAndLngByAddr(String addr) {
try {
String res = null;
//去掉一些非法的标识符、空格等
addr = addr.replace(" ", "").replace("#", "").replace("中国", "");
String queryStr = URL + "'keyWord':'" + addr + "'%7D&tk=" + TK;
String info = HttpClientUtils.get(queryStr);
if (StringUtils.isNotBlank(info)) {
JSONObject resultJson = JSON.parseObject(info);
if (!"无结果".equals(resultJson.get("msg"))) {
JSONObject locationObj = (JSONObject) resultJson.get("location");
//纬度
String lat = locationObj.get("lat") + "";
//经度
String lng = locationObj.get("lon") + "";
res = "经纬度:" + lng + "," + lat;
}
}
return res;
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
log.info("经纬度为:" + calculateLatAndLngByAddr("广西壮族自治区柳州市城中区学院路33号"));
}
}
输出结果:
程序改变世界