-2

I would like to be able to estimate the distance traveled per country through the Google Maps APIs.

Example: the origin of my path is in Amsterdam (Netherlands) then I have one waypoint in Berlin (Germany) and the final destination is Warsaw (Poland).

I would like to estimate the amount of KM traveled per country.

I have searched through the Google Maps API but I could not find a way to do this.

The software program output should be something like:

  • Netherlands: 53km
  • Germany 504km
  • Poland 304km
MSalters
  • 173,980
  • 10
  • 155
  • 350
EllardDK
  • 1
  • 2
  • Look again https://developers.google.com/maps/documentation/javascript/distancematrix – Martheen Sep 04 '20 at 06:59
  • With that I can check the distance between two or more points, not per country, as far as I can see. Correct me if I am wrong. – EllardDK Sep 04 '20 at 07:12
  • Just use the geocoding https://developers.google.com/maps/documentation/javascript/geocoding It works even for vague input like country name https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple#maps_geocoding_simple-javascript – Martheen Sep 04 '20 at 07:26
  • To clarify, I'd like to know the distance to be traveled per country. So something along the lines of : Netherlands: 53km, Germany 504km and Poland: 304km. Could you point me in a direction how I would do that with geocoding? – EllardDK Sep 04 '20 at 07:46
  • From the route given, split them by the countries – Martheen Sep 04 '20 at 08:41
  • possible duplicate of [Google maps api v3 calculate mileage by state](https://stackoverflow.com/questions/34028829/google-maps-api-v3-calculate-mileage-by-state) (replace state with country). – geocodezip Sep 04 '20 at 12:43
  • "TomTom" tag remove.. (That's another map provider). – MSalters Sep 07 '20 at 13:48

1 Answers1

0

After messing around with it myself for a little bit I came to the following solution:

import turf from '@turf/turf'
import polyline from '@mapbox/polyline'
import shapefile from 'shapefile'

// The google routes api result
import data from './coords.js';

// The compete route polyline
const polydata = polyline.toGeoJSON(data.routes[0].overview_polyline.points);

async function fetchWorldData() {
    let worldData = [];
    try {
        let overBorder = false;

        // Load country borders shapeFile
        const source = await shapefile.open("TM_WORLD_BORDERS-0.3.shp");

        // Loop over all countries
        while (true) {
            // Read the source for a specific country
            const result = await source.read();
            if (result.done) break;

            // Check if the trip will cross any borders, if they do, set overBorder to true
            if (turf.lineIntersect(polydata, result.value.geometry).features.length !== 0) {
                overBorder = true;

                // Append intersected borders
                worldData.push(result.value);
            }
        }


        // Return a list with all the country data
        return worldData;

    } catch (e) {
        console.log(e);
    }
}

async function makePrediction() {
    console.time("execution time");
    // Object to returned

    let countries = []

    // When leaving a border you will intersect with it(1) You will then intersect with the next border (2) causing another intersect.
    // This bool ignores the entering intersect.
    let ignoreNextBorder = false;

    try {
        // Fetch the world data
        let worldData = await fetchWorldData();

        worldData.map(async border => {
            // Store distance and duration per country
            let distance = 0;
            let duration = 0;

            data.routes[0].legs[0].steps.map(async (step) => {
                // Get the step starting point
                let pt = turf.point([step.start_location.lng, step.start_location.lat]);
                const pointInCountry = turf.booleanPointInPolygon(pt, border.geometry);

                // Check if the step starting point is in the current country
                if (pointInCountry) {
                    // Add the step distance to the total
                    distance += step.distance.value;
                    duration += step.duration.value;
                }
            });

            countries[border.properties.NAME] = {
                duration: duration,
                distance: distance
            }
        });

        console.timeEnd("execution time");

        return countries;
    } catch (e) {
        console.log(e)
    }
}

makePrediction().then(console.log);

You can pass a different shape file if you would want to. It displays the results like so: Example result

The downside is, countries are not ordered. But this suits my needs plenty fine.

EllardDK
  • 1
  • 2