jquery multiple select shows and hide google map markers - javascript

I have a filterfunction for google maps markers first it worked perfectly but than I wanted to have an multiple select box and than the function was not working anymore because the output is an Array i think.
Here is an working example: FIDDLE
This is the filterMarker function:
filterMarkers = function (category) {
var selectedValue = $(".select-multiple").val();
console.log($(".select-multiple").val(), category);
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == selectedValue || category.length === 0) {
// console.log('mcat', marker.category, 'cat', category);
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
Thereby I tried this to do a forEach loop trough selected values and than check if they match with category of the marker:
var foo = [];
$('.select-multiple :selected').each(function(i, selected){
foo[i] = $(selected).val();
var result = JSON.stringify(foo[i]);
console.log(result);
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == result || result.length === 0) {
// console.log('mcat', marker.category, 'cat', category);
marker.setVisible(true);
}
}
});
What am I doing wrong in my filterMarkers function could someone help me out on this one?!

You were very close. You have to detect if there are any filters selected and clear or show all pins, then show the selected pins in the loop.
filterMarkers = function(category) {
// New - clear all markers or show all. If needed the selected markers will be made visible in following step.
if ($('.select-multiple :selected').length > 0) {
for (i = 0; i < markers1.length; i++) {
gmarkers1[i].setVisible(false);
}
}
else {
for (i = 0; i < markers1.length; i++) {
gmarkers1[i].setVisible(true);
}
}
$('.select-multiple :selected').each(function(i, selected) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == $(selected).val() ) {
// console.log('mcat', marker.category, 'cat', category);
marker.setVisible(true);
}
}
});
}
Note - could not get a snippet running here because I could not get the google map link to work. However, the OP's fiddle works and if you paste the above function over his function of same name then it runs well. Trust me I tried hard with the snippet but could not get it to play.

Related

How to remove element on second click

I need to add elements to container on a first click and delete it on a second one. I guess I'm trying to make it super hard while there is a more elegant and clear solution. Fiddle Link
I was thinking of arrays to create a 1st array for clicked elements and the 2nd one for elements that are already in a container. Then filter the first array through the second one and delete those (unmatched) elements from my container.
var click = +$(this).data('clicks') || 0; // Check if contacts cliked first time
if (click % 2 == 1) { // 2nd click
fruits.splice($.inArray(name, fruits), 1); // Remove Name from an array
$(".test .single").each(function (index, elem) {
compArr.push($(this).text());
});
keyArr = fruits.filter(i => compArr.indexOf(i) !== -1);
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
} // I guess problem is here
} else { // 1st click
fruits.push(name);
$('.test textarea').css({
'font-size': '12px',
'border': '0'
}).prop('placeholder', '').before('<span class="single">' + name + '></span>');
$('textarea').val('');
}
$(this).data('clicks', click + 1);
For me, this part doesn't work properly. But I would love to hear any of your suggestions even if the entire logic is wrong. Thanks!
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
}
I've managed to fix it. Added this code:
let deleteSingle = $('.single');
for (let i = 0; i < deleteSingle.length; i++) {
for (let j = 0; j < arrayNewKeys.length; j++) {
if (deleteSingle[i].innerHTML.includes(arrayNewKeys[j])) {
deleteSingle.eq(i).addClass('a');
break;
} else {
deleteSingle.eq(i).removeClass('a');
}
}
}
$('.styleContacts:not(.a)').remove();
if ($('.test > .single.a:only-child')) {
$('.single.a').removeClass('a');
}
Instead of this:
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
} // I guess problem is here

Google maps api filter checkbox [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to make google map with filtering. One filter is select box (for now it is working) and other filer is with check boxes. So now my it have behavior as a radio button. You can se example here http://extrol.ellectadigital.com/distributeri/.
When you check it, it shows good pin, but when you click on the second it removes the first pin, and I don't want that.
So here is my code :
`http://codepen.io/PoznanM/pen/VpoZOm`
Problem is here onclick="filterChecker(this.value);" in filterChecker function only single checked item was compared and other marker are cleared.
So you have to compare all the checked items. I added function selectAllChecked() which passes checked values as array to function filterChecker()
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
var filters = {
shower: false,
vault: false,
flush: false
}
// Our markers
markers1 = [
['0', 'Title', 44.741318, 20.433573, 'Beograd', 'distributer'],
['1', 'Title', 45.823783, 16.024404, 'Zagreb', 'servis'],
['2', 'Title', 44.438350, 17.631215, 'Bosna', 'maloprodaja']
];
/**
* Function to init map
*/
function initialize() {
var center = new google.maps.LatLng(45.662477, 18.022074);
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(45.662477, 18.022074),
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
/**
* Function to add marker to map
*/
function addMarker(marker) {
var tip = marker[5];
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
tip: tip,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener
google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
return function() {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(15);
}
})(marker1, content));
}
/**
* Function to filter markers by category
*/
filterMarkers = function(category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
var get_set_options = function() {
ret_array = []
for (option in filters) {
if (filters[option]) {
ret_array.push(option)
}
}
return ret_array;
}
var filter_markers = function() {
set_filters = get_set_options()
// for each marker, check to see if all required options are set
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// start the filter check assuming the marker will be displayed
// if any of the required features are missing, set 'keep' to false
// to discard this marker
keep = true
for (opt = 0; opt < set_filters.length; opt++) {
if (!marker.properties[set_filters[opt]]) {
keep = false;
}
}
marker.setVisible(keep)
}
}
// Fuction for checkboxes
var tipovi = document.getElementsByClassName('chk-btn').value;
var selectAllChecked = function() {
var checkedPlace = []
var allCheckedElem = document.getElementsByName('filter');
for (var i = 0; i < allCheckedElem.length; i++) {
if (allCheckedElem[i].checked == true) {
checkedPlace.push(allCheckedElem[i].value)//creating array of checked items
}
}
filterChecker(checkedPlace) //passing to function for updating markers
}
var filterChecker = function(tip) {
//console.log(tip);
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
//console.log(marker);
if (in_array(this.marker.tip, tip) != -1) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
// Init map
initialize();
function in_array(needle, haystack) {
var found = 0;
for (var i = 0, len = haystack.length; i < len; i++) {
if (haystack[i] == needle) return i;
found++;
}
return -1;
}
#map-canvas {
height: 300px;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<div id="map-canvas">
</div>
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Izaberite Mesto</option>
<option value="Beograd">Beograd</option>
<option value="Zagreb">Zagreb</option>
<option value="Bosna">Bosna</option>
</select>
<div id="buttons">
<input type="checkbox" name="filter" value="distributer" class='chk-btn' onclick="selectAllChecked();">
<label for='shower'>Distributer</label>
<input type="checkbox" name="filter" value="maloprodaja" class='chk-btn' onclick="selectAllChecked();">
<label for='flush'>Maloprodaja</label>
<input type="checkbox" name="filter" value="servis" class='chk-btn' onclick="selectAllChecked();">
<label for='vault'>Servis</label>
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCmUfKutqGZ-VgbD4fwjOFd1EGxLXbxcpQ&sCensor=false"></script>

Function to display returned results count isn't working as expected

My jQuery checkbox filter works normally:
http://jsfiddle.net/EducateYourself/Lmehmj26/3/
Under checkbox form I want to show the number of results. It is 7 by default.
When I filter the results, it does not show the correct number of displayed results.
Could you please help me to find my mistake?
I commented the lines in my jsfiddle code where I added variable n to achieve the result I want.
$('.category').on('change', function () {
var n; //declare variable n
var category_list = [];
$('#filters :input:checked').each(function () {
var category = $(this).val();
category_list.push(category);
});
if (category_list.length == 0) {
$('.resultblock').show();
} else {
$('.resultblock').hide();
});
$('#count').text(n); // change the results qunatity
}
});
The problem is that you are incrementing n multiple times for a single element if it contains multiple matching tags.
You should only increment n once, at most, for each element:
Updated Example
$('.resultblock').each(function() {
var item = $(this).data('tag'),
itemArray = item.split(' '),
hasTag = false;
for (var i = 0; i < category_list.length; ++i) {
if (itemArray.indexOf(category_list[i]) >= 0) {
hasTag = true;
}
}
if (hasTag) {
$(this).show();
n++; // Only increment n once, at most, for each element.
}
});
Here is a cleaner, simplified version of your code:
Updated Example
$('.category').on('change', function() {
var categoryList = $('#filters :input:checked').map(function() {
return this.value;
}).get();
var count = 0;
$('.resultblock').hide().each(function() {
var itemTagsArray = $(this).data('tag').split(' ');
var hasTag = false;
categoryList.forEach(function(tag) {
if (itemTagsArray.indexOf(tag) > -1) {
hasTag = true;
}
});
if (hasTag) {
$(this).show();
count++;
}
});
$('#count').text(count);
});
You're counting doubles, a very easy fix is to add a check for visibility in your for loop like so
for (i = 0; i < category_list.length; ++i) {
if (itemArray.indexOf(category_list[i]) >= 0 && !$(self).is(":visible")) {
$(self).show();
n=n+1; //increase the value of n if found a result
}
}
As shown in this fiddle, that works
As a sidenote, your numbering breaks when you've selected one or more checkboxes and then deselect all. To prevent this you should change your check if there's been any checkboxes checked to
if (category_list.length == 0) {
$('.resultblock').show();
$('#count').text($('.resultblock').length);
}

Xpages - Remove selected items from an array

Does anyone know how to remove selected items from an array?
var view:NotesView = getComponent("viewPanel2");
var UtbildningarArray = new Array();
viewScope.col = view.getSelectedIds();
if (viewScope.col.length > 0){
for (i=0; i<viewScope.col.length; i++){
var docid = viewScope.col[i];
if (docid != null) {
var doc = database.getDocumentByID(docid);
UtbildningarArray.push(doc.getItemValueString("Namn"))
}
}
}
document1.removeItemValue("Utbildningar",UtbildningarArray);
document1.save();
I have tried, removeEntry and splice but I don't get it work.
Thanks,
Jonas
Edit:
You are right, have added this in the code:
var view:NotesView = getComponent("viewPanel2");
var UtbildningarArray = new Array();
var UtbildningarArray = new Array();
var FieldUtbArray = new Array(getComponent('inputHidden1').getValue());
viewScope.col = view.getSelectedIds();
if (viewScope.col.length > 0){
for (i=0; i<viewScope.col.length; i++){
var docid = viewScope.col[i];
if (docid != null) {
var doc = database.getDocumentByID(docid);
UtbildningarArray.push(doc.getItemValueString("Namn"))
}
}
}
document1.replaceItemValue("Utbildningar",FieldUtbArray.slice(UtbildningarArray));
document1.save();
I'm saving what the user selected in a hidden input, and when the user clicks the "Remove programs" button I display the selected courses in the view. Then should the user be able to click a checkbox and remove the selected course(s). Now when I save nothing happens.
I think you need to show more what you want to remove.
Below you have to code snippets that will remove an entry from an js array.
http://openntf.org/XSnippets.nsf/snippet.xsp?id=remove-an-entry-from-an-array-of-strings
http://dontpanic82.blogspot.se/2010/10/code-snippet-arraysplice-according-to.html
I got it work!
for (var i = 0; i < FieldUtbArray.length; i++) {
found = false;
// find a[i] in b
for (var j = 0; j < UtbildningarArray.length; j++) {
if (FieldUtbArray[i] == UtbildningarArray[j]) {
found = true;
break;
}
}
if (!found) {
result.push(FieldUtbArray[i]);
}
}

How to re-drop marker on the google map?

I've got two functions:
function showMarkers() {
hotspotsIterator = 0;
for(var i = 0; i < table.length; i++) {
var obj = table[i];
if(obj && obj.marker) {
var obj = table[i];
obj.marker.setMap(map);
}
}
}
function hideMarkers() {
for(var i = 0; i < table.length; i++) {
var obj = table[i];
if(obj && obj.marker) {
obj.marker.setMap(null);
}
}
}
First is showing markers, and second is hiding them. When I first use showMarkers() there is Animation.DROP performed. But when I hide them and show again, animation is not running, and the markers are simply shown.
Can someone tell me how to re-drop markers? Without creating new instances?
EDIT:
I have already created the code to re-create the same marker and it works, but its not elegant solution at all!
And Google Docs for markers doesn't resolve the issue.
Add following code right below the obj.marker.setMap(map); : obj.marker.setAnimation(google.maps.Animation.DROP);
Here the reference: Marker Animations

Categories

Resources