package com.baidu.demo;
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
/**
* 功能描述: 调用百度地图Api实现经纬度的获取
* @author WeiGang.
* @version v1.0
* @date 2019/11/23 10:07
*/
public class LatitudeUtils {
private static final String KEY_1 = "HgVeUZy5grgtZYlBy3yO5kr6WxwWLLP1";
/**
* 功能描述: 返回输入地址的经纬度坐标
* @param address 地址
* @return {@link Map< String, String>} lng(经度),lat(纬度)
* @author WeiGang.
* @date 2019/11/23 10:05
* @version v1.0
*/
public static Map<String, String> getGeocoderLatitude(String address) {
BufferedReader in = null;
try {
//将地址转换成utf-8的16进制
address = URLEncoder.encode(address, "UTF-8");
//如果有代理,要设置代理,没代理可注释
//System.setProperty("http.proxyHost","192.168.1.188");
//System.setProperty("http.proxyPort","3128");
URL tirc = new URL("http://api.map.baidu.com/geocoder?address=" + address + "&output=json&key=" + KEY_1);
in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
String res;
StringBuilder sb = new StringBuilder("");
while ((res = in.readLine()) != null) {
sb.append(res.trim());
}
String str = sb.toString();
Map<String, String> map = null;
if (StringUtils.isNotEmpty(str)) {
int lngStart = str.indexOf("lng\":");
int lngEnd = str.indexOf(",\"lat");
int latEnd = str.indexOf("},\"precise");
if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
String lng = str.substring(lngStart + 5, lngEnd);
String lat = str.substring(lngEnd + 7, latEnd);
map = new HashMap<>();
map.put("lng", lng);
map.put("lat", lat);
return map;
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 功能描述: 转化为弧度(rad)
* @param d 半径
* @return {@link double}
* @author WeiGang.
* @date 2019/11/25 20:12
* @version v1.0
*/
private static double rad(double d) {
return d * Math.PI / 180.0;
}
/**
* 功能描述: 通过经纬度获取距离(单位:米)
* @param lat1 纬度1
* @param lng1 经度1
* @param lat2 纬度2
* @param lng2 经度2
* @return {@link double}
* @author WeiGang.
* @date 2019/11/25 20:12
* @version v1.0
*/
public 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 * 10000d) / 10000d;
s = s * 1000;
return s;
}
public static void main(String args[]) throws Exception {
Map<String, String> json = LatitudeUtils.getGeocoderLatitude("四川省成都市武侯区");
System.out.println("lng : " + json.get("lng"));
System.out.println("lat : " + json.get("lat"));
}
}