In my openlayers 5 (based on a angular 6 app), I am implementing a functionality where you search for something, query the db, the db brings back some geoJSON and I render this geoJSON data in a ol vector layer.
There are two different ways to search, so there are two different forms that bring back geoJSOn to the same ol vector.
Of course, before rendering the data, I have to clear out the layer.
This is my code
ngOnInit() {//initialize some params and the ol map
//bring results-as you type - pure angular
this.results = this.myForm.valueChanges.pipe(
switchMap( formdata => this.mapcmsService.searchName(formdata.name, formdata.cepDrop))
);//pipe
this.tilesource = new OlXYZ({
url:'http://tile.stamen.com/terrain/{z}/{x}/{y}.jpg'
});
this.tilelayer = new OlTileLayer({
source: this.tilesource
});
this.vectorsource = new VectorSource({});
this.vectorlayer = new VectorLayer({
source: this.vectorsource
});
this.view = new OlView({
center: OlProj.fromLonLat([6.661594, 50.433237]),
zoom: 2,
});
this.olmap = new OlMap({
target: 'map',
layers: [this.tilelayer,this.vectorlayer],
view: this.view,
projection: 'EPSG:3857'
});
const selectClick = new Select({
condition: click,
layers:[this.vectorlayer]
});
this.olmap.addInteraction(selectClick);
selectClick.on(
'select', ()=>{
const values = selectClick.getFeatures().item(0).values_;
this.getDetails(values.id);
}
);
} //closes ngOnInit
Outside the ngOnInit, after the initialization,there are the two different functions that bring geoJSON to the same ol vector layer. They basically do the same thing.
searchById(id){
this.map_loading = true;
this.myService.getById(id).subscribe((data) =>{
this.vectorsource.refresh();
this.vectorsource.clear();
const fff = (new GeoJSON()).readFeatures(data.data);
this.vectorsource.addFeatures(fff);
this.map_loading = false;
})
}//searchById
and
searchCategories(){
this.map_loading = true;
this.myService.categoriesSearch(this.categoriesForm.value).subscribe((data) =>{
this.vectorsource.refresh();
this.vectorsource.clear();
const fff = (new GeoJSON()).readFeatures(data.data);
this.vectorsource.addFeatures(fff);
this.map_loading = false;
})
}//searchCategories
The problem is that the ol vector source is not always cleared before new features are added. I search for something, features are rendered. I search again , and sometimes, the old features remain on the map, along with the new ones.
I did a silly move to add refresh with clean and nothing is fixed. This is not standard, eg every other search. This randomly happen and I dont have a clue how to debug it. Please advice
Thanks
Is there an unique id for each feature?
I had the same problem that features were loaded constantly. I used the bbox-strategy and every time I moved the map, it loaded all the features in the extent, even if they were already there.
I had to set an unique id in the data for my features, so OpenLayers can refer to the existing ones if you load new ones. This randomness maybe comes through the generated ids for the features, that are sometimes equal to the new ones and sometimes not.
Dont know if that faces your problem, it just flew into my brain while I read that.
Related
I want to provide my users with an API (pointing to my server) that will fetch data from Firebase and return it to them. I want it to be a 'normal' point-in-time request (as opposed to streaming).
My data is 'boxes' within 'projects'. A user can query my API to get all boxes for a project.
My data is normalised, so I will look up the project and get a list of keys of boxes in that project, then go get each box record individually. Once I have them all, I will return the array to the user.
My question: what is the best way to do this?
Here's what I have, and it works. But it feels so hacky.
const projectId = req.params.projectId; // this is passed in by the user in their call to my server.
const boxes = [];
let totalBoxCount = 0;
let fetchedBoxCount = 0;
const projectBoxesRef = db
.child('data/projects')
.child(projectId)
.child('boxes'); // a list of box keys
function getBox(boxSnapshot) {
totalBoxCount++;
db
.child('data/boxes') // a list of box objects
.child(boxSnapshot.key())
.once('value')
.then(boxSnapshot => {
boxes.push(boxSnapshot.val());
fetchedBoxCount++;
if (fetchedBoxCount === totalBoxCount) {
res.json(boxes); // leap of faith that getBox() has been called for all boxes
}
});
}
projectBoxesRef.on('child_added', getBox);
// 'value' fires after all initial 'child_added' things are done
projectBoxesRef.once('value', () => {
projectBoxesRef.off('child_added', getBox);
});
There are some other questions/answers on separating the initial set of child_added objects, and they have influenced my current decision, but they don't seem to relate directly.
Thanks a truck-load for any help.
Update: JavaScript version of Jay's answer below:
db
.child('data/boxes')
.orderByChild(`projects/${projectId}`)
.equalTo(true)
.once('value', boxSnapshot => {
const result = // some parsing of response
res.json(result);
});
This may be too simple a solution but if you have projects, and each project has boxes
your projects node
projects
project_01
boxes
box_id_7: true
box_id_9: true
box_id_34: true
project_37
boxes
box_id_7: true
box_id_14: true
box_id_42: true
and the boxes node
boxes
box_id_7
name: "a 3D box"
shape: "Parallelepiped"
belongs_to_project
project_01: true
box_id_14
name: "I have unequal lenghts"
shape: "Rhumboid"
belongs_to_project
project_37: true
box_id_34
name: "Kinda like a box but with rectangles"
shape: "cuboid"
belongs_to_project
project_01: true
With that, just one (deep) query on the boxes node will load all of the boxes that belong to project_01, which in this case is box_id_7 and box_id_34.
You could go the the other way and since you know the box id for each project in the projects node, you could do a series of observers to load in each project via it's specific path /boxes/box_id_7 etc. I like the query better; faster and less bandwidth.
You could expand on this if a box can belong to multiple projects:
box_id_14
name: "I have unequal lenghts"
shape: "Rhumboid"
belongs_to_project
project_01: true
project_37: true
Now query on the boxes node for all boxes that are part of project_01 will get box_id_7, box_id_14 and box_id_34.
Edit:
Once that structure is in place, use a Deep Query to then get the boxes that belong to the project in question.
For example: suppose you want to craft a Firebase Deep Query to return all boxes where the box's belongs_to_project list contains an item with key "project_37"
boxesRef.queryOrderedByChild("belongs_to_project/project_37"
.queryEqualToValue(true)
.observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot)
})
OK I think I'm happy with my approach, using Promise.all to respond once all the individual 'queries' are returned:
I've changed my approach to use promises, then call Promise.all() to indicate that all the data is ready to send.
const projectId = req.params.projectId;
const boxPromises = [];
const projectBoxesRef = db
.child('data/projects')
.child(projectId)
.child('boxes');
function getBox(boxSnapshot) {
boxPromises.push(db
.child('data/boxes')
.child(boxSnapshot.key())
.once('value')
.then(boxSnapshot => boxSnapshot.val())
);
}
projectBoxesRef.on('child_added', getBox);
projectBoxesRef.once('value', () => {
projectBoxesRef.off('child_added', getBox);
Promise.all(boxPromises).then(boxes => res.json(boxes));
});
The application shows work-shifts for certain time-period. firebaseConn.getShifts is the API-function to get the shiftData for the given time period.
versions:
firebase: 2.0.6
angularFire: 0.9.0 (confirmed with 0.8.2 also)
This is my firebase schema:
And this is the code:
.factory('watchers', function(bunch-of-dependencies) {
var unbindShifts = function() {};
var inited = false;
var shifts = {};
... some irrelevant code in between ...
function initShifts() {
unbindShifts();
shifts.object = firebaseConn.getShifts( false, from, to, $scope );
$scope.shifts = shifts.object;
shifts.object.$bindTo($scope, "shifts").then(function(unbind) {
unbindShifts = unbind;
});
}
The firebase-queries (that have worked fine before adding the unbind / bind and possibly time-based querying might cause issues too):
firebaseConn.getShifts = function(asArray, from, to, scope) {
return cacheRequest(FBURL + "shifts", asArray, [from, to]);
};
function cacheRequest(url, asArray, limits) {
var type = asArray ? "array" : "object";
var startAt = limits ? limits[0] : undefined;
var endAt = limits ? limits[1] : undefined;
var retObj, FBRef;
cached[url] = cached[url] || {};
/* If there are limits-parameters we don't cache at all atm. Since those queries should be checked differently than static urls */
if(!limits && cached[url][type]) {
FBRef = cached[url][type];
} else {
FBRef = cached[url][type] = createFBRef(url, startAt, endAt);
}
if(asArray) {
retObj = FBRef.$asArray();
} else {
retObj = FBRef.$asObject();
}
return retObj;
}
function createFBRef(resourceURL, startAt, endAt) {
var modifiedObject = $firebase( createRef( resourceURL ).orderByKey().startAt(startAt).endAt(endAt) );
return modifiedObject;
}
function createRef(resourceURL) {
return new Firebase( resourceURL );
}
Now I have located the problem to be with the query limiting. If the from and to Dates are undefined, this works without problems. But I need to be able to limit the amount of data, since loading many years of workshift-data, to show a weeks time, won't be good :).
The actual problem is not displaying and fetching the data, everything works fine, it's related to the times and re-binding.
If I do any changes to e.g. "20150115"-table. For example I add another "groups"-child there. When i unbind and rebind, the whole "20150115"-table gets deleted and this holds true only to the latest changes. If I add multiple child to different dates e.g. "20150113", "20150114", "20150115" and the latest change is in "20150115" and then I unbind + re-bind another time from firebase, all the other root-paths will stay as they are, but the latest change in "20150115" will make the whole tree deleted.
I hope I make myself clear, so for safety I try to explain it again in simpler way.
- Changes to 1. "20150113", 2. "20150114", 3. "20150115" through the app.
- Changing timeline from UI causes: unbind + re-bind
- As a side-effect the whole "20150114" tree gets deleted.
The problem is somehow related to advanced querying with orderByKey().startAt(startAt).endAt(endAt) and binding.
Also for additional info. The data which is added through the UI gets added to the firebase database, but when the re-binding happens, the data is deleted from the database. Specifically on rebind, unbinding causes no issues, if I delay rebinding with timeout.
EDIT:
I have found the source of the actual issue. After the new binding is in place and everything seems to be in order, there is an angular watch event that kicks in. The event tries to save the last change user made before re-binding.
So if I have and active timeline for december (20141201 - 20141230) and I change "20141225"-data. Then change the timeline to 20150101 - 20150130, causing unbind and rebind (or manually fetching new data). There will be an event, after the binding has been done and everything seems to be in order, trying to save 20141225 data to either the new timeline (20150101 - 20150130) or the old one, not sure which one. This causes the firebase to actually delete the whole 20141225-tree, instead of saving the data.
The new data makes it into your Firebase fine, which you can see by either checking your Firebase dashboard or by running a quick snippet like this in your browser's dev console:
new Firebase("https://firebaseurl").once('value', function(s) { console.log(s.val()); })
The data even makes it back into your application. The only problem is that Angular doesn't know that new data has arrived, so it doesn't update the view with the new data.
Normally AngularFire's $asObject and $asArray methods take care of notifying AngularJS when new data arrives from Firebase. But since you are constantly creating new queries, you'll have to take care of that yourself.
There are a few ways to signal the new data to AngularJS and I'm definitely not an expert on which one is best. But if you add $scope.$apply(); to your setDays function it works:
function setDays(ref) {
var FBRange = setFBRange(ref, from, to);
var days;
unbindDays();
days = $firebase(FBRange).$asObject();
$scope.days = days;
days.$bindTo($scope, "days").then(function(unbind) {
unbindDays = unbind;
// As a result of the new binding entry gets mysteriously deleted from firebase
});
$scope.$apply(); // Tell AngularJS about the new data, so that it updates the view
function setFBRange(ref, from, to) {
return ref.orderByKey().startAt(""+from).endAt(from + to + "");
}
}
Updated Plunkr with this change (and some others to help in debugging): http://plnkr.co/edit/YZtkzUNtjQUCcw4xb2mj?p=preview
In my client UI I have a form with differents search criterias, and I'd like to reactively update the results list. The search query is transformed into a classical minimongo selector, saved in a Session variable, and then I have observers to do things with the results:
// Think of a AirBnb-like application
// The session variable `search-query` is updated via a form
// example: Session.set('search-query', {price: {$lt: 100}});
Offers = new Meteor.Collection('offers');
Session.setDefault('search-query', {});
resultsCursor = Offers.find(Session.get('search-query'));
// I want to add and remove pins on a map
resultCursor.observe({
added: Map.addPin,
removed: Map.removePin
});
Deps.autorun(function() {
// I want to modify the cursor selector and keep the observers
// so that I would only have the diff between the old search and
// the new one
// This `modifySelector` method doesn't exist
resultsCursor.modifySelector(Session.get('search-query'));
});
How could I implement this modifySelector method on the cursor object?
Basically I think this method needs to update the compiled version of the cursor, ie the selector_f attribute, and then rerun observers (without losing the cache of the previous results). Or is there any better solution?
Edit: Some of you have misunderstood what I'm trying to do. Let me provide a complete example:
Offers = new Meteor.Collection('offers');
if (Meteor.isServer && Offers.find().count() === 0) {
for (var i = 1; i < 4; i++) {
// Inserting documents {price: 1}, {price: 2} and {price: 3}
Offers.insert({price:i})
}
}
if (Meteor.isClient) {
Session.setDefault('search-query', {price:1});
resultsCursor = Offers.find(Session.get('search-query'));
resultsCursor.observe({
added: function (doc) {
// First, this added observer is fired once with the document
// matching the default query {price: 1}
console.log('added:', doc);
}
});
setTimeout(function() {
console.log('new search query');
// Then one second later, I'd like to have my "added observer" fired
// twice with docs {price: 2} and {price: 3}.
Session.set('search-query', {});
}, 1000);
}
This doesn't solve the problem in the way you seem to be wanting to, but I think the result is still the same. If this is a solution you explicitly don't want, let me know and I can remove the answer. I just didn't want to put code in a comment.
Offers = new Meteor.Collection('offers');
Session.setDefault('search-query', {});
Template.map.pins = function() {
return Offers.find(Session.get('search-query'));
}
Template.map.placepins = function(pins) {
// use d3 or whatever to clear the map and then place all pins on the map
}
Assuming your template is something like this:
<template name="map">
{{placepins pins}}
</template>
One solution is to manually diff the old and the new cursors:
# Every time the query change, do a diff to add, move and remove pins on the screen
# Assuming that the pins order are always the same, this use a single loop of complexity
# o(n) rather than the naive loop in loop of complexity o(n^2)
Deps.autorun =>
old_pins = #pins
new_pins = []
position = 0
old_pin = undefined # This variable needs to be in the Deps.autorun scope
# This is a simple algo to implement a kind of "reactive cursor"
# Sorting is done on the server, it's important to keep the order
collection.find(Session.get('search-query'), sort: [['mark', 'desc']]).forEach (product) =>
if not old_pin?
old_pin = old_pins.shift()
while old_pin?.mark > product.mark
#removePin(old_pin)
old_pin = old_pins.shift()
if old_pin?._id == product._id
#movePin(old_pin, position++)
new_pins.push(old_pin)
old_pin = old_pins.shift()
else
newPin = #render(product, position++)
new_pins.push(newPin)
# Finish the job
if old_pin?
#removePin(old_pin)
for old_pin in old_pins
#removePin(old_pin)
#pins = new_pins
But it's a bit hacky and not so efficient. Moreover the diff logic is already implemented in minimongo so it's better to reuse it.
Perhaps an acceptable solution would be to keep track of old pins in a local collection? Something like this:
Session.setDefault('search-query', {});
var Offers = new Meteor.Collection('offers');
var OldOffers = new Meteor.Collection(null);
var addNewPin = function(offer) {
// Add a pin only if it's a new offer, and then mark it as an old offer
if (!OldOffers.findOne({_id: offer._id})) {
Map.addPin(offer);
OldOffers.insert(offer);
}
};
var removePinsExcept = function(ids) {
// Clean out the pins that no longer exist in the updated query,
// and remove them from the OldOffers collection
OldOffers.find({_id: {$nin: ids}}).forEach(function(offer) {
Map.removePin(offer);
OldOffers.remove({_id: offer._id});
});
};
Deps.autorun(function() {
var offers = Offers.find(Session.get('search-query'));
removePinsExcept(offers.map(function(offer) {
return offer._id;
}));
offers.observe({
added: addNewPin,
removed: Map.removePin
});
});
I'm not sure how much faster this is than your array answer, though I think it's much more readable. The thing you need to consider is whether diffing the results as the query changes is really much faster than removing all the pins and redrawing them each time. I would suspect that this might be a case of premature optimization. How often do you expect a user to change the search query, such that there will be a significant amount of overlap between the results of the old and new queries?
I have the same problem in my own hobby Meteor project.
There is filter session var where selector is storing. Triggering any checkbox or button changes filter and all UI rerender.
That solution have some cons and the main - you can't share app state with other users.
So i realized that better way is storing app state in URL.
May be it is also better in your case?
Clicking button now change URL and UI rendering based on it. I realize it with FlowRouter.
Helpful reading: Keeping App State on the URL
I've a layout template with a left sidebar where I show information of Location passed entities as an array.
Also in this template, I show a object Map with all of this locations.
I want to do click on a Location of my sidebar and then on the same template show another object Map replacing the previous with information of this Location. Keeping the sidebar with the information and not doing new queries on the database.
How to achieve this?
Ajax? Conditional layout?
I read this article but I don't understand how to solved my problem: http://twig.sensiolabs.org/doc/recipes.html#overriding-a-template-that-also-extends-itself
PD: I'm using Twig template and Symfony2
You could have a separate template for printing object map and, as you guessed, this would have to be done using AJAX. You would pass the data you want to show on map (not id as you don't want to query database again) and the controller would return formatted HTML.
However, this seems to me a bit overkill. I would always consider doing JS (with optional framework) in order to swap the content of sidebar with Map object.
It really depends on which map API do you use. If it could be controlled via JS I would look no further. It it could not, well then, AJAX is your natural choice....
UPDATE:
OK, what you should do is create initial Map object that will be modified later on:
var theMap = null;
function initializeMap(){
var mapOptions = {
center: new google.maps.LatLng(some_latitude, some_longitude),
zoom: 8, // goes from 0 to 18
mapTypeId: google.maps.MapTypeId.ROADMAP
};
theMap = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
// you must have some element with ID = 'map_canvas'
}
some_latitude and some_longitude are fairly unimportant as you will most likely set new coordinates in a few moments.
Now assuming (but not crucial at all) that you use some of the JS frameworks (I prefer jQuery) you could bind click event to those location links:
var onlyMarker = null;
$('.location').click(function(){
var $t = $(this);
var newLatLang = new google.maps.LatLng($t.attr('data-lat') ,$t.attr('data-lng'));
if ( onlyMarker == null ) {
onlyMarker = new google.maps.Marker({
position: newLatLang
map: theMap,
title: $t.attr('title')
});
}else{
onlyMarker.setPosition(newLatLang);
}
});
Now, relying on HTML5's 'data-*' attibutes is not good idea in particular as if you use any other version lower you will most likely end-up with invalid markup. The workaround is to for link (<a>) to carry id/key to LatLng object, for example:
// initially generated from `AJAX` or in `Twig` loop
var allLatlangs = [
new google.maps.LatLngf(some_latitude, some_longitude),
new google.maps.LatLngf(some_latitude, some_longitude),
new google.maps.LatLngf(some_latitude, some_longitude),
];
$('.location').click(function(){
var id = $(this).attr('id');
var newLatLang = allLatLang(id);
//....
// everything else is the same
// ....
});
Don't forget to include Maps API with proper API key:
https://maps.googleapis.com/maps/api/js?key=API_KEY_HERE&sensor=true
In order to obtain valid API key follow this link: API KEY HOW-TO
This link basically covers key steps that I have described here so study it and it should all come together nicely.
Also, if you're unsure how to retrieve some things from Maps you should consult reference:
REFERENCE which has every method call described pretty good
Remember not to execute any of this code until everything is being loaded.
Hope this helped a bit :)
I can't make my multiple-check-box filtering system to work. I'll explain the problem, the research I've done here on stackoverflow, and why I still need help after that.
My problem is that my check boxes can't bring back the markers when I gradually unselect them. These said filters work well when I click them, because they incrementally fade away the markers associated with them. However, after just unselecting a couple of these checkboxes, all the markers are back on screen, and the last boxes don't do anything when they are finally unclicked.
This is the temporary URL of the project: http://www.lcc.gatech.edu/~amartell6/php/main12.php
This is the code where I'm getting stuck:
//this getJson function exists within an init funciton where a map
//has already been called
$.getJSON(theUrl,function(result){
$.each(result, function(i, item){
//get Longitude
var latCoord = item.coordinate;
var parenthCoord = latCoord.indexOf(",");
var partiaLat = latCoord.substr(1,parenthCoord-1);
var lat = parseFloat(partiaLat);
//alert(lat);
//get Latitude
var lngCoord = item.coordinate;
var commaCoord = lngCoord.indexOf(",");
var partiaLng = lngCoord.substr(commaCoord+1);
var lng = parseFloat(partiaLng);
//alert(lng);
// display ALL the story markers
var storyMarker;
storyMarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),// ----- > whithin the mutidimentional array,
map: map
});
//display the stories by clicking on the markers
google.maps.event.addListener(storyMarker, 'click', function() {
var from = "From ";
if(item.end_date != ""){
item.end_date = " to " + item.end_date;
}
else{
from = "";
}
$('#output').html(
'<p><span class="selected">Type of Entry: </span>' +
item.entry_type + ' <br/><br/>'+
'<span class="selected">Title: </span>'+ item.entry_title + '<br/><br/>' +
'<span class="selected">Date(s):</span><br/>'+ from +item.start_date+
//' to '+item.end_date+'<br/><br/>'+
item.end_date+'<br/><br/>'+
'<span class="selected">Content:</span><br/><br/> '+ item.entry
+'</p>'
);
});// end of story displays
//call filters from filter funciton
filter('#evacuation-filter',item.evacuation,"Yes");
filter('#evacuation-order-filter',item.evacuation_order,"Yes");
filter('#w-nearby-filter',item.w_nearby,"Yes");
filter('#hurricane-reached-filter',item.hurricane_reached,"Yes");
filter('#outdoors-filter',item.in_out_doors,"Outdoors Most of the Time");
filter('#indoors-filter',item.in_out_doors,"Indoors Most of the Time");
filter('#food-filter',item.food,"Yes");
filter('#windows-filter',item.windows,"Yes");
filter('#power-filter',item.power,"Yes");
filter('#wounded-filter',item.wounded,"Yes");
filter('#looting-filter',item.looting,"Yes");
filter('#blackouts-filter',item.blackouts,"Yes");
filter('#trees-filter',item.trees,"Yes");
filter('#powerlines-filter',item.powerlines,"Yes");
filter('#light-filter',item.light,"Yes");
filter('#sidewalks-filter',item.sidewalks,"Yes");
filter('#buildings-filter',item.buildings,"Yes");
filter('#flooding-filter',item.flooding,"Yes");
//FILTER FUNCTION
//first parameter is the checkbox id, the second is the filter criteria
//(the filter function has to be called within the $.each loop to be within scope)
var otherFilter = false;
function filter(id, criterion1, value){
var activeFilters = [];
$(id).change(function() {
//evalute if the checkbox has been "checked" or "unchecked"
var checkBoxVal = $(id).attr("checked");
//if it's been checked:
if(checkBoxVal=="checked"){
//1 - Get markers that don't talk about the filter
if(criterion1!=value && storyMarker.getVisible()==true){
//2 - fade them away, and leave only those meet the criteria
storyMarker.setVisible(false);
otherFilter = true;
activeFilters.push(criterion1);
//document.getElementById("text3").innerHTML=activeFilters+"<br/>";
//alert(activeFilters.push(criterion1) +","+criterion1.length);
}
}
//if it's been unchecked:
else if(checkBoxVal==undefined){
//1 - Get markers that don't talk about the filter
if(criterion1!=value && storyMarker.getVisible()==false){
//2 - Show them again
storyMarker.setVisible(true);
otherFilter = false;
activeFilters.pop(criterion1);
//alert(activeFilters.pop(criterion1) +","+criterion1.length);
} //end of if to cancel filter and bring markers and stories back
}
}); // end of change event
} // end of filter function
//var otherDropDown = false;
filter2("#media-filter",item.media);
filter2("#authorities-filter",item.authorities);
//---------------
function filter2(id2,criterion2){
$(id2).change(function() {
//get the value of the drowpdown menu based on its id
var dropDownVal = $(id2).attr("value");
var all="All";
//if the value isn't "All", other filters have not been applied, and marker is on screen
if(dropDownVal!=all && otherFilter==false){
//1 - check if the marker doesn't comply with filter
if(criterion2!=dropDownVal){
//2 - fade them away if not, and leave only those meet the criteria
storyMarker.setVisible(false);
//3 - If the marker does comply with it
}else if(criterion2==dropDownVal){
//4 - keep it there
storyMarker.setVisible(true);
}//end of filter applier
//else if if the value IS "All", filters have not been applied, and marker is faded
}else if(dropDownVal==all && otherFilter==false){
//select all the possible values for the cirterion
if(criterion2!=undefined){
//and show all those markers
storyMarker.setVisible(true);
}
}
});
} //end of function filter2
}); // end of $.each
}); // end of $.getJSON
I found one related blog post. This one suggests adding a category to the markers. However, when I do that, the filters keep working the same way. I think this happens because each filter is programmed to hide every single marker that meets their selecting criteria, but each marker has more than one property they can be filtered with.
Do you know if there is a way to make the script detect how many filters point towards the same marker, and only show it back if no filters are pointing at it? This is my guess on how to solve it, even though I don't know how to make it happen in code.
Finally, if you know of alternate ways to make the filters work, let me know.
I created an application with similar logic several years ago http://www.ioos.gov/catalog/ But it was for GMap 2.0 but I think the logic would be the same.
My approach was to extend the Google maps Marker object (already bloated) with features I wanted to filter them on.
These would be all the properties you're storing in your 'click' listener and perhaps more: e.g. item.title, item_start_date, etc. whatever you eventually want to filter your marker by.
var all_markers = [];
storyMarker.end_date = item.end_date;
storMarker.title = item.title;
...
all_markers.push(storyMarker);
Then when you want to filter loop thru all the markers, check the marker value against the filter condition and setVisible(true) or false as need.
Erik already provided a solution to my problem. However, I think the community may benefit from reading other options, and I want to share the solution I came up with. Even if it may not be the most effective, it works.
In the code I just mentioned, I declared all the storyMarkers at once when the map initializes:
// display ALL the story markers
var storyMarker;
storyMarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),// ----- > whithin the mutidimentional array,
map: map
});
Now, I added a new argument to the markers, but instead of creating a variable as in the example I had found in other post, this argument was an empty array:
storyMarker.pointer = [];
The previous filter function had three levels. The first level detected a change in the check box. The second one verified whether the check box had been checked or unchecked. The third level ran the filter on e-v-e-r-y marker, either to show it or hide it.
This is where my solution began. Within the most inner if statement of the filter function, I added a discretionary element within the pointer array:
storyMarker.pointer.push("element");
Right after this, I nested a new if statement to check if the array is not empty. If it indeed isn't empty, the program hides the marker that this array belongs to.
The program inverses the logic when a box is unchecked. It calls-off the filter, subtracts one element from the array associated with that marker, and then checks if there are other markers associated with it. The system now only shows up markers whose arrays are empty.
//alert(storyMarker.pointer);
function filter(id,criterion,value){
$(id).change(function() {
var checkBoxVal = $(id).attr("checked");
if(checkBoxVal=="checked"){
if(criterion!=value){
storyMarker.pointer.push("element");
//alert("array length: "+storyMarker.pointer.length);
if(storyMarker.pointer.length>0){
storyMarker.setVisible(false);
}
}
}
else if(checkBoxVal!="checked"){
if(criterion!=value){
storyMarker.pointer.pop("element");
//alert("array length: "+storyMarker.pointer.length);
if(storyMarker.pointer.length<=0){
storyMarker.setVisible(true);
}
}
}
});
}
In summary, the script is still clicking a marker more multiple times if the user clicks on more than one marker. The system can now recognize how many times is one marker pointed out, and only show the one that has no pointers at all.