如何将十几个坐标转换为路线?有没有网站或方法可以粘贴到谷歌地图上? 谢谢你
您可以利用 Directions Service API 来实现此目的。下面的示例展示了如何在 Google 地图中读取坐标并打印路线:
var data = JSON.parse($("#textCoordinates").val()); //read coordinates from textarea element
var converter = new GPSMapConverter();
converter.printRoute(data);
哪里
坐标以以下 JSON 格式提供:
[
{
"lat": 41.879676,
"lng": -87.632599
},
{
"lat": 39.908601,
"lng": -86.149237
},
{
"lat": 40.009653,
"lng": -83.012640
},
{
"lat": 40.440311,
"lng": -79.990691
},
{
"lat": 38.979612,
"lng": -77.008612
}
]
和
GPSMapConverter
:
var GPSMapConverter = function () {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(57.9865525, 25.40965)
};
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsService = new google.maps.DirectionsService;
};
GPSMapConverter.prototype = {
clearRoute: function() {
if (this.directionsDisplay != null) {
this.directionsDisplay.setMap(null);
}
},
printRoute: function(coordinates) {
var directionWaypoints = $.map(coordinates, function(coord, i) {
if (i > 0 && i < coordinates.length - 1) {
return {
"location": new google.maps.LatLng(coord.lat, coord.lng),
"stopover": false
};
}
});
var request = {
origin: new google.maps.LatLng(coordinates[0].lat, coordinates[0].lng),
destination: new google.maps.LatLng(coordinates[coordinates.length - 1].lat, coordinates[coordinates.length - 1].lng),
travelMode: google.maps.TravelMode.DRIVING,
waypoints: directionWaypoints
};
this.calculateAndDisplayRoute(request);
},
calculateAndDisplayRoute: function (request) {
this.directionsDisplay.setMap(this.map);
(function(display,service) {
service.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
})(this.directionsDisplay, this.directionsService);
}
};
源代码:Plunker
实例:应用程序
您可以使用的坐标数量可能有限制,但请尝试以下操作:https://www.google.com/maps/dir/XX.XXXXX,-YY.YYYYY/ AA.AAAAA,-BB.BBBBB/ CC.CCCCCC,-DD.DDDDD/ 等等