Skip to content

Instantly share code, notes, and snippets.

@zaynaib
Last active January 26, 2023 20:22
Show Gist options
  • Save zaynaib/e7cddeb3ab6d8ae40f51be7753e8e3e5 to your computer and use it in GitHub Desktop.
Save zaynaib/e7cddeb3ab6d8ae40f51be7753e8e3e5 to your computer and use it in GitHub Desktop.
d3 with leaflet
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
crossorigin=""/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.8/d3.min.js" type="text/JavaScript"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<style>
</style>
</head>
<body>
<div>
<input type="text" id="wardInput" placeholder="Search for Ward...">
<button type="button" onclick="getInputValue()">Search</button>
</div>
<div id="container">
<div id="map"></div>
<div id="wardInfo">
<ul id="wardDemographics">
</ul>
</div>
<div>
<svg id="viz" style="width:600px;height:600px;" ></svg>
</div>
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
crossorigin=""></script>
<!-- API key -->
<script type="text/javascript" src="js/config.js"></script>
<!-- JS -->
<!-- <script type="text/javascript" src="js/logic1.js"></script> -->
<!-- <script type="text/javascript" src="js/logic.js"></script> -->
<script type="text/javascript" src="js/stackedbar.js"></script>
</body>
</html>
console.log("hello, World!")
//leaflet [ latitude ,longitiude]
var myMap = L.map("map", {
center: [41.881832, -87.623177],
zoom: 11
});
// We create the tile layer that will be the background of our map.
let tileLayer = L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery (c) <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
accessToken: API_KEY
}).addTo(myMap);
let link = 'data/chicago-wards.geojson'
link = 'data/chicago-wards-demos.geojson'
/*
function barChart(geoFeature){
let data = geoFeature.properties
console.log(data)
let total = data.Total/10000
console.log(total)
// create svg element:
d3.selectAll("#bar > *").remove();
var svg = d3.select("#bar").append("svg").attr("width", 600).attr("height", 600)
// Add the path using this helper function
svg.append('circle')
.attr('cx', 100)
.attr('cy', 100)
.attr('r', total)
.attr('stroke', 'black')
.attr('fill', '#69a3b2');
} // end of barchart function
*/
function assignPopup(feature, layer){
layer.on('click',function(){
//console.log('hello')
let wardList = document.getElementById('wardDemographics');
//delete all of the child elements in the wardInfo div
wardList.replaceChildren();
let li = document.createElement('li');
//loop through all of the features except for the first 2 key/pair values
const entries = Object.entries(feature.properties).slice(3,-1)
//console.log(entries)
//console.log(entries.slice(2,-1))
for(const [key, value] of entries){
//console.log(`${key}:${value}`)
let li = document.createElement('li');
let liContent = document.createTextNode(`${key}:${value}`)
li.appendChild(liContent)
wardList.appendChild(li)
}
// barChart(feature)
})
}
function getInputValue(){
let inputVal = document.getElementById("wardInput").value;
console.log(inputVal);
return getInputValue;
}
function ward11(feature){
let wardInput = getInputValue()
if(feature.properties.ward == 11){
return true
}
}
async function getResponse() {
const response = await fetch(link);
const data = await response.json(); // Extracting data as a JSON Object from the response
//console.log('async/await executed')
//console.log(data)
L.geoJson(data,{
// feature automatically assigne the original geojson object
//assigned the layer that is created by leaflet and added to map
onEachFeature: assignPopup,
//filter: ward11
}).addTo(myMap);
}
getResponse()
var data = [
{month: new Date(2018, 1, 1), apples: 10, bananas: 20, oranges: 15},
//{month: new Date(2018, 2, 1), apples: 15, bananas: 15, oranges: 15},
//{month: new Date(2018, 3, 1), apples: 20, bananas: 25, oranges: 15}
];
var xScale = d3.scaleLinear().domain([0, 10]).range([0, 500]);
var yScale = d3.scaleLinear().domain([0, 100]).range([500, 0]);
var heightScale = d3.scaleLinear().domain([0,100]).range([0, 500]);
let fruit = ["apples", "bananas", "oranges"]
var fillScale = d3.scaleOrdinal()
.domain(fruit)
.range(["#fcd88a", "#cf7c1c", "#93c464"]);
var stackedLayout = d3.stack().keys(fruit)
console.log(fruit)
var stackArea = d3.area()
.x((d, i) => xScale(i))
.y0(d => yScale(d[0]))
.y1(d => yScale(d[1]));
// Create a g element for each series
d3.select("#viz").selectAll("g.bar")
.data(stackedLayout(data))
.enter()
.append("g")
.attr("class", "bar")
.each(function(d) {
d3.select(this).selectAll("rect")
.data(d)
.enter()
.append("rect")
.attr("x", (p,q) => xScale(q) + 30)
.attr("y", p => yScale(p[1]))
.attr("height", p => heightScale(p[1] - p[0]))
.attr("width", 40)
.style("fill", fillScale(d.key));
});
console.log(d3.select('#viz'))
console.log("hello, World!")
//leaflet [ latitude ,longitiude]
var myMap = L.map("map", {
center: [41.881832, -87.623177],
zoom: 11
});
// We create the tile layer that will be the background of our map.
let tileLayer = L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery (c) <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
accessToken: API_KEY
}).addTo(myMap);
let link = 'data/chicago-wards.geojson'
link = 'data/chicago-wards-demos.geojson'
function barChart(geoFeature){
// read in the data
let data = geoFeature.properties
console.log(data)
let entries = Object.entries(data).slice(5,8)
console.log(entries)
entries = Object.fromEntries(entries)
console.log(entries)
//remove all svg elements in the viz canvas
d3.selectAll("#viz > *").remove();
// set up scales for data viz
var xScale = d3.scaleLinear().domain([0, 10]).range([0, 500]);
var yScale = d3.scaleLinear().domain([0, 100000]).range([500, 0]);
var heightScale = d3.scaleLinear().domain([0,100000]).range([0, 500]);
//get the keys from the data
let races = ["Black", "White", "Latino"]
var fillScale = d3.scaleOrdinal()
.domain(races)
.range(["black", "blue", "red"]);
//.range(["#fcd88a", "#cf7c1c", "#93c464"]);
var stackedLayout = d3.stack().keys(races)
console.log(races)
var stackArea = d3.area()
.x((d, i) => xScale(i))
.y0(d => yScale(d[0]))
.y1(d => yScale(d[1]));
// Create a g element for each series
d3.select("#viz").selectAll("g.bar")
.data(stackedLayout([entries]))
.enter()
.append("g")
.attr("class", "bar")
.each(function(d) {
d3.select(this).selectAll("rect")
.data(d)
.enter()
.append("rect")
.attr("x", (p,q) => xScale(q) + 30)
.attr("y", p => yScale(p[1]))
.attr("height", p => heightScale(p[1] - p[0]))
.attr("width", 40)
.style("fill", fillScale(d.key));
});
console.log(d3.select('#viz'))
}
/*
function barChart(geoFeature){
let data = geoFeature.properties
console.log(data)
let total = data.Total/10000
console.log(total)
// create svg element:
d3.selectAll("#bar > *").remove();
var svg = d3.select("#bar").append("svg").attr("width", 600).attr("height", 600)
// Add the path using this helper function
svg.append('circle')
.attr('cx', 100)
.attr('cy', 100)
.attr('r', total)
.attr('stroke', 'black')
.attr('fill', '#69a3b2');
} // end of barchart function
*/
function assignPopup(feature, layer){
layer.on('click',function(){
//console.log('hello')
let wardList = document.getElementById('wardDemographics');
//delete all of the child elements in the wardInfo div
wardList.replaceChildren();
let li = document.createElement('li');
//loop through all of the features except for the first 2 key/pair values
const entries = Object.entries(feature.properties).slice(3,-1)
//console.log(entries)
//console.log(entries.slice(2,-1))
for(const [key, value] of entries){
//console.log(`${key}:${value}`)
let li = document.createElement('li');
let liContent = document.createTextNode(`${key}:${value}`)
li.appendChild(liContent)
wardList.appendChild(li)
}
barChart(feature)
})
}
function getInputValue(){
let inputVal = document.getElementById("wardInput").value;
console.log(inputVal);
return getInputValue;
}
function ward11(feature){
let wardInput = getInputValue()
if(feature.properties.ward == 11){
return true
}
}
async function getResponse() {
const response = await fetch(link);
const data = await response.json(); // Extracting data as a JSON Object from the response
//console.log('async/await executed')
//console.log(data)
L.geoJson(data,{
// feature automatically assigne the original geojson object
//assigned the layer that is created by leaflet and added to map
onEachFeature: assignPopup,
//filter: ward11
}).addTo(myMap);
}
getResponse()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment