我想在这个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个点替换“origin”和“destination”,以便在这两个点之间创建一个行程。
有什么想法吗?
感谢您的帮助!
答案 0 :(得分:0)
一种可能的解决方案,使用Google地图数据层显示您的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);