Skip to content

Instantly share code, notes, and snippets.

@Alex-Devoid
Created September 5, 2019 20:34
Show Gist options
  • Select an option

  • Save Alex-Devoid/b86ad9aa336aea1adbaccc1b49c54009 to your computer and use it in GitHub Desktop.

Select an option

Save Alex-Devoid/b86ad9aa336aea1adbaccc1b49c54009 to your computer and use it in GitHub Desktop.
Draft 2 mayoral votes 2019 Tucson
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og==" crossorigin=""></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/topojson@3"></script>
<style >
/* #site-navbar-container.affix{
z-index:100000
} */
.info {
padding: 6px 8px;
font: 12px/14px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.legend {
line-height: 10px;
color: #555;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
</style>
<body>
<div class="row">
<div id="mymapid" style="width: 100%; height: 500px;"></div>
</div>
<script>
var objCheck = []
var surface = "https://raw.githubusercontent.com/Alex-Devoid/Crime_Rate_by_zipcode_2017_TPD/master/tucsonCityLimits.geojson";
var votesByPrecinct = "votes_by_precinct_TucsonPrimary2019.geojson";
var mymap = L.map('mymapid').setView([32.118638011730695, -110.79162597656251], 10);
// var sat = L.tileLayer('https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiYWRldm9pZDE2IiwiYSI6ImNqeWtpN2xpcDA5YzEza24xd3k4ajd3ZmoifQ.Kk8GtRCZU0nK4bZwu5AnBw', {
// attribution: 'Arizona Daily Star | mymap data &copy; <a href="http://openstreetmymap.org">OpenStreetmymap contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA, Imagery &copy; <a href="http://mapbox.com">mapbox',
// maxZoom: 19,
// zoomDelta: 0.25,
// zoomSnap: 0.25,
// wheelPxPerZoomLevel: 100
//
// })
var osm = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
zoomSnap: 0.25,
// wheelPxPerZoomLevel: 100,
attribution: 'map data &copy; <a href="https://www.openstreetmymap.org/">OpenStreetmymap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">mapbox</a>',
id: 'mapbox.streets'
})
var basemymaps = {
"Street mymap": osm
};
var info = L.control();
info.onAdd = function (mymap) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
osm.addTo(mymap);
d3.json(votesByPrecinct, function(error, votesPrecinct) {
d3.json(surface, function(error, tucsonBoundary1) {
if (error) throw error;
// console.log(tucsonBoundary);
//
// var anex = topojson.topology({"Annexations":tucsonBoundary});
//
// console.log(anex);
//
// var selected = d3.set([
// 'TUC'
// ]);
//
// var deannex = d3.set([
// 'N'
// ]);
//
// var tucsonBoundary1 = topojson.merge(anex, anex.objects.Annexations.geometries.filter(function(d) {
// return selected.has(d.properties.CITY_CD) && deannex.has(d.properties.DEANNEX)
// }));
function sumVotes(voteFeatures){
var voteProperties = voteFeatures.properties["Primary_Results2019"];
var votesObj = {"candidates":{
"Randi Dorman": (Number(voteProperties[0]["Mayor"]['DEM']["DORMAN, RANDI"]) + Number(voteProperties[1].Mayor['DEM']["DORMAN, RANDI"])),
"Steve Farley": (Number(voteProperties[0].Mayor['DEM']["FARLEY, STEVE"]) + Number(voteProperties[1].Mayor['DEM']["FARLEY, STEVE"])),
"Regina Romero": (Number(voteProperties[0].Mayor['DEM']["ROMERO, REGINA"])+ Number(voteProperties[1].Mayor['DEM']["ROMERO, REGINA"])),
}
};
var mostVotesKey = Object.keys(votesObj.candidates).reduce(function(a, b){ return votesObj.candidates[a] > votesObj.candidates[b] ? a : b });
votesObj['mostVotes'] = mostVotesKey;
votesObj['precinct'] = voteFeatures.properties["PRECINCT"];
var sortvotes = [];
for (var candidate in votesObj.candidates) {
sortvotes.push([candidate, votesObj.candidates[candidate]]);
}
sortvotes.sort(function(a, b) {
return a[1] - b[1];
});
votesObj['sorted'] = sortvotes;
objCheck.push(votesObj)
if((votesObj.sorted[0][1] +votesObj.sorted[1][1]+votesObj.sorted[2][1]) === 0){
votesObj['mostVotes'] = "No one";
}
return votesObj;
}
function getColor(obj){
console.log(obj)
if(obj.mostVotes === 'Randi Dorman'){
return "#66c2a5";
}else if(obj.mostVotes === 'Steve Farley'){
return '#fd3cac';
}else if(obj.mostVotes === 'Regina Romero'){
return "#fd8d3c";
}else if((obj.sorted[0][1] +obj.sorted[1][1]+obj.sorted[2][1]) === 0){
return '#fdee3c';
}
}
info.update = function (props) {
var votesObjCan;
if (props) {
votesObjCan = sumVotes(props)
}
this._div.innerHTML = '<h3>Democratic Mayoral Votes by Precinct</h3>' + (props ?
'<b>' + votesObjCan.mostVotes + '</b> took precinct '+ votesObjCan.precinct + " with <b>" +votesObjCan.candidates[votesObjCan.mostVotes] +'</b> votes.<br />' + `${votesObjCan.sorted[1][0]}: ${votesObjCan.sorted[1][1]}<br />`+`${votesObjCan.sorted[0][0]}: ${votesObjCan.sorted[0][1]} votes`
: 'Hover over a state');
};
info.addTo(mymap);
function style(feature) {
return {
weight: 2,
opacity: .6,
color: 'white',
dashArray: '3',
fillOpacity: 0.55,
fillColor: getColor(sumVotes(feature))
};
}
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 4,
color: '#666',
// dashArray: '',
fillOpacity: 0.2
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
info.update(layer.feature);
}
var geojson;
function resetHighlight(e) {
geojson.resetStyle(e.target);
info.update();
}
function zoomToFeature(e) {
mymap.fitBounds(e.target.getBounds());
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
}
var myStyle = {
"color": "#000000",
"weight": 5,
"opacity": 1
};
L.geoJSON(tucsonBoundary1,{style:myStyle
}).addTo(mymap);
geojson = L.geoJSON(votesPrecinct, {
style: style,
onEachFeature: onEachFeature
// style: function(feature) {
// console.log(feature);
//
//
// var votesSum = sumVotes(feature.properties["Primary_Results2019"])
//
//
// switch (votesSum.mostVotes) {
// case 'randi': return {color: "#b2df8a", fill: true,
// opacity: .75, fillOpacity: .75};
//
//
//
// case 'regina': return {color: "#1f78b4",
// fill: true,
// opacity: .5, fillOpacity: .75};
// case 'steve': return {color: "#a6cee3", fill: true,
// opacity: .75, fillOpacity: .75};
//
//
// }
// }
}).addTo(mymap);
console.log(votesPrecinct.features.length);
console.log(objCheck);
mymap.fitBounds(geojson.getBounds());
var legend = L.control({position: 'bottomleft'});
legend.onAdd = function () {
var div = L.DomUtil.create('div', 'info legend');
// loop through our density intervals and generate a label with a colored square for each interval
div.innerHTML =
'<p><strong>Democratic Mayoral Candidates' + '<'+'/'+'strong'+'>' + '<'+'/'+'p'+'>' +
'<i style="background:'+"#fd8d3c" + '">'+'<'+'/'+'i'+'>' + "Regina Romero" + '<'+'/'+'p'+'>'+
'<i style="background:'+'#fd3cac' + '">'+'<'+'/'+'i'+'>' + "Steve Farley" + '<'+'/'+'p'+'>'+
'<i style="background:'+"#66c2a5" + '">'+'<'+'/'+'i'+'>' + "Randi Dorman" + '<'+'/'+'p'+'>'+
'<i style="background:'+"#fdee3c" + '">'+'<'+'/'+'i'+'>' + "Zero Votes" + '<'+'/'+'p'+'>';
return div;
};
legend.addTo(mymap);
L.control.scale({position: 'bottomright',metric: false }).addTo(mymap);
})
mymap.on('zoomend',function(e) {
// console.log(e.target.getZoom());
})
mymap.on('click', function(ev){
var coordinates = mymap.getCenter()
console.log(coordinates);
});
});
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment