我想使用另一个数组在 java 脚本数组中插入几个位置

I want to insert few location in to java script array using a another array

本文关键字:数组 插入 位置 几个 脚本 另一个 java      更新时间:2023-09-26

此函数获取几个位置之间的总距离。通常它适用于这个数组,而不遵循getLocations数组和for循环。

waypoints: [{location: 'Galle'},{location: 'Kandy'},{location: 'minneriya wildlife park'}, {location: 'Horton Plains'}],

现在我想使用 for 循环将这些位置插入到 getLocations 数组中,如下所示:

function getDistance() {
    var getLocations = ['Galle','Kandy', 'minneriya wildlife park', 'Horton Plains'];
    var request = {
        origin: getLocations[0],
        destination: getLocations[0],
        for (var i = 0; i < getLocations.length; i++) { 
            waypoints = [{location :getLocations[i]}]
        }
        waypoints,travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
} 

现在它无法正常工作。我在网上冲浪寻找解决方案,但找不到。请帮助我。我想知道它是如何以正确的方式工作的。谢谢

您的示例包含错误,特别是在初始化对象的行request waypoints数组无法以这种方式初始化。一种选择是将waypoints数组初始化置于对象初始化之外request如下所示。

固定示例

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var mapOptions = {
        zoom: 8
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    getDistance();
    directionsDisplay.setMap(map);
}
function getDistance() {
    var locations = ['Galle', 'Kandy', 'minneriya wildlife park', 'Horton Plains'];
    var waypoints = locations.map(function(loc) {
        return { 'location': loc };
    });
    var request = {
        origin: locations[0],
        destination: locations[0],
        waypoints: waypoints,
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
                height: 100%;
                margin: 0px;
                padding: 0px;
            }
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<div id="map-canvas"></div>