[GIS] Leaflet fitBounds Starting Position

csvjavascriptleafletposition;

I am creating a Leaflet application that uses the code from the Simple CSV template to set the bounds of the map to the selected markers.

The issue I have is that I want to set a start position that isn't the bounds of all of my markers. I would also like the map to return to this start position once the clear function is initiated as well.

Some of the key sections of code can be seen below but the repository is available by the link above.

var addCsvMarkers = function() {
hits = 0;
total = 0;
filterString = document.getElementById('filter-string').value;

if (filterString) {
    $("#clear").fadeIn();
} else {
    $("#clear").fadeOut();
}

map.removeLayer(markers);
points.clearLayers();

markers = new L.MarkerClusterGroup(clusterOptions);
points.addData(dataCsv);
markers.addLayer(points);

map.addLayer(markers);
try {
    var bounds = markers.getBounds();
    if (bounds) {
        map.fitBounds(bounds, {maxZoom: 15});
    }
} catch(err) {
    // pass
}
if (total > 0) {
    $('#search-results').html("Showing <b>" + hits + "</b> of <b>" + total + "</b> Projects");
}
return false;
};

&

$("#clear").click(function(evt){
    evt.preventDefault();
    $("#filter-string").val("").focus();
    addCsvMarkers();
});

EDIT: Is it possible for the setView that is called in when defining the map to override the fitBounds command?

var map = L.map('map', {
zoomControl: false,
minZoom: 3,
maxZoom: 18
}).setView([54.5, -4], 6);

Best Answer

Many options here depending on what you are wanting to do exactly.

  1. Add a boolean argument to addCsvMarkers that optionally fits the map to the markers

    function addCsvMarkers(fitBounds) {
    
        // snip... jumping to the middle... 
        map.addLayer(markers);
        try {
            var bounds = markers.getBounds();
            // check for fitBounds option here
            if (bounds && fitBounds) {
                map.fitBounds(bounds, {maxZoom: 15});
            }
        // ...snip
    }
    
    // call it like so, to skip fitting bounds on the csv markers:
    addCsvMarkers(false);
    
  2. As long as your map is in global scope, you can also define a function, e.g. "zoomHome" that returns the map to any view/extent you want:

    function zoomHome() {
        map.setView([54.5, -4], 6);
    }
    

    You can call this when you init the app:

    // declare map in global scope
    var map; 
    $(document).ready(function() {
        map = L.map('map', {
            zoomControl: false,
            minZoom: 3,
            maxZoom: 18
        });
        // here:
        zoomHome();
    });
    

    Or as a part of "clear"

    $("#clear").click(function(evt){
        evt.preventDefault();
        $("#filter-string").val("").focus();
        addCsvMarkers(false);
        zoomHome();
    });