user3825831
user3825831

Reputation: 109

view multiple geoJSon files into view using LEaflet

I created a javascript template for loading GEOJson file onto a leaflet map. The files could be ploygons, multypolygons, markers, icons etc..The question I have is how would I be able to fitBounds all of these files? When I call fitBounds now only the first file is used and the rest are ignored.

What I'm basically doing is in my main HTML/JavaScript file I just have to give a filename and a name I want to be the overlay, and there could be one or more. In my template javascript I load all of these files using

    var myStuff = L.geoJson(data,
              {
                style:mystyle},
              OnEachFeature, pointToLoayer
              //more complex but just to give a better understanding...
               });
                myStuff.addTo(map);
                map.fitBounds(myStuff);

Everything that I'm trying to do works except for the fitBounds part. "Data" is the files that I'm loading, but fitBounds only affects the first. Any one have any ideas?

I can give more detail if anyone is confused...

Upvotes: 1

Views: 756

Answers (1)

YaFred
YaFred

Reputation: 10008

First, there is a mistake in your code: fitBounds takes a L.LatLngBounds arguments

So your code should be:

map.fitBounds(myStuff.getBounds());

If you want to use fitBounds you can only have one GeoJSON layer

However, you can add data to your layer

var myStuff = L.geoJson(data1);
myStuff.addData(data2);
myStuff.addData(data3);

myStuff.addTo(map);
map.fitBounds(myStuff.getBounds());

If you absolutely want to keep many layers, you have to calculate the bounding rectangle yourself ..

var myStuff1 = L.geoJson(data1);
var bounds1 = myStuff1.getBounds();
var myStuff2 = L.geoJson(data2);
var bounds2 = myStuff2.getBounds();

myStuff.addTo(map);
map.fitBounds(bestBounds(bounds1, bounds2));

function bestBounds(bounds1, bounds2) {
// clever computation to get west,east,north,south
}

Upvotes: 2

Related Questions