I'm trying to add specific objects into an array using a foreach loop but my code results in an array that has lots of duplicate values (in this case: 76) while the result should be 3.
The result is then used to add waypoints for the Google Maps Direction API and display it in the Google Map on the web page.
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>