google-maps-services 计算两地距离

本人在做招聘网站开发时,遇到需要根据地址计算应聘者以及工作地的经纬度以及两者之间的距离。通过查找相关资料,决定使用google-maps-services插件。该插件使用比较简单。案例如下:


   com.google.maps
   google-maps-services
   0.2.9
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);

 

你可能感兴趣的:(google-map,java)