Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

center on layer or feature? #84

Open
Kilian opened this Issue · 2 comments

3 participants

@Kilian

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?

@tyrauber

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.

@mbostock
Collaborator

D3's geo.path could probably help you here—it supports computing the bounding box and centroid of arbitrary GeoJSON features. You can then pass the result to polymaps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.