Search in sources :

Example 1 with DistanceMatrix

use of com.google.maps.model.DistanceMatrix in project Employee-Self-Service by nysenate.

the class GoogleMapsService method drivingDistance.

/**
 * Calculates the driving distance in miles from one address to another.
 * @param from The starting address.
 * @param to The ending address.
 */
@Override
public double drivingDistance(GoogleAddress from, GoogleAddress to) throws InterruptedException, ApiException, IOException {
    String[] origins = new String[] { getGoolgeAddressParam(from) };
    String[] destinations = new String[] { getGoolgeAddressParam(to) };
    DistanceMatrix request = DistanceMatrixApi.getDistanceMatrix(context, origins, destinations).mode(TravelMode.DRIVING).departureTime(java.time.Instant.ofEpochMilli(DateTime.now().toInstant().getMillis())).trafficModel(TrafficModel.OPTIMISTIC).units(Unit.IMPERIAL).await();
    long meters = 0;
    if (request.rows[0].elements[0].distance != null) {
        meters = request.rows[0].elements[0].distance.inMeters;
    }
    return UnitUtils.metersToMiles(meters).doubleValue();
}
Also used : DistanceMatrix(com.google.maps.model.DistanceMatrix)

Example 2 with DistanceMatrix

use of com.google.maps.model.DistanceMatrix in project shopizer by shopizer-ecommerce.

the class ShippingDistancePreProcessorImpl method prePostProcessShippingQuotes.

public void prePostProcessShippingQuotes(ShippingQuote quote, List<PackageDetails> packages, BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store, IntegrationConfiguration globalShippingConfiguration, IntegrationModule currentModule, ShippingConfiguration shippingConfiguration, List<IntegrationModule> allModules, Locale locale) throws IntegrationException {
    if (delivery.getZone() == null) {
        return;
    }
    boolean zoneAllowed = false;
    if (allowedZonesCodes != null) {
        for (String zoneCode : allowedZonesCodes) {
            if (zoneCode.equals(delivery.getZone().getCode())) {
                zoneAllowed = true;
                break;
            }
        }
    }
    if (!zoneAllowed) {
        return;
    }
    if (StringUtils.isBlank(delivery.getPostalCode())) {
        return;
    }
    Validate.notNull(apiKey, "Requires the configuration of google apiKey");
    GeoApiContext context = new GeoApiContext().setApiKey(apiKey);
    // build origin address
    StringBuilder originAddress = new StringBuilder();
    originAddress.append(origin.getAddress()).append(BLANK).append(origin.getCity()).append(BLANK).append(origin.getPostalCode()).append(BLANK);
    if (!StringUtils.isBlank(origin.getState())) {
        originAddress.append(origin.getState()).append(" ");
    }
    if (origin.getZone() != null) {
        originAddress.append(origin.getZone().getCode()).append(" ");
    }
    originAddress.append(origin.getCountry().getIsoCode());
    // build destination address
    StringBuilder destinationAddress = new StringBuilder();
    destinationAddress.append(delivery.getAddress()).append(BLANK);
    if (!StringUtils.isBlank(delivery.getCity())) {
        destinationAddress.append(delivery.getCity()).append(BLANK);
    }
    destinationAddress.append(delivery.getPostalCode()).append(BLANK);
    if (!StringUtils.isBlank(delivery.getState())) {
        destinationAddress.append(delivery.getState()).append(" ");
    }
    if (delivery.getZone() != null) {
        destinationAddress.append(delivery.getZone().getCode()).append(" ");
    }
    destinationAddress.append(delivery.getCountry().getIsoCode());
    try {
        GeocodingResult[] originAdressResult = GeocodingApi.geocode(context, originAddress.toString()).await();
        GeocodingResult[] destinationAdressResult = GeocodingApi.geocode(context, destinationAddress.toString()).await();
        if (originAdressResult.length > 0 && destinationAdressResult.length > 0) {
            LatLng originLatLng = originAdressResult[0].geometry.location;
            LatLng destinationLatLng = destinationAdressResult[0].geometry.location;
            delivery.setLatitude(String.valueOf(destinationLatLng.lat));
            delivery.setLongitude(String.valueOf(destinationLatLng.lng));
            // keep latlng for further usage in order to display the map
            DistanceMatrix distanceRequest = DistanceMatrixApi.newRequest(context).origins(new LatLng(originLatLng.lat, originLatLng.lng)).destinations(new LatLng(destinationLatLng.lat, destinationLatLng.lng)).awaitIgnoreError();
            if (distanceRequest != null) {
                DistanceMatrixRow distanceMax = distanceRequest.rows[0];
                Distance distance = distanceMax.elements[0].distance;
                quote.getQuoteInformations().put(Constants.DISTANCE_KEY, 0.001 * distance.inMeters);
            } else {
                LOGGER.error("Expected distance inner google api to return DistanceMatrix, it returned null. API key might not be working for this request");
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while calculating the shipping distance", e);
    }
}
Also used : GeocodingResult(com.google.maps.model.GeocodingResult) LatLng(com.google.maps.model.LatLng) DistanceMatrix(com.google.maps.model.DistanceMatrix) GeoApiContext(com.google.maps.GeoApiContext) DistanceMatrixRow(com.google.maps.model.DistanceMatrixRow) Distance(com.google.maps.model.Distance) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException)

Example 3 with DistanceMatrix

use of com.google.maps.model.DistanceMatrix in project google-maps-services-java by googlemaps.

the class DistanceMatrixApiTest method testGetDistanceMatrixWithBasicStringParams.

@Test
public void testGetDistanceMatrixWithBasicStringParams() throws Exception {
    try (LocalTestServerContext sc = new LocalTestServerContext(getDistanceMatrixWithBasicStringParams)) {
        String[] origins = new String[] { "Perth, Australia", "Sydney, Australia", "Melbourne, Australia", "Adelaide, Australia", "Brisbane, Australia", "Darwin, Australia", "Hobart, Australia", "Canberra, Australia" };
        String[] destinations = new String[] { "Uluru, Australia", "Kakadu, Australia", "Blue Mountains, Australia", "Bungle Bungles, Australia", "The Pinnacles, Australia" };
        DistanceMatrix matrix = DistanceMatrixApi.getDistanceMatrix(sc.context, origins, destinations).await();
        assertNotNull(matrix.toString());
        assertNotNull(Arrays.toString(matrix.rows));
        // Rows length will match the number of origin elements, regardless of whether they're
        // routable.
        assertEquals(8, matrix.rows.length);
        assertEquals(5, matrix.rows[0].elements.length);
        assertEquals(DistanceMatrixElementStatus.OK, matrix.rows[0].elements[0].status);
        assertEquals("Perth WA, Australia", matrix.originAddresses[0]);
        assertEquals("Sydney NSW, Australia", matrix.originAddresses[1]);
        assertEquals("Melbourne VIC, Australia", matrix.originAddresses[2]);
        assertEquals("Adelaide SA, Australia", matrix.originAddresses[3]);
        assertEquals("Brisbane QLD, Australia", matrix.originAddresses[4]);
        assertEquals("Darwin NT, Australia", matrix.originAddresses[5]);
        assertEquals("Hobart TAS 7000, Australia", matrix.originAddresses[6]);
        assertEquals("Canberra ACT 2601, Australia", matrix.originAddresses[7]);
        assertEquals("Uluru, Petermann NT 0872, Australia", matrix.destinationAddresses[0]);
        assertEquals("Kakadu NT 0822, Australia", matrix.destinationAddresses[1]);
        assertEquals("Blue Mountains, New South Wales, Australia", matrix.destinationAddresses[2]);
        assertEquals("Purnululu National Park, Western Australia 6770, Australia", matrix.destinationAddresses[3]);
        assertEquals("Pinnacles Drive, Cervantes WA 6511, Australia", matrix.destinationAddresses[4]);
        sc.assertParamValue(StringUtils.join(origins, "|"), "origins");
        sc.assertParamValue(StringUtils.join(destinations, "|"), "destinations");
    }
}
Also used : DistanceMatrix(com.google.maps.model.DistanceMatrix) Test(org.junit.Test)

Aggregations

DistanceMatrix (com.google.maps.model.DistanceMatrix)3 GeoApiContext (com.google.maps.GeoApiContext)1 Distance (com.google.maps.model.Distance)1 DistanceMatrixRow (com.google.maps.model.DistanceMatrixRow)1 GeocodingResult (com.google.maps.model.GeocodingResult)1 LatLng (com.google.maps.model.LatLng)1 IntegrationException (com.salesmanager.core.modules.integration.IntegrationException)1 Test (org.junit.Test)1