Skip to content Skip to sidebar Skip to footer

Google Map Itinerary From Geojson File

I'd like to draw an itinerary between 2 markers which are defined in this geoJSON file: { 'type': 'FeatureCollection', 'features': [ { 'type': 'Feature', 'geometry':

Solution 1:

One possible solution, use the Google Maps Data Layer to display your GeoJSON. The use it to retrieve the coordinates and get directions between them. The below code assumes 2 points (and uses your example with 2 points):

working fiddle

functioncalculate() {
    var request = {
        origin: origin,
        destination: destination,


        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

// global variablesvar origin = null;
var destination = null;
var infowindow = new google.maps.InfoWindow();
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();

functioninitialize() {
    // Create a simple map.
    features = [];
    map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 4,
        center: {
            lat: -28,
            lng: 137.883
        }
    });
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directions-panel'));
    google.maps.event.addListener(map, 'click', function () {
        infowidow.close();
    });
    // process the loaded GeoJSON data.
    google.maps.event.addListener(map.data, 'addfeature', function (e) {
        if (e.feature.getGeometry().getType() === 'Point') {
            map.setCenter(e.feature.getGeometry().get());
            // set the origin to the first pointif (!origin) origin = e.feature.getGeometry().get();
            // set the destination to the second pointelseif (!destination) {
                destination = e.feature.getGeometry().get();
                // calculate the directions once both origin and destination are set calculate();
            }
        }
    });
    map.data.addGeoJson(data);
}

google.maps.event.addDomListener(window, 'load', initialize);

Post a Comment for "Google Map Itinerary From Geojson File"