- GPS座標(經緯度)轉化爲地理位置(省市區)
- 兩個位置(經緯度)之間的距離,精確到米
- 需要導入GsonJsonParser相關的jar包或者maven依賴
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import static java.lang.Math.*;
import static java.lang.Math.PI;
//經緯度轉化爲省市區
@Component
public class LocationUtil {
private static Logger logger = LoggerFactory.getLogger(LocationUtil.class);
@Autowired
private RestTemplate restTemplate;
@Value("${com.address.analyze.urlString}")
private String urlString;
@Value("${com.address.analyze.user}")
private String urlUser;
/**
* 通過經緯度信息得到地理位置信息
*/
public String getAddress(String latitude, String longitude) throws RuntimeException{
//latitude 緯度
//longitude 經度
//http://116.196.105.215:1234/gis?auth_user=freevip&latitude=39.880655&longitude=116.354386
if (StringUtils.isBlank(longitude) || StringUtils.isBlank(latitude)) {
logger.debug("longitude or longitude is blank... longitude : {} , longitude : {}.", longitude, latitude);
throw new RuntimeException("fail.logOrLat.blank");
}
String url = urlString.replace("{auth_user}", urlUser)
.replace("{longitude}", longitude)
.replace("{latitude}", latitude);
String addressInfoString = restTemplate.getForObject(url, String.class);
Map<String, Object> addressInfo = new GsonJsonParser().parseMap(addressInfoString);
return analyzeAddressInfo(addressInfo);
}
/**
* 解析結果,得到省市區
*/
private String analyzeAddressInfo(Map<String, Object> addressInfo) {
Map<String, Object> locationMap = (Map<String, Object>) addressInfo.get("data");
if (locationMap == null || locationMap.isEmpty()) {
return "";
}
StringBuffer result = new StringBuffer();
for (Map.Entry<String, Object> entry : locationMap.entrySet()) {
if (entry.getKey().contains("zh")) {
result.append(entry.getValue());
}
}
return result.toString();
}
//高德地圖可以做驗證
//https://lbs.amap.com/api/javascript-api/example/calcutation/calculate-distance-between-two-markers
//https://lbs.amap.com/console/show/picker
/**
* 地球半徑
*/
private static double EARTH_RADIUS = 6378137;
/**
* 兩個經緯度之間的直線距離,精確到米
*/
public double getDistance(double lat1, double lng1, double lat2, double lng2) {
double radLat1 = Rad(lat1);
double radLng1 = Rad(lng1);
double radLat2 = Rad(lat2);
double radLng2 = Rad(lng2);
double a = radLat1 - radLat2;
double b = radLng1 - radLng2;
double result = 2 * asin(sqrt(pow(sin(a / 2), 2) + cos(radLat1) * cos(radLat2) * pow(sin(b / 2), 2))) * EARTH_RADIUS;
return result;
}
/**
* 經緯度轉化成弧度
*/
private double Rad(double d) {
return d * PI / 180d;
}
}
配置
#經緯度轉化爲省市區
com.address.analyze.urlString=http://116.196.105.215:1234/gis?auth_user={auth_user}&latitude={latitude}&longitude={longitude}
com.address.analyze.user=freevip