JavaScript 数组 foreach 循环会导致重复值



我正在尝试使用 foreach 循环将特定对象添加到数组中,但我的代码导致一个数组有很多重复值(在本例中:76(,而结果应该是 3。

然后,结果用于为谷歌地图方向API添加航点,并将其显示在网页上的谷歌地图中。

var directionsDisplay = new google.maps.DirectionsRenderer();
var directionService = new google.maps.DirectionsService();
var map;
var mapOptions = {
zoom: 14,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map)
var arr = [];
var beginpoint;
var endpoint;
$(document).ready(function() {
$.getJSON("https://api.jsonbin.io/b/5bc7956651e8b664f2bcce19", function(data) {
var json = []; // THE ARRAY TO STORE JSON ITEMS.
$.each(data, function(index, value) {
json.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
// Loop the JSON
var arrayLength = json.length;
for (var i = 0; i < arrayLength; i++) {
if (json[i].GENRE == "CRIME" && json[i].CONTINENT == "NOORD-AMERIKA") {
//console.log(json[i]); 
latLng = new google.maps.LatLng(json[i].BREEDTEGRAAD, json[i].LENGTEGRAAD);
arr.push({
location: latLng,
stopover: true
});
}
}
});
});
});
function calculateRoute() {
beginpoint = new google.maps.LatLng(arr[0].latitude, arr[0].longitude);
endpoint = new google.maps.LatLng(arr[0].latitude, arr[0].longitude);
console.log(arr);
var request = {
origin: beginpoint,
destination: endpoint,
waypoints: arr,
optimizeWaypoints: true,
travelMode: 'DRIVING'
};
directionService.route(request, function(result, status) {
if (status == "OK") {
directionsDisplay.setDirections(result);
} else {
console.log(result);
console.log(status);
alert("Er is iets fout gegaan");
}
});
}
document.getElementById('get').onclick = function() {
calculateRoute();
}
#map-canvas {
width: 500px;
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7deCJieASLxPQvF6qpX2xLi-mz6hKKSk&libraries=place" type="text/javascript"></script>
<div id="map-canvas"></div>
<button id="get">bereken</button>

你不需要双倍。您已经在 json 循环值中等于 json 中的对象。

试试这个:)

$(document).ready(function() {
$.getJSON("https://api.jsonbin.io/b/5bc7956651e8b664f2bcce19", function(data) {
$.each(data, function(index, value) {      
if (value.GENRE == "CRIME" && value.CONTINENT == "NOORD-AMERIKA") {
console.log(value); 
latLng = new google.maps.LatLng(value.BREEDTEGRAAD, value.LENGTEGRAAD);
arr.push({
location: latLng,
stopover: true
});
}
});
});
});

最新更新