Skip to content

Instantly share code, notes, and snippets.

@serdaradali
Last active March 29, 2018 09:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serdaradali/11276011 to your computer and use it in GitHub Desktop.
Save serdaradali/11276011 to your computer and use it in GitHub Desktop.
Choropleth map zoom
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.background {
fill: none;
pointer-events: all;
}
.choropleth {
margin: 20px 20px;
}
.cities {
stroke: #fff;
stroke-width: 1px;
stroke-linejoin: round;
}
.districts {
stroke: #fff;
stroke-width: 0.5px;
stroke-linejoin: round;
}
.choro_outline {
opacity: 1;
stroke: #000;
stroke-width: 1.5px;
}
.tooltip {
width: 60px;
height:20px;
position: absolute;
opacity: 0;
padding: 6px 8px;
font: 8px/10px 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;
}
.zoomout {
width: 50px;
height: 50px;
background: url("left-arrow-icon.jpg");
background-size: contain;
position: absolute;
top: 10px;
left: 30px;
z-index: 5;
}
#switch{
position:absolute;
left:650px;
top:130px;
width: 120px;
height: 30px;
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
}
</style>
<body>
<link type="text/css" rel="stylesheet" href="jquery.switchButton.css"/>
<script src="http://d3js.org/queue.v1.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script src="jquery.switchButton.js"></script>
<div id="map"></div>
<div id="switch"><input type="checkbox" id = "levelSwitch" value="1" checked></div>
<script>
function randomData(n)
{
var data = [];
for(var i=0; i<n;i++)
{
data[i] = Math.floor((Math.random())*100);
}
return data;
}
var width=960,height=600,centered;
var div = document.createElement("div");
var cityMapJSON = {}, districtMapJSON={};
var selectedCity,selectedCityDistricts, selectedNeighborCity, selectedNeighborCityDistricts, districtVotes,turkeyTotal = [0.44,0.28,0.15,0.09,0.03,0.01];
var cityScale = d3.scale.quantile(),districtScale = d3.scale.quantile(), barScale = d3.scale.linear().domain([0,100]).range([0,200]);
var colors7 = ["rgb(254,229,217)", "rgb(252,187,161)", "rgb(252,146,114)", "rgb(251,106,74)", "rgb(239,59,44)", "rgb(203,24,29)", "rgb(153,0,13)"];
var projection = d3.geo.mercator()
.scale(1)
.translate([0, 0]);
var zoomedIn = false;
var path = d3.geo.path()
.projection(projection);
var svg,citiG,barSvg,districtGregCenters = [];
var cityPath,districtPath;
var country,cityFeatures,districtFeatures;
var mapMode = 1; // variable holding detail type: 1=city level, -1=district level
queue()
.defer(d3.json, "turkeyCitiesTopoSimplified.json")
.defer(d3.json, "turkeyDistrictsTopoSimplified.json")
.await(readMapData);
function readMapData(error,cityJSON,districtJSON) {
var cityData = randomData(cityJSON.objects.turkeyCities.geometries.length),districtData=randomData(districtJSON.objects.turkeyDistricts.geometries.length);
var svg = d3.select("#map").append("svg")
.attr("width", width)
.attr("height", height)
.attr("class", "choropleth");
var div = d3.select("#statDetails").html("<p align=\"center\">Turkiye Geneli</p>");
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", clickedCity);
cityScale.domain(cityData)
.range(d3.range(6));
country = topojson.mesh(cityJSON, cityJSON.objects.turkeyCities),
cityFeatures = topojson.feature(cityJSON, cityJSON.objects.turkeyCities).features,
districtFeatures = topojson.feature(districtJSON, districtJSON.objects.turkeyDistricts).features;
var b = path.bounds(country),
s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];
projection
.scale(s)
.translate(t);
g = svg.append("g");
// draw city geometry and fill colors according to city election data
cityPath = g.selectAll("path.cities")
.data(cityFeatures)
.enter().append("path")
.attr("class","cities")
.attr("fill", function(d,i){
return colors7[cityScale(cityData[i])];})
.attr("d", path)
.on("click", clickedCity)
.on("mouseover", function(d,i) {
d3.select("#statDetails").html("<p align=\"center\">" + d.properties.NAME_1 + "</p>");
d3.select(this.parentNode.appendChild(this)).transition().duration(300)
.style({'stroke-opacity':1,'stroke':'#000'});
})
.on("mouseout", function(d,i) {
d3.select("#statDetails").html("<p align=\"center\">Turkiye Geneli</p>");
d3.select(this.parentNode.appendChild(this)).transition().duration(300)
.style({'stroke-opacity':1,'stroke':'#FFF'})
});
districtScale.domain(districtData)
.range(d3.range(6));
// draw district geometry and fill colors according to district election data. Hidden in the beginning
districtPath = g.selectAll("path.districts")
.data(districtFeatures)
.enter().append("path")
.attr("class","districts")
.attr("fill", function(m,i){
return colors7[districtScale(districtData[i])];})
.attr("d", path)
.on("mouseover", function(d,i) {
d3.select("#statDetails").html("<p align=\"center\">" + d.properties.NAME_2 + "," + d.properties.NAME_1 +"</p>");
d3.select(this.parentNode.appendChild(this)).transition().duration(300)
.style({'stroke-opacity':1,'stroke':'#000'});
})
.on("mouseout", function(d,i) {
d3.select("#statDetails").html("<p align=\"center\">" + d.properties.NAME_1 + "</p>");
d3.select(this.parentNode.appendChild(this)).transition().duration(300)
.style({'stroke-opacity':1,'stroke':'#FFF'});
})
.style("display","none");
$("#levelSwitch").change(function(){
mapMode *= -1;
if(mapMode == 1)
{
d3.selectAll("path.districts").style("display","none");
d3.selectAll("path.cities").style("display","inline");
}
else if(mapMode == -1)
{
d3.selectAll("path.cities").style("display","none");
d3.selectAll("path.districts").style("display","inline");
}
});
}
function clickedCity(d,i) {
var x, y, k;
// if not already zoomed, zoom in. If clicked on a neighbor, change focus
if (d && centered !== d) {
d3.select("#switch").style("display","none");
// fade out all cities except the clicked one
g.selectAll("path.cities")
.filter(function(m){
return m.properties.ID_1 != d.properties.ID_1})
.style("fill-opacity", 0.1);
// store selected city & its districts for later use
selectedCity = d3.selectAll("path.cities").filter(function(m){ return m == d});
selectedCityDistricts = g.selectAll("path.districts")
.filter(function(m){return m.properties.ID_1 == d.properties.ID_1});
// set translate&scale parameters for zooming into city
var centroid = path.centroid(d);
x = centroid[0];
y = centroid[1];
k = 4;
centered = d;
// if zoomed into a city from country level
if(!zoomedIn)
{
// create(or show) zoom out div
d3.select("#map").append("div")
.attr("class","zoomout")
.on("click",clickedCity);
}
else //already zoomed in, clicked to a neighbor city
{
// display previously hidden cities
d3.selectAll("path.cities").style("display","inline");
}
// hide all districts
g.selectAll("path.districts")
.style("display","none")
.style("fill-opacity",0.1);
// Only display selected city districts
selectedCityDistricts.style("display","inline");
// zoomed into district level
zoomedIn = true;
}
else { // zoom out
d3.select("#switch").style("display","inline");
zoomedIn = false;
x = width / 2;
y = height / 2;
k = 1;
centered = null;
// hide all visible districts
selectedCityDistricts.style("display","none");
g.selectAll("path.districts")
.style("fill-opacity",1);
// set display for hidden city
selectedCity.style("display","inline");
// restore all city opacities
g.selectAll("path.cities")
.transition()
.duration(750)
.style("fill-opacity", 1);
// remove zoom out div
d3.select("div.zoomout").remove();
}
g.selectAll("path")
.classed("active", centered && function(d) { return d === centered; });
g.transition()
.duration(750)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
.each("end",function(d)
{
if(zoomedIn)
{
// show all districts of selected city
selectedCityDistricts
.style("display","inline")
.style("fill-opacity", 1);
// slowly make zoomed city disappear so that disctrict can be seen. At the end, disable city for allowing mouse operations on districts
selectedCity.style("display","none")
.style("fill-opacity", 0.1)
.style("stroke-width", 1.5 / k + "px");
}
});
}
$("#levelSwitch").switchButton({
on_label: 'District',
off_label: 'City',
checked: false
});
d3.select(self.frameElement).style("height", height + "px");
</script>
</body>
.switch-button-label {
float: left;
font-size: 10pt;
cursor: pointer;
}
.switch-button-label.off {
color: #adadad;
}
.switch-button-label.on {
color: #0088CC;
}
.switch-button-background {
float: left;
position: relative;
background: #ccc;
border: 1px solid #aaa;
margin: 1px 10px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
cursor: pointer;
}
.switch-button-button {
position: absolute;
left: -1px;
top : -1px;
background: #FAFAFA;
border: 1px solid #aaa;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
/**
* jquery.switchButton.js v1.0
* jQuery iPhone-like switch button
* @author Olivier Lance <olivier.lance@sylights.com>
*
* Copyright (c) Olivier Lance - released under MIT License {{{
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
* }}}
*/
/*
* Meant to be used on a <input type="checkbox">, this widget will replace the receiver element with an iPhone-style
* switch button with two states: "on" and "off".
* Labels of the states are customizable, as are their presence and position. The receiver element's "checked" attribute
* is updated according to the state of the switch, so that it can be used in a <form>.
*
*/
(function($) {
$.widget("sylightsUI.switchButton", {
options: {
checked: undefined, // State of the switch
show_labels: true, // Should we show the on and off labels?
labels_placement: "both", // Position of the labels: "both", "left" or "right"
on_label: "ON", // Text to be displayed when checked
off_label: "OFF", // Text to be displayed when unchecked
width: 25, // Width of the button in pixels
height: 11, // Height of the button in pixels
button_width: 12, // Width of the sliding part in pixels
clear: true, // Should we insert a div with style="clear: both;" after the switch button?
clear_after: null, // Override the element after which the clearing div should be inserted (null > right after the button)
on_callback: undefined, //callback function that will be executed after going to on state
off_callback: undefined //callback function that will be executed after going to off state
},
_create: function() {
// Init the switch from the checkbox if no state was specified on creation
if (this.options.checked === undefined) {
this.options.checked = this.element.prop("checked");
}
this._initLayout();
this._initEvents();
},
_initLayout: function() {
// Hide the receiver element
this.element.hide();
// Create our objects: two labels and the button
this.off_label = $("<span>").addClass("switch-button-label");
this.on_label = $("<span>").addClass("switch-button-label");
this.button_bg = $("<div>").addClass("switch-button-background");
this.button = $("<div>").addClass("switch-button-button");
// Insert the objects into the DOM
this.off_label.insertAfter(this.element);
this.button_bg.insertAfter(this.off_label);
this.on_label.insertAfter(this.button_bg);
this.button_bg.append(this.button);
// Insert a clearing element after the specified element if needed
if(this.options.clear)
{
if (this.options.clear_after === null) {
this.options.clear_after = this.on_label;
}
$("<div>").css({
clear: "left"
}).insertAfter(this.options.clear_after);
}
// Call refresh to update labels text and visibility
this._refresh();
// Init labels and switch state
// This will animate all checked switches to the ON position when
// loading... this is intentional!
this.options.checked = !this.options.checked;
this._toggleSwitch();
},
_refresh: function() {
// Refresh labels display
if (this.options.show_labels) {
this.off_label.show();
this.on_label.show();
}
else {
this.off_label.hide();
this.on_label.hide();
}
// Move labels around depending on labels_placement option
switch(this.options.labels_placement) {
case "both":
{
// Don't move anything if labels are already in place
if(this.button_bg.prev() !== this.off_label || this.button_bg.next() !== this.on_label)
{
// Detach labels form DOM and place them correctly
this.off_label.detach();
this.on_label.detach();
this.off_label.insertBefore(this.button_bg);
this.on_label.insertAfter(this.button_bg);
// Update label classes
this.on_label.addClass(this.options.checked ? "on" : "off").removeClass(this.options.checked ? "off" : "on");
this.off_label.addClass(this.options.checked ? "off" : "on").removeClass(this.options.checked ? "on" : "off");
}
break;
}
case "left":
{
// Don't move anything if labels are already in place
if(this.button_bg.prev() !== this.on_label || this.on_label.prev() !== this.off_label)
{
// Detach labels form DOM and place them correctly
this.off_label.detach();
this.on_label.detach();
this.off_label.insertBefore(this.button_bg);
this.on_label.insertBefore(this.button_bg);
// update label classes
this.on_label.addClass("on").removeClass("off");
this.off_label.addClass("off").removeClass("on");
}
break;
}
case "right":
{
// Don't move anything if labels are already in place
if(this.button_bg.next() !== this.off_label || this.off_label.next() !== this.on_label)
{
// Detach labels form DOM and place them correctly
this.off_label.detach();
this.on_label.detach();
this.off_label.insertAfter(this.button_bg);
this.on_label.insertAfter(this.off_label);
// update label classes
this.on_label.addClass("on").removeClass("off");
this.off_label.addClass("off").removeClass("on");
}
break;
}
}
// Refresh labels texts
this.on_label.html(this.options.on_label);
this.off_label.html(this.options.off_label);
// Refresh button's dimensions
this.button_bg.width(this.options.width);
this.button_bg.height(this.options.height);
this.button.width(this.options.button_width);
this.button.height(this.options.height);
},
_initEvents: function() {
var self = this;
// Toggle switch when the switch is clicked
this.button_bg.click(function(e) {
e.preventDefault();
e.stopPropagation();
self._toggleSwitch();
return false;
});
this.button.click(function(e) {
e.preventDefault();
e.stopPropagation();
self._toggleSwitch();
return false;
});
// Set switch value when clicking labels
this.on_label.click(function(e) {
if (self.options.checked && self.options.labels_placement === "both") {
return false;
}
self._toggleSwitch();
return false;
});
this.off_label.click(function(e) {
if (!self.options.checked && self.options.labels_placement === "both") {
return false;
}
self._toggleSwitch();
return false;
});
},
_setOption: function(key, value) {
if (key === "checked") {
this._setChecked(value);
return;
}
this.options[key] = value;
this._refresh();
},
_setChecked: function(value) {
if (value === this.options.checked) {
return;
}
this.options.checked = !value;
this._toggleSwitch();
},
_toggleSwitch: function() {
this.options.checked = !this.options.checked;
var newLeft = "";
if (this.options.checked) {
// Update the underlying checkbox state
this.element.prop("checked", true);
this.element.change();
var dLeft = this.options.width - this.options.button_width;
newLeft = "+=" + dLeft;
// Update labels states
if(this.options.labels_placement == "both")
{
this.off_label.removeClass("on").addClass("off");
this.on_label.removeClass("off").addClass("on");
}
else
{
this.off_label.hide();
this.on_label.show();
}
this.button_bg.addClass("checked");
//execute on state callback if its supplied
if(typeof this.options.on_callback === 'function') this.options.on_callback.call(this);
}
else {
// Update the underlying checkbox state
this.element.prop("checked", false);
this.element.change();
newLeft = "-1px";
// Update labels states
if(this.options.labels_placement == "both")
{
this.off_label.removeClass("off").addClass("on");
this.on_label.removeClass("on").addClass("off");
}
else
{
this.off_label.show();
this.on_label.hide();
}
this.button_bg.removeClass("checked");
//execute off state callback if its supplied
if(typeof this.options.off_callback === 'function') this.options.off_callback.call(this);
}
// Animate the switch
this.button.animate({ left: newLeft }, 250, "easeInOutCubic");
}
});
})(jQuery);
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
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