Маршрут Google Map из файла geoJSON

Я хотел бы нарисовать маршрут между двумя маркерами, которые определены в этом файле geoJSON:

{
"type": "FeatureCollection",
"features":

 [

    { "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [-73.563032, 45.495403]},
        "properties": {"prop0": "value0"}
    },

    { "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [-73.549762, 45.559673]},
        "properties": {"prop0": "value0"}
    }
]

}

Два маркера хорошо отображаются на карте.

Теперь я хочу создать маршрут (автомобиль) между этими двумя точками.

У меня есть эта функция javascript, которая позволяет мне рисовать маршрут из формы, заполненной пользователем:

function calculate() {

origin      =   document.getElementById('origin').value;
destination =   document.getElementById('destination').value;


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);
     }
   });
  }

А теперь я хотел бы заменить «источник» и «пункт назначения» двумя точками, определенными в моем файле geoJSON, чтобы создать маршрут между этими двумя точками.

Есть идеи ?

Спасибо за помощь !


person Tibo M    schedule 30.07.2014    source источник
comment
Как вы отображаете данные GeoJSON? Общий ответ на ваш вопрос будет состоять в том, чтобы проанализировать GeoJSON для координат, превратить их в объекты google.maps.LatLng и передать их в службу маршрутов.   -  person geocodezip    schedule 30.07.2014


Ответы (1)


Одним из возможных решений является использование слоя данных Google Maps для отображения вашего GeoJSON. Используйте его, чтобы получить координаты и проложить маршрут между ними. В приведенном ниже коде предполагается 2 балла (и используется ваш пример с 2 баллами):

рабочая скрипта

function calculate() {
    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 variables
var origin = null;
var destination = null;
var infowindow = new google.maps.InfoWindow();
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();

function initialize() {
    // 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 point
            if (!origin) origin = e.feature.getGeometry().get();
            // set the destination to the second point
            else if (!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);
person geocodezip    schedule 31.07.2014