I've built a Mapbox map that has a fairly involved custom popup structure, including photos and formatting. I'm using a .csv file and omnivore to feed my data, and creating the popup .on ready. I've also got a search box that searches the data using jQuery.
Independently, each one works. The popups load fine, and the search is working. But after filtering using the search thing, I lose the popups.
I've looked at this similar post but nothing suggested seems to be working. I think this has to do with my popup variable being contained inside of the .on ready function. Is there something I'm missing here? Do I need to restructure how the popups are created?
Here's my code:
var featureLayer = L.mapbox.featureLayer().addTo(map);
jQuery('#search').keyup(search);
Load data, format popups:
var csvLayer = omnivore.csv('Stats.csv', null, L.mapbox.featureLayer())
.on('ready', function() {
map.fitBounds(csvLayer.getBounds(), {paddingTopLeft: [0,25]});
function updownFormat(updown, change){
if (updown === '—') {
return "No change ";
} else if (updown === "N/A") {
return "New store - no data ";
} else if (updown === '▲') {
return '<span class="upPercent">' + updown + "</span> " + change;
} else {
return '<span class="downPercent">' + updown + "</span> " + change;
}
};
csvLayer.eachLayer(function(layer) {
var prop = layer.feature.properties
var popup = '<div class="popup"><h3>'+ prop.storename +'<\/h3>' +
'<h4>'+ prop.town +'</h4>' +
'<p><b>Rank:</b> #'+ prop.rank +' (of 80 stores) <br>' +
'<b>Sales: </b>' + prop.money14 +' (2014)<br>' +
'<b>Growth: </b>' + updownFormat(prop.updown, prop.change) + ' (from 2013)</p>' +
'<h5>Best selling bottles (2014)</h5>' +
'<img src="'+ prop.pop1img +'" class="liquorimg">' +
'<ol><li><b>'+prop.pop1+'</b></li><li>'+prop.pop2+'</li><li>'+prop.pop3+'</li><li>'+prop.pop4+'</li><li>'+prop.pop5+'</li></ol></div>';
layer.bindPopup(popup);
});
})
.addTo(map);
The search function:
function search() {
// get the value of the search input field
var searchString = jQuery('#search').val().toLowerCase();
csvLayer.setFilter(showStoreTown);
function showStoreTown(feature) {
return feature.properties.storetown
.toLowerCase()
.indexOf(searchString) !== -1;
}
}
Fixed, thanks to Twitter! Setting map bounds on "ready" and setting the popup creation on "addlayer" took care of it.