Reputation: 128
Good day fellow Stackers,
I have a working example of my dilemma here.
It's an old problem, so I do apologize. I'm struggling because other examples have the map locations stored in a simple array, while mine is stored in a object. I was working off someone else's code from here.
I'm sure my code is a chaotic, but I managed to get pull the relevant values from the keys, however when I apply google maps javascript functions or other methods, they just don't seem to work. Even though it is listening for the markers.
Any help would be much appreciated!
Here is an extract of the code I am struggling with:
document.getElementById('type').addEventListener("change", function() {
for (var i=0; i<markers.length; i++) {
marker = gmarkers1[i];
console.log(markers[i]);
for (var key in markers[i]) {
console.log(markers[i].category);
if (markers[i].category == data || data.length === 0) {
console.log(data);
marker.setVisible(false);
} else {
console.log(data);
marker.setVisible(false);
}
}
}
});
Upvotes: 0
Views: 1914
Reputation: 426
Another way would be to remove all markers and only recreate the markers that have the category that you want.
First I created a flag markersExist
to check if there are existing markers and delete them.
var markersExist = false; //flag to clear markers already on the map
document.getElementById('type').addEventListener("change", function() {
var filter = document.getElementById('type').value;
//removes all Markers from map first.
if(markersExist == true){
for (var i = 0; i < gmarkers1.length; i++) {
gmarkers1[i].setMap(null);
}
gmarkers1 = [];
}
The I modified to the loop to check for markers.category
and create them if they coincide with the category filter
.
for (var i=0; i<markers.length; i++) {
if(filter == markers[i].category){
var data = markers[i];
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
icon: icons[data.type].icon,
category: category
});
gmarkers1.push(marker);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + data.description + "</div>");
infoWindow.open(map, marker);
});
});
markersExist = true;
}
I modified your code in this jsfiddle.
Upvotes: 1