Open Kilian opened 13 years ago
I am doing this now, but it takes a few steps.
First, I get the bounds:
function createBounds(geoms){
// where geoms is an array of arrays containing x,y coords
// [[x,y],[x,y]...]
var bounds = new Array();var cw=null; var ce=null; var cn=null; var cs=null;
for (i=0;i< geoms.length;i++){
if(cw == null || geoms[i][0] > cw){cw = geoms[i][0];}
if(ce == null || geoms[i][0] < ce){ce = geoms[i][0];}
if(cn == null || geoms[i][1] > cn){cn = geoms[i][1];}
if(cs == null || geoms[i][1] < cs){cs = geoms[i][1];}
}
bounds = [[cw, cn], [ce, cn], [ce, cs], [cw, cs], [cw, cn]]
return bounds
}
Then I get the center of the bounds.
function createCenter(bounds){
// bounds is a bounding box around a polygon. An array of 5, lat/lng arrays
var lat = bounds[2][1]-((bounds[2][1]-bounds[0][1])/2);
var lng = bounds[2][0]-((bounds[2][0]-bounds[0][0])/2);
var center = [lat, lng]
return center
}
Then I move the map to that new center.
var center = createCenter(createBounds(polygon));
map.center({lon: center[1], lat: center[0]})
There is probably a simpler way. I just haven't found it yet. I originally wrote these functions in ruby, so the js could probably be optimized, but it does work.
I would like an easy way to center the map on a certain feature or (the center of) a non-tiled geojson layer. Is this possible?