/**
* 通过经纬度获取地址名称
*
* @param latitude(维度), longitude(经度)
* @return address(地址)
*/
@GetMapping(value = "/getAddress")
public Result getAddress(@RequestParam(value = "LATITUDE") String latitude,
@RequestParam(value = "LONGITUDE") String longitude) {
Map<String, String> result = new HashMap<>();
result.put("ADDRESS", MapUtil.getAddressByLatAndLng(latitude, longitude));
return Result.buildResult(Result.Status.OK, result);
}
/**
* 通过地址获取经纬度
*
* @param
* @return address(地址)
*/
@GetMapping(value = "/getLatAndLngByAddress")
public Result getLatAndLng(@RequestParam(value = "ADDRESS") String address) {
return Result.buildResult(Result.Status.OK, MapUtil.getLatAndLngByAddress(address));
}
//数组转集合
private List<String> array2List(String[] strings) {
return Arrays.asList(strings);
}
//判断两个经纬度的距离
private static final double EARTH_RADIUS = 6378.137;//地球半径,单位千米
//将角度转为弧度
private static double rad(double d) {
return d * Math.PI / 180.0;
}
private static double getDistance(double lat1, double lng1, double lat2, double lng2) {
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = Math.round(s * 1000);
return s;
}
}
package springboot_001.utils;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.impl.client.DefaultHttpClient;
import springboot_001.safeguard.controller.WeLinkZBController;
import springboot_001.safeguard.entity.MapResult;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/**
* @author zhao pan
* @Date 16:19 2019/12/18
* @Description
*/
public class MapUtil {
public static final String ak = "1NKC2pNxVRKuPBdzkIrjiTAdiFE7VcyB";
// private static final String ak = "4IKgN0DzGVgiGtXW0hm8Z0OWsnYL7CuM";
// private static final String mapUrl = "172.30.68.94:8080";
public static final String mapUrl = "api.map.baidu.com";
public static String getAddressByLatAndLng(String latitude, String longitude) {
StringBuffer sb = new StringBuffer();
//创建HttpClient实例
HttpClient client = getHttpClient();
//创建httpGet
HttpGet httpGet = new HttpGet("http://" + mapUrl + "/reverse_geocoding/v3/?ak=" + ak + "&output=json&coordtype=wgs84ll&location=" + latitude + "," + longitude); //先维度(lati)后经度
//执行
try {
HttpResponse response = client.execute(httpGet);
HttpEntity entry = response.getEntity();
if (entry != null) {
InputStreamReader is = new InputStreamReader(entry.getContent());
BufferedReader br = new BufferedReader(is);
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str.trim());
}
br.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return "地址获取失败";
} catch (IOException e) {
e.printStackTrace();
return "地址获取失败";
}
Gson gson = new Gson();
MapResult mapResult = gson.fromJson(sb.toString(), MapResult.class);
if (mapResult.getResult() == null || mapResult.getResult().get("formatted_address") == null) {
return "地址获取失败";
}
return mapResult.getResult().get("formatted_address").toString();
}
public static Map<String, Object> getLatAndLngByAddress(String address) {
Map<String, Object> result = new HashMap<>();
StringBuffer sb = new StringBuffer();
//创建HttpClient实例
HttpClient client = getHttpClient();
//创建httpGet
HttpGet httpGet = new HttpGet("http://" + mapUrl + "/geocoding/v3/?ak=" + ak + "&output=json&callback=showLocation&address=" + address);
//执行
try {
HttpResponse response = client.execute(httpGet);
HttpEntity entry = response.getEntity();
if (entry != null) {
InputStreamReader is = new InputStreamReader(entry.getContent());
BufferedReader br = new BufferedReader(is);
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str.trim());
}
br.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return result;
} catch (IOException e) {
e.printStackTrace();
return result;
}
Gson gson = new Gson();
MapResult mapResult = gson.fromJson(sb.toString().replaceAll("showLocation&&showLocation\\(", "").replaceAll("\\)", ""), MapResult.class);
if(mapResult.getResult() == null) return result;
Map<String, Object> mapResultLocation = (Map<String, Object>) mapResult.getResult().get("location");
result.put("LATITUDE", mapResultLocation.get("lat")); //维度
result.put("LONGITUDE", mapResultLocation.get("lng")); //经度
return result;
}
public static Map<String, Object> getInfoByLatAndLng(String latitude, String longitude){
Map<String, Object> result = new HashMap<>();
StringBuffer sb = new StringBuffer();
//创建HttpClient实例
HttpClient client = getHttpClient();
//创建httpGet
HttpGet httpGet = new HttpGet("http://" + mapUrl + "/reverse_geocoding/v3/?ak=" + ak + "&output=json&coordtype=wgs84ll&location=" + latitude + "," + longitude); //先维度(lati)后经度
//执行
try {
HttpResponse response = client.execute(httpGet);
HttpEntity entry = response.getEntity();
if (entry != null) {
InputStreamReader is = new InputStreamReader(entry.getContent());
BufferedReader br = new BufferedReader(is);
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str.trim());
}
br.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return result;
} catch (IOException e) {
e.printStackTrace();
return result;
}
Gson gson = new Gson();
MapResult mapResult = gson.fromJson(sb.toString(), MapResult.class);
if (mapResult.getResult() == null || mapResult.getResult().get("formatted_address") == null) {
return result;
}
return ( Map<String, Object>)mapResult.getResult().get("addressComponent");
}
//设置代理
private static HttpClient getHttpClient() {
DefaultHttpClient httpClient = new DefaultHttpClient();
String proxyHost = "openproxy.huawei.com";
int proxyPort = 8080;
String userName = "bwx686365";
String password = "lmwda@1314";
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(proxyHost, proxyPort),
new UsernamePasswordCredentials(userName, password));
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
return httpClient;
}
}
根据地址信息获取经纬度
import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import net.sf.json.JSONObject;
public class LngAndLatUtil {
public static Map<String,Double> getLngAndLat(String address){
Map<String,Double> map=new HashMap<String, Double>();
String url = "http://api.map.baidu.com/geocoder/v2/?address="+address+"&output=json&ak=你自己的ak值";
String json = loadJSON(url);
JSONObject obj = JSONObject.fromObject(json);
if(obj.get("status").toString().equals("0")){
double lng=obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
double lat=obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
map.put("lng", lng);
map.put("lat", lat);
//System.out.println("经度:"+lng+"---纬度:"+lat);
}else{
//System.out.println("未找到相匹配的经纬度!");
}
return map;
}
public static String loadJSON (String url) {
StringBuilder json = new StringBuilder();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return json.toString();
}
}
//把代码中的ak值(红色字部分)更改为你自己的ak值,在百度地图API中注册一下就有。
//调用方式:
Map<String,Double> map=LngAndLatUtil.getLngAndLat("上海市黄浦区六合路");
System.out.println("经度:"+map.get("lng")+"---纬度:"+map.get("lat"));
百度API地址
百度开放平台后台地址