Through the Java Google Maps SDK, you can get the lat/lng for a specific address, then using the haversine distance formula to get the distance in KM.
<dependency>
<groupId>com.google.maps</groupId>
<artifactId>google-maps-services</artifactId>
<version>2.2.0</version>
</dependency>
Code:
public static Double getDistanceInKmAsTheCrowFlies(String apiKey, String address1, String address2)
{
GeocodingResult[] address1GeoCode = getGeocoding(apiKey, address1);
GeocodingResult[] address2GeoCode = getGeocoding(apiKey, address2);
if (address1GeoCode != null && address2GeoCode != null)
{
double lat1 = address1GeoCode[0].geometry.location.lat;
double lng1 = address1GeoCode[0].geometry.location.lng;
double lat2 = address2GeoCode[0].geometry.location.lat;
double lng2 = address2GeoCode[0].geometry.location.lng;
return getHaversineDistance(lat1, lng1, lat2, lng2);
}
return null;
}
public static GeocodingResult[] getGeocoding(String apiKey, String address)
{
GeocodingApiRequest req = GeocodingApi.newRequest(new GeoApiContext.Builder()
.apiKey(apiKey)
.build());
GeocodingResult[] query = req.address(address).awaitIgnoreError();
if (query != null && query.length > 0)
{
return query;
}
return null;
}
public static double getHaversineDistance(double lat1, double lng1, double lat2, double lng2)
{
int r = 6371; // average radius of the earth in km
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = r * c;
return d;
}