Search code examples
javascriptgoogle-mapsgoogle-maps-api-3directions

Multiple markers with google maps API route, drawn by distance


I'm creating a route on Google maps. The route has a start and endpoint with about 10 waypoints along the way.

What i'd like to do is 'walk' virtualy over this route, doing so i want to display a marker (depending on distance in meters) how far i have walked so far.

I've got it all set, the route, the distance in meters, the only thing that i cannot get to work is adding a marker ON the route.

Startpoint (0) ---------(marker 300 meter)-------------------- Endpoint (1000)

https://developers.google.com/maps/documentation/javascript/directions

I'm using the code as documented, here is my jscode fwiw

// I'm getting a startpoint (stockholm) endpoint (italy) and 
// array of 10 waypoints of other places in europe along the way

function initMap(startCoordinate, endCoordinate, waypoints) {
var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: { lat: 50.60, lng: 8.36 },
    mapTypeId: 'terrain'
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: false,
    map: map,
    panel: document.getElementById('right-panel')
});

var start = new google.maps.LatLng(startCoordinate);
var end = new google.maps.LatLng(endCoordinate);

directionsDisplay.addListener('directions_changed', function () {
    computeTotalDistance(directionsDisplay.getDirections());
});

displayRoute(start, end, directionsService, directionsDisplay, waypoints);
}

function displayRoute(origin, destination, service, display, waypoints) {

if (waypoints.length > 1)
{
    waypoints.shift();
    waypoints.pop();
}

service.route({
    origin: 'Centralplan 15, 111 20 Stockholm',
    destination: 'Piazza Giuseppe Garibaldi, 80142 Napoli, Italië',
    waypoints: waypoints,
    travelMode: 'DRIVING',
    avoidTolls: true
}, function (response, status) {
    if (status === 'OK') {
        display.setDirections(response);
    } else {
        console.log('Could not display directions due to: ' + status);
        console.log(response);
    }
});

I have looked into http://www.geocodezip.com/v3_animate_marker_directions.html but this is an animation on the route, i just need a still marker. It does however place a marker on route, i cannot seem to figure out exactly how it does that.


Solution

  • You will basically need to loop through the DirectionsLegs of your route, then in its DirectionsSteps and maybe substeps (DirectionsStep has an array of DirectionsSteps) until you find one which has your point A as start_location.

    So you will now have the equivalent of a portion of line, and will be able to do what's describe here.