Skip to content

Instantly share code, notes, and snippets.

Last active November 8, 2020 19:12
What would you like to do?
Leaflet with a topojson layer
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>A basic map with Leaflet</title>
<!--add Leaflet CSS-->
<link rel="stylesheet" href=""
<!--our own style rules-->
<style type="text/css">
body, html {
height: 90%;
#map-container {
height: 100%;
<!--The div in which the map will be created-->
<div id="map-container"></div>
<!--load leaflet.js-->
<script src=""
<!--we need the topojson library as well-->
<script src=""></script>
<!--our own code to create the map-->
let map ='map-container');
map.setView([52.268, 4.998], 7);
let bglayer_Positron = L.tileLayer('https://cartodb-basemaps-{s}{z}/{x}/{y}.png', {
attribution: '&copy; <a href="">OpenStreetMap</a> &copy; <a href="">CartoDB</a>',
subdomains: 'abcd',
maxZoom: 19
//extend Leaflet to create a GeoJSON layer from a TopoJSON file
L.TopoJSON = L.GeoJSON.extend({
addData: function (data) {
var geojson, key;
if (data.type === "Topology") {
for (key in data.objects) {
if (data.objects.hasOwnProperty(key)) {
geojson = topojson.feature(data, data.objects[key]);, geojson);
return this;
}, data);
return this;
L.topoJson = function (data, options) {
return new L.TopoJSON(data, options);
//create an empty geojson layer
//with a style and a popup on click
var geojson = L.topoJson(null, {
style: function(feature){
return {
color: "#000",
opacity: 1,
weight: 1,
fillColor: '#35495d',
fillOpacity: 0.8
onEachFeature: function(feature, layer) {
//fill: #317581;
//define a function to get and parse geojson from URL
async function getGeoData(url) {
let response = await fetch(url);
let data = await response.json();
return data;
//fetch the geojson and add it to our geojson layer
getGeoData('gemeenten2017.topojson').then(data => geojson.addData(data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment