Center a map in d3 given a geoJSON object

后端 未结 11 2229
慢半拍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:33

    I was looking around on the Internet for a fuss-free way to center my map, and got inspired by Jan van der Laan and mbostock's answer. Here's an easier way using jQuery if you are using a container for the svg. I created a border of 95% for padding/borders etc.

    var width = $("#container").width() * 0.95,
        height = $("#container").width() * 0.95 / 1.9 //using height() doesn't work since there's nothing inside
    
    var projection = d3.geo.mercator().translate([width / 2, height / 2]).scale(width);
    var path = d3.geo.path().projection(projection);
    
    var svg = d3.select("#container").append("svg").attr("width", width).attr("height", height);
    

    If you looking for exact scaling, this answer won't work for you. But if like me, you wish to display a map that centralizes in a container, this should be enough. I was trying to display the mercator map and found that this method was useful in centralizing my map, and I could easily cut off the Antarctic portion since I didn't need it.

提交回复
热议问题