Reputation: 587
I am using D3 in a page where my objective is to superimpose two groups of paths : I have the earth coastlines as a background map (imported from a GeoJSON file), and I want to superimpose an old map on it, which is a separate SVG : http://bl.ocks.org/bperel/9943623/250fc9af2e09bf176f6d510e0b59fe643d792287
The SVG loading went well, however I would like my two maps to be included inside the same SVG element : it will be easier if I want the maps to be panned or zoomed. The issue here is that the external SVG has a specific viewbox, so if I move its <g> elements to the other SVG, the coordinates get messy. Hence my question : is there a way to convert the 2nd SVG to a <g> element that I could include in the first SVG ? Maybe d3 knows how to do that but I couldn't find such a tool in the documentation.
Upvotes: 2
Views: 979
Reputation: 3725
originalSVG
= the SVG element you want to clone and convert into g element
quasiClone
= the result of that
parentOfClone
= parent below you want to put your new g element
var quasiClone = parentOfClone.append("g");
for (var i=0; i<originalSVG.childNodes.length; i++){
var child = originalSVG.childNodes[i];
var childClone = child.cloneNode(true);
quasiClone.node().appendChild(childClone);
}
Upvotes: 0
Reputation: 3488
If you are going to zoom/pan the superimposed SVG's, Include both svg's in a <g>
container element and attach zoom behavior to the <g>
container.
Essentually, you will have:
<svg id=topSVG>
<g id=container>
<svg id=projection1>
....
</svg>
<svg id=projection2>
....
</svg>
</g>
</svg>
Below is a snippet relating to my mouswheel zoom for d3:
var myZoom=d3.behavior.zoom().scaleExtent([.1, 1000]).on("zoom", mouseWheelZoom)
function callZoomBehavior()
{
//---attach to root svg---
d3.select("#"+SVGId)
.call(myZoom)
//---reset from previous file call---
myZoom.translate([0,0])
myZoom.scale(1)
PrevScale=1
}
var PrevScale //--previous scale event---
function mouseWheelZoom()
{
//--place in d3 object--
var zoomG=d3.select("#topZoomG")
if(PrevScale!=d3.event.scale) //--transition on scale change--
{
zoomG.transition().attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")")
}
else //--no transition on pan---
{
zoomG.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")")
}
PrevScale=d3.event.scale
}
Upvotes: 1