I have a nested SVG (path) that I want to manipulate by centering and scaling the "inner" SVG relative to an "inner bounding box" - let's say a square of 500px^2. However, I am struggling with understanding how to adjust the viewport and scaling to achieve the desired effect.
Here is an example code snippet where I am attempting to achieve this, but haven't been able to comprehend the necessary viewport adjustments and scaling calculations:
<!DOCTYPE html>
<html>
<head>
<style>
#svg {
background:silver;
}
path {
stroke: red;
stroke-width: 0.0001;
fill: none;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
<svg id="svg" height="800" width="624" viewport="0 0 800 624" preserveAspectRatio="xMinYMin meet"></svg>
<script type="text/javascript">
function latLng2point(latLng) {
return {
x: (latLng.lng + 180) * (256 / 360),
y: (256 / 2) - (256 * Math.log(Math.tan((Math.PI / 4) + ((latLng.lat * Math.PI / 180) / 2))) / (2 * Math.PI))
};
}
function poly_gm2svg(gmPaths, fx) {
var point,
gmPath,
svgPath,
svgPaths = [],
minX = 256,
minY = 256,
maxX = 0,
maxY = 0;
for (var pp = 0; pp < gmPaths.length; ++pp) {
gmPath = gmPaths[pp], svgPath = [];
for (var p = 0; p < gmPath.length; ++p) {
point = latLng2point(fx(gmPath[p]));
minX = Math.min(minX, point.x);
minY = Math.min(minY, point.y);
maxX = Math.max(maxX, point.x);
maxY = Math.max(maxY, point.y);
svgPath.push([point.x, point.y].join(','));
}
svgPaths.push(svgPath.join(' '))
}
return {
path: 'M' + svgPaths.join(' M'),
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
};
}<pre><code><!DOCTYPE html>
<html>
<head>
<style>
#svg {
background:silver;
}
path {
stroke: red;
stroke-width: 0.0001;
fill: none;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry"></script>
<svg id="svg" height="800" width="624" viewport="0 0 800 624" preserveAspectRatio="xMinYMin meet"></svg>
<script type="text/javascript">
// Additional content omitted for brevity...
In this example, a Google encoded polyline is used which may change frequently. My goal is to constrain any given path within the boundaries of a 500px square while keeping it centered.
If you have any suggestions or pointers on how to achieve this effect, especially in dealing with SVG absolute positioning challenges, please share your insights.
This code uses basic SVG functionality, but I am open to using JavaScript libraries if they can simplify the process of handling positioning constraints effectively. Any recommendations?
EDIT: For reference, here is a conceptual image of the intended outcome: https://i.sstatic.net/bnXNK.png