Skip to content

Instantly share code, notes, and snippets.

@wboykinm
Last active June 8, 2017 14:26
Show Gist options
  • Save wboykinm/41cf9893621d17ac893a to your computer and use it in GitHub Desktop.
Save wboykinm/41cf9893621d17ac893a to your computer and use it in GitHub Desktop.
Census dotmap using 1.) censusreporter.org for data, and 2.) turf.js for random points within a polygon
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>turfjs census dotmap</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0;}
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/turf/v2.0.2/turf.min.js'></script>
<div id='map'></div>
<script>
// specify census geoid - grab one here: http://censusreporter.org/
geoId = '15000US080470138003';
// get the polygon and population
$.getJSON('https://api.censusreporter.org/1.0/geo/tiger2013/' + geoId + '?geom=true', function(data) {
var block = JSON.parse(JSON.stringify(data));
// define the map and center on the polygon
L.mapbox.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';
var map = L.mapbox.map('map', 'faraday2.5905fe9b')
.fitBounds(L.geoJson(block).getBounds());
// style for the polygon
var polyStyle = {
color: "#351f72",
weight: 2,
fillOpacity: 0,
opacity: 0.8
};
// add the polygon to the map
var blockFeature = L.geoJson(block, {
style: polyStyle
});
blockFeature.addTo(map);
// create a bbox object for the polygon
var blockBox = [blockFeature.getBounds()._southWest.lng,blockFeature.getBounds()._southWest.lat,blockFeature.getBounds()._northEast.lng,blockFeature.getBounds()._northEast.lat];
// style for the population points
var markerStyle = {
radius: 1.4,
fillColor: "#634ea0",
color: "#000",
weight: 0,
opacity: 0,
fillOpacity: 0.7
};
// add the population of the feature
var randomCount = block.properties.population;
// increment up to the population count
for (var i = 0; i < randomCount; i++) {
// add a random point within the polygon's bbox
var point = turf.random('points', 1, {
bbox: blockBox
});
// check to see if the point is within the polygon itself;
// if not, decrement the count and try again
if (turf.inside(point.features[0], block) == false ) {
i = i - 1;
continue;
}
// if the point is inside the polygon, add it to the map
L.geoJson(point, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, markerStyle);
}
}).addTo(map);
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment