I am creating a map, using gmaps.js, that has different types of markers (parking, residence and academic). The removeMarkers()
function of gmaps.js does not take any arguments, it just hides everything.
My goal is to have checkboxes for each category that show/hide the corresponding markers if the checkbox is checked or not. Similar to this JSFiddle which was linked from a previous question with a similar problem. My code is similar to the one in the mentioned question but I am getting Uncaught TypeError: Cannot read property 'length' of undefined
in jquery.min.js:2
in the console when I check one of the boxes. The other thing that is different is that I am getting the data from a JSON file and the storing it to an array.
Here is my code:
$.getJSON("json/map-data.json", function(data) {
gMarkers['parking'] = [], gMarkers['academic'] = [], gMarkers['residence'] = [];
// Loop through each feature in the JSON file
for (var i = 0; i < data.features.length; i++) {
features.push(data.features[i]);
types.push(features[i].properties.type);
descriptions.push(features[i].properties.description);
titles.push(features[i].properties.title);
markers.push(features[i].geometry.point);
polygons.push(features[i].geometry.polygon);
// store JSON data to temporary variable to later push to an array
var markerForArray = {
lat: markers[i][0],
lng: markers[i][4],
title: titles[i],
infoWindow: {
content: descriptions[i]
}
};
// Store markerForArray sorted by "type"
if (types[i] === 'parking')
gMarkers['parking'].push(markerForArray);
else if (types[i] === 'residence')
gMarkers['residence'].push(markerForArray);
else if (types[i] === 'academic')
gMarkers['academic'].push(markerForArray);
};
/* Takes the poi type as a parameter */
GMaps.prototype.addMarkersOfType = function (poi_type) {
// save the relevant map
console.log(gMarkers['parking'][0]);
var theMap = this.map;
// clear markers of this type
realMarkers[poi_type]=[];
// for each Gmaps marker
$.each(gMarkers[poi_type],function(index, obj){
// add the marker
var marker = map.addMarkers(obj);
// save it as real marker
realMarkers[poi_type].push(marker);
});
}
/* Takes the poi type as a parameter */
GMaps.prototype.removeMarkersOfType = function (poi_type) {
// for each real marker of this type
$.each(realMarkers[poi_type], function(index, obj){
// remove the marker
obj.setMap(null);
});
// clear markers of this type
realMarkers[poi_type]=[];
}
$('input[type="checkbox"').click(function() {
var poi_type = $(this).attr('name');
if ($(this).is(':checked'))
map.addMarkersOfType(poi_type);
else
map.removeMarkersOfType(poi_type);
});
});
The JSON data looks like this:
{
"type": "Feature",
"properties": {
"title": "Parking Lot #1",
"type": "parking",
"description": ""
},
"geometry": {
"point": [12.12345, -12.12345],
"polygon": [
[12.12245, 12.12845],
[12.12345,-12.12745],
[12.12445,-12.12645],
[12.12545,-12.12545]
]
}
}
Here is my code on JSFiddle: http://jsfiddle.net/88cakes/sw9m4vyo/4/