[GIS] Set view does not work after Fitbounds

javascriptleafletsetviewweb-mapping

I have a map and a layergroup.

var map = L.map('map').setView([27.6758,85.3313], 12);
L.tileLayer('http://{s}.tile.cloudmade.com/8ae544230be74379927e6dee5d416398/997/256/{z}/{x}/{y}.png', {}).addTo(map);

layergroup = new L.featureGroup();

js_arr = [[27.675765991210938,85.33130645751953],[27.675764083862305,85.33131408691406],[27.675764083862305,85.33131408691406],[27.675764083862305,85.33131408691406]]; 

layer.boundary_geom = L.polygon(js_arr);
layergroup.addLayer(layer.boundary_geom);

layergroup.addTo(map);

map.fitBounds(layergroup.getBounds());

After the map is displayed i have a button which calls map.setView(....).
The problem is that if fitbounds is commented out setview works, if fitbounds is active then setview doesnot work.

Best Answer

You have several mistakes in your code:

  • You are using a factory method as a constructor. Instead of var foo = new L.featureGroup(), use var foo = L.featureGroup() or var foo = new L.FeatureGroup(). Note lowercase/uppercase! Leaflet coding style favours using factory methods (lowercase, no new).

  • layer is not defined, so you cannot assign layer.boundary_geom.

  • Your polygon coordinates have repeated coordinates. In practice this means that your polygon only has two vertices.

  • The polygon coordinates are very close, only a few meters apart. When fitting to bounds, the map will hit maxZoom, and your polygon will appear to be just one point.

Once these are taken care of, a demo map looks just fine, in both Leaflet 0.7.x and 1.0.0-beta.