Published
Edited
Apr 27, 2020
1 star
Insert cell
md`# GeoJSON Zoomable Example for NSW Localities/Postcodes
- minor changes from Fork; data from data.gov.au`
Insert cell
d3 = require("d3@5")
Insert cell
height = 800

Insert cell
mapHeight = height;
Insert cell
mapWidth = width;
Insert cell
geojson = d3.json("https://data.gov.au/geoserver/nsw-suburb-locality-boundaries-psma-administrative-boundaries/wfs?request=GetFeature&typeName=ckan_91e70237_d9d1_4719_a82f_e71b811154c6&outputFormat=json")
Insert cell
postcodes = d3.json("https://raw.githubusercontent.com/Elkfox/Australian-Postcode-Data/master/au_postcodes.json")
Insert cell
Insert cell
projection = d3.geoEquirectangular().scale(50000).center([151.2, -33.8]).translate([600, 400]);
Insert cell
geoGenerator = d3.geoPath()
.projection(projection)

Insert cell
colors = ({
TURRAMURRA: 'green',
"MOUNT COLAH": 'blue',
"ST IVES": 'yellow',
WAHROONGA: 'red',
ASQUITH: 'aqua',
HORNSBY: 'pink',
NORMANHURST: 'orange',
"LA PEROUSE": 'purple',
})
Insert cell
{
String.prototype.ucFirst= function() {
var words = this.toLowerCase().split(' ');
return words
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
const wrapper = d3.select(DOM.element("div"));

const svg = wrapper.append("svg")
.attr("width", mapWidth)
.attr("height", mapHeight)
.attr("style", "background-color:blue");
var tooltip = d3.select("body").append("div")
.attr("id", "choroplethTooltip");
const g = svg.append("g");
const u = g
.selectAll('path')
.data(geojson.features);

// Create path elements and update the d attribute using the geo generator
u.enter()
.append('path')
.attr('d', geoGenerator)
.attr('fill', (d) => colors[d.properties.nsw_loca_2]||'#fff')
.attr('stroke', '#bbb')
.attr('stroke-width', 0.5)
.on("mouseover", function(d) {
tooltip.transition()
.duration(200)
.style("opacity", 1);
tooltip.html(`<span>${d.properties.nsw_loca_2.ucFirst()}</strong> ${postcode_lookup.get(d.properties.nsw_loca_2).postcode}</span>`)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
d3.select(this).style('stroke-width', 2);
})
.on("mouseout", function(d) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
d3.select(this).style('stroke-width', 0.5);
});
var zoom = d3
.zoom()
.scaleExtent([.3, 16])
.on("zoom", zoomed);

function zoomed() {
g.attr("transform", d3.event.transform);
}

svg.call(zoom);
return wrapper.node()
}
Insert cell
html`<style>
#choroplethTooltip {
opacity: 0;
position: absolute;
font-size: 0.7em;
max-width: 150px;
background-color: #fff;
padding: 0.5em;
border: 1px #333 solid;
border-radius: 6px;
pointer-events: none;
}
</style>`
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more