d3js scale, transform and translate

前端 未结 3 972
夕颜
夕颜 2020-12-15 10:28

I\'ve created nycMap, a project that uses angularJS (MVC), yeoman (build), d3 (mapping) and geoJSON (geo data).

Everything works very nicely, but I did have to spen

3条回答
  •  长情又很酷
    2020-12-15 11:17

    I've had the same problems. But it is very easy to do when you have a bounding box, which can be determined from the GeoJSON (like meetamit said), or while creating the GeoJson. And the width of the wanted SVG.

    I'll start with the variables lattop, lonleft, lonright, width and height for the bounding box of the geojson and the dimensions of the image. I haven't yet occupied myself with calculating a good height from the difference in latutude. So the height is just estimated to be big enough to fit the image. The rest should be clear from the code:

    var xym = d3.geo.mercator();
    
    // Coordinates of Flanders
    var lattop = 51.6;
    var lonleft = 2.4;
    var lonright = 7.7;
    var width = 1500;
    var height =1000;
    
    // make the scale so that the difference of longitude is 
    // exactly the width of the image
    var scale = 360*width/(lonright-lonleft);
    xym.scale(scale);
    
    // translate the origin of the map to [0,0] as a start, 
    // not to the now meaningless default of [480,250]
    xym.translate([0,0]);
    
    // check where your top left coordinate is projected
    var trans = xym([lonleft,lattop]);
    // translate your map in the negative direction of that result
    xym.translate([-1*trans[0],-1*trans[1]]);
    
    
    var path = d3.geo.path().projection(xym);
    
    var svg = d3.select("body").append("svg").attr("width",width).attr("height",height);
    

    Note, if you go over the date line (180 degrees), you will have to take the overflow into account.

提交回复
热议问题