我正在尝试使用foreach循环将特定对象添加到数组中,但是我的代码导致数组中包含很多重复值(在本例中为76),而结果应为3。
然后将结果用于添加Google Maps Direction API的航点,并将其显示在网页上的Google Map中。
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>
答案 0 :(得分:1)
您不需要加倍。您已经处于与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
});
}
});
});
});