Center a map in d3 given a geoJSON object

后端 未结 11 2227
慢半拍i
慢半拍i 2020-11-21 22:55

Currently in d3 if you have a geoJSON object that you are going to draw you have to scale it and translate it in order to get it to the size that one wants and translate it

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 23:14

    With mbostocks' answer, and Herb Caudill's comment, I started running into issues with Alaska since I was using a mercator projection. I should note that for my own purposes, I am trying to project and center US States. I found that I had to marry the two answers with Jan van der Laan answer with following exception for polygons that overlap hemispheres (polygons that end up with a absolute value for East - West that is greater than 1):

    1. set up a simple projection in mercator:

      projection = d3.geo.mercator().scale(1).translate([0,0]);

    2. create the path:

      path = d3.geo.path().projection(projection);

    3.set up my bounds:

    var bounds = path.bounds(topoJson),
      dx = Math.abs(bounds[1][0] - bounds[0][0]),
      dy = Math.abs(bounds[1][1] - bounds[0][1]),
      x = (bounds[1][0] + bounds[0][0]),
      y = (bounds[1][1] + bounds[0][1]);
    

    4.Add exception for Alaska and states that overlap the hemispheres:

    if(dx > 1){
    var center = d3.geo.centroid(topojson.feature(json, json.objects[topoObj]));
    scale = height / dy * 0.85;
    console.log(scale);
    projection = projection
        .scale(scale)
        .center(center)
        .translate([ width/2, height/2]);
    }else{
    scale = 0.85 / Math.max( dx / width, dy / height );
    offset = [ (width - scale * x)/2 , (height - scale * y)/2];
    
    // new projection
    projection = projection                     
        .scale(scale)
        .translate(offset);
    }
    

    I hope this helps.

提交回复
热议问题