谷歌地图行程从geoJSON文件

Google Map itinerary from geoJSON file

本文关键字:geoJSON 文件 谷歌地图      更新时间:2023-09-26

我想在这个geoJSON文件中定义的2个标记之间画一个行程:

{
"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文件中定义的2个点来替换"原点"answers"目的地",以便创建这两个点之间的行程。

你知道吗?

感谢您的帮助

一个可能的解决方案,使用谷歌地图数据层来显示您的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);