本人在做招聘網站開發時,遇到需要根據地址計算應聘者以及工作地的經緯度以及兩者之間的距離。通過查找相關資料,決定使用google-maps-services插件。該插件使用比較簡單。案例如下:
<dependency>
<groupId>com.google.maps</groupId>
<artifactId>google-maps-services</artifactId>
<version>0.2.9</version>
</dependency>
public class GoogleMapUtil {
//google map
@Value("${googleMap.key}")
private String googleMapKey;
private static final double EARTH_RADIUS = 6378137;
private static double rad(double d)
{
return d * Math.PI / 180.0;
}
public static double GetDistance(double lon1,double lat1,double lon2, double lat2)
{
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lon1) - rad(lon2);
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 * 10000) / 10000;
return s*0.621;
}
public LatLng getGeocoding(String address) {
try {
GeoApiContext context = new GeoApiContext.Builder().apiKey(googleMapKey).build();
GeocodingResult[] results = GeocodingApi.geocode(context, address).await();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(results[0].addressComponents));
System.out.println(gson.toJson(results[0].geometry.location));
LatLng location = results[0].geometry.location;
return location;
} catch (ApiException e) {
} catch (InterruptedException e) {
} catch (IOException e) {
} catch (Exception e) {
}
return null;
}
根據地址獲取相應的經緯度
final LatLng location = googleMapUtil.getGeocoding("location");
Double latitude = location.lat;
Double longitude = location.lng;
根據兩者間的經緯度計算距離
final double distance = GoogleMapUtil.getDistance(jobLongitude, jobLatitude, applicantLongitude, applicantLatitude);