Skip to content

Instantly share code, notes, and snippets.

@ngottlieb
Last active November 22, 2018 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngottlieb/22b12b4f83b1e329dfb177034665f505 to your computer and use it in GitHub Desktop.
Save ngottlieb/22b12b4f83b1e329dfb177034665f505 to your computer and use it in GitHub Desktop.
Loading external GeoJSON with Leaflet-Ajax
import L from 'leaflet';
require("leaflet-ajax");
export default class Map {
constructor(props) {
this.map = L.map('mapid').setView([42, -100], 4);
// see here for other tileLayer providers:
// https://leaflet-extras.github.io/leaflet-providers
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(this.map);
this.loadDataset();
}
loadDataset() {
this.geojsonLayer = new L.GeoJSON.AJAX("https://raw.githubusercontent.com/loganpowell/census-geojson/master/GeoJSON/500k/2017/american-indian-area!alaska-native-area!hawaiian-home-land.json",
{
onEachFeature: this.onEachFeature,
style: this.setRandomFeatureColor
}).
addTo(this.map);
}
onEachFeature(feature, layer) {
if (feature.properties && feature.properties.NAME) {
layer.bindPopup(feature.properties.NAME);
}
}
setRandomFeatureColor(feature) {
// from https://stackoverflow.com/questions/1484506/random-color-generator#1484514
const letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return {
color: color
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment