Public
Edited
Dec 9, 2022
1 fork
13 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function drawGraticuleTicks(
svgNode,
{
step = [1, 1],
fontSize = 10,
fontFamily = "inherit",
fontFill = "black",
fontStroke = "white",
fontStrokeWidth = 2,
tickSize = 0,
tickPadding = 4,
tickStroke = "black",
tickStrokeWidth = 0.75,
position = "inside", // Supports "inside" and "outside",
closenessPrecision = 0.001,
debug = false
} = {}
) {
const {
projection,
height,
width,
marginTop,
marginRight,
marginLeft,
marginBottom
} = svgNode.props;

const boundsGeo = viewportAsGeo({
projection,
width,
height,
marginTop,
marginRight,
marginBottom,
marginLeft
});

const pos = graticuleLabelPositions(boundsGeo, { step });
const P = pos.map((p) => {
const [x, y] = projection(p);

p.x = x;
p.y = y;
return p;
});

const g = d3.select(svgNode).append("g").attr("class", "graticule-ticks");

const leftMost = d3.min(P, (p) => p.x);
let leftTicks = pos.filter(
(p) => Math.abs(p.x - leftMost) <= closenessPrecision
);
leftTicks = leftTicks.filter((t) => t.type === "latitude");
const bottomMost = d3.max(P, (p) => p.y);
let bottomTicks = pos.filter(
(p) => Math.abs(p.y - bottomMost) <= closenessPrecision
);
bottomTicks = bottomTicks.filter((t) => t.type === "longitude");

// Left ticks
const leftTickG = g
.append("g")
.attr("class", "left-graticules-ticks")
.selectAll(".tick")
.data(leftTicks)
.join("g")
.attr("class", "tick")
.attr("transform", (d) => `translate(${d.x},${d.y})`);

leftTickG
.append("line")
.attr("class", "tick-line")
.attr("x2", (position === "outside" ? -1 : 1) * tickSize);
leftTickG
.append("text")
.attr("dy", (position === "outside" ? -1 : 1) * (tickSize + tickPadding))
.attr("dominant-baseline", position === "outside" ? "auto" : "hanging")
.attr("text-anchor", "middle")
.attr("transform", "rotate(-90)");

// Bottom Ticks
const bottomTickG = g
.append("g")
.attr("class", "bottom-graticules-ticks")
.selectAll(".tick")
.data(bottomTicks)
.join("g")
.attr("class", "tick")
.attr("transform", (d) => `translate(${d.x},${d.y})`);

bottomTickG
.append("line")
.attr("class", "tick-line")
.attr("y2", (position === "outside" ? 1 : -1) * tickSize);
bottomTickG
.append("text")
.attr("dy", (position === "outside" ? 1 : -1) * (tickSize + tickPadding))
.attr("text-anchor", "middle")
.attr("dominant-baseline", position === "outside" ? "hanging" : "auto");

g.selectAll(".tick-line")
.attr("stroke", tickStroke)
.attr("stroke-width", tickStrokeWidth);

// Add label text
g.selectAll("text")
.attr("font-family", fontFamily)
.attr("font-size", fontSize)
.attr("fill", fontFill)
.attr("stroke", fontStroke)
.attr("stroke-width", fontStrokeWidth)
.attr("paint-order", "stroke")
.text((d) =>
d.type === "longitude" ? formatLongitude(d[0]) : formatLatitude(d[1])
);

if (debug) {
g.append("g")
.selectAll(".edge-points")
.data(boundsGeo.coordinates[0])
.join("circle")
.attr("class", "edge-points")
.attr("r", ".75")
.attr("fill", "#0ff")
.each(function (d) {
const [x, y] = projection(d);
d3.select(this).attr("cx", x).attr("cy", y);
});

g.append("g")
.attr("class", "graticules-intersection-points")
.selectAll(".graticules-intersection-point")
.data(pos)
.join("circle")
.attr("class", "graticules-intersection-point")
.attr("r", 4)
.attr("fill", "none")
.attr("stroke-width", 2)
.each(function (d) {
const [cx, cy] = projection(d);
d3.select(this)
.attr("cx", cx)
.attr("cy", cy)
.attr("stroke", d.type === "longitude" ? "red" : "orange");
});
}
}
Insert cell
function viewportAsGeo({
projection,
width,
height,
marginTop = 0,
marginRight = 0,
marginLeft = 0,
marginBottom = 0,
precision = 2.5
} = {}) {
const p1 = [marginLeft, marginTop];
const p2 = [width - marginRight, marginTop];
const p3 = [width - marginRight, height - marginBottom];
const p4 = [marginLeft, height - marginBottom];

const vertices = [p1, p2, p3, p4, p1];

const viewportSize = Math.min(
width - marginRight - marginLeft,
height - marginTop - marginBottom
);
const parts = Math.floor(viewportSize / precision);

let lines = pairUp(vertices);
lines = lines
.flatMap(([p1, p2]) => partitionLine(...p1, ...p2, parts))
.map((l) => l[0]);
lines = [...lines, p1];

return {
type: "Polygon",
coordinates: [lines.map((p) => projection.invert(p))]
};
}
Insert cell
// Based on https://observablehq.com/@fil/finding-intersections-method-2#positions
function graticuleLabelPositions(boundsGeo, { step = [1, 1] }) {
let i = [];
let poly = boundsGeo.coordinates[0].slice();
let cur = poly[0];
// poly.push(cur);
// let p0 = cur;
poly.forEach((p) => {
// Above 80° longitude, we can reduce the lines
// I think, that’s default on d3.graticules
let latStep = Math.abs(p[1]) > 80 ? 90 : step[1];
let lonStep = step[0];
if (Math.floor(p[1] / latStep) != Math.floor(cur[1] / latStep)) {
p.type = "latitude";
i.push(p);
} else if (Math.floor(p[0] / lonStep) != Math.floor(cur[0] / lonStep)) {
p.type = "longitude";
i.push(p);
}
cur = p;
});

return i;
}
Insert cell
function pairUp(arr) {
return arr.reduce((res, cur, i, arr) => {
if (i === 0) return res;
return [...res, [arr[i - 1], cur]];
}, []);
}
Insert cell
function generateMap({
projection = d3.geoIdentity().reflectY(true),
width,
height,
marginLeft,
marginRight,
marginBottom,
marginTop,
padding,
step,
features,
tickPosition,
tickSize,
tickPadding,
graticulePrecision
} = {}) {
const svg = drawMap(features, {
projection,
width,
height,
marginLeft,
marginRight,
marginBottom,
marginTop,
padding,
debug
});
drawGraticules(svg, { step, debug, graticulePrecision });
drawGraticuleTicks(svg, {
step,
position: tickPosition,
tickSize,
tickPadding,
debug
});
return svg;
}
Insert cell
function drawGraticules(
svgNode,
{
step = [1, 1],
graticulePrecision = 2.5,
stroke = "#999",
strokeWidth = 0.5,
clipId = DOM.uid("clip"),
debug = false
} = {}
) {
const {
projection,
marginTop,
marginRight,
marginLeft,
marginBottom,
height,
width,
padding
} = svgNode.props;

const canvas = d3.select(svgNode);

const graticuleGenerator = d3
.geoGraticule()
.step(step)
.precision(graticulePrecision);
const graticules = graticuleGenerator();
const path = d3.geoPath(projection);

const extent = graticuleGenerator.extent();

const defs = d3.select(svgNode).select("defs").node()
? d3.select(svgNode).select("defs")
: d3.select(svgNode).insert("defs", ":first-child");

defs
.append("clipPath")
.attr("id", clipId.id)
.append("rect")
.attr("x", marginLeft)
.attr("y", marginTop)
.attr("width", width - (marginLeft + marginRight))
.attr("height", height - (marginTop + marginBottom));

const g = d3.select(svgNode).append("g").attr("class", "key-graticules");

g.append("path")
.attr("class", "graticules")
.attr("stroke", stroke)
.attr("stroke-width", strokeWidth)
.attr("fill", "none")
.attr("clip-path", clipId)
.attr("d", path(graticules));

g.append("rect")
.attr("class", "graticule-outline")
.attr("fill", "none")
.attr("stroke", stroke)
.attr("stroke-width", strokeWidth)
.attr("x", marginLeft)
.attr("y", marginTop)
.attr("width", width - (marginLeft + marginRight))
.attr("height", height - (marginTop + marginBottom));
}
Insert cell
function drawMap(
geo,
{
width = 640,
height,
marginTop = 1,
marginLeft = 1,
marginBottom = 1,
marginRight = 1,
padding = 30,
projection = d3.geoIdentity().reflectY(true),

fill = "none",
stroke = "black",
strokeWidth = 0.75,
strokeLinejoin = "round",

backgroundFill = "#fff",
debug = false
} = {}
) {
// If height is not provided, compute from Geo and projection
if (height == null) {
const fauxProjection = d3.geoIdentity().reflectY(true);
const fauxPath = d3.geoPath(fauxProjection);
fauxProjection.fitWidth(
width - (marginLeft + marginRight + 2 * padding),
geo
);
height =
Math.ceil(fauxPath.bounds(geo)[1][1]) +
(marginTop + marginBottom + 2 * padding);
}

projection = projection.scale === undefined ? projection() : projection;
// https://github.com/d3/d3-geo/blob/main/README.md#projection_fitSize
projection.fitExtent(
[
[marginLeft + padding, marginTop + padding],
[width - (marginRight + padding), height - (marginBottom + padding)]
],
geo
);
projection.clipExtent([
[0, 0],
[width, height]
]);

const path = d3.geoPath(projection);

const svg = DOM.svg(width, height);

d3.select(svg)
.attr("style", "max-width: 100%; height: auto; height: intrinsic;")
.style("background", backgroundFill);

const canvas = d3.select(svg).append("g").attr("class", "features");

if (debug) {
canvas
.append("rect")
.attr("fill", "none")
.attr("stroke", "#f0f")
.attr("x", marginLeft)
.attr("y", marginTop)
.attr("width", width - (marginLeft + marginRight))
.attr("height", height - (marginTop + marginBottom));
canvas
.append("rect")
.attr("fill", "none")
.attr("stroke", "#f0f")
.attr("x", marginLeft + padding)
.attr("y", marginTop + padding)
.attr("width", width - (marginLeft + marginRight + 2 * padding))
.attr("height", height - (marginTop + marginBottom + 2 * padding));
}

canvas
.append("path")
.datum(geo)
.attr("fill", "none")
.attr("stroke", stroke)
.attr("stroke-width", strokeWidth)
.attr("stroke-linejoin", strokeLinejoin)
.attr("d", path);

return Object.assign(svg, {
props: {
projection,
width,
height,
marginTop,
marginLeft,
marginBottom,
marginRight,
padding,
geo
}
});
}
Insert cell
formatLongitude = (x) => `${formatLatLon(x)}°${x < 0 ? "W" : "E"}`
Insert cell
formatLatitude = y => `${formatLatLon(y)}°${y < 0 ? "S" : "N"}`
Insert cell
formatLatLon = d3.format(".2f")
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more