Skip to content

Instantly share code, notes, and snippets.

@ozanyusufoglu
Last active September 12, 2017 09:07
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 ozanyusufoglu/8cb453c091138829f41fabfd4bc7ed0d to your computer and use it in GitHub Desktop.
Save ozanyusufoglu/8cb453c091138829f41fabfd4bc7ed0d to your computer and use it in GitHub Desktop.
zoomable v2
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="http://d3js.org/topojson.v2.min.js"></script>"
<style>
.background {
fill: none;
pointer-events: all;
}
#info {
position:absolute;
top: 10px;
left: 10px;
}
h1 {
font-family:arial;
font-size:2em;
color:#333;
}
#city-layer {
fill: #ccc;
cursor: pointer;
}
#city-layer .active {
fill : orange;
}
#city-mesh {
fill: none;
stroke: #fff;
stroke-width: 1.5px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
}
#town-mesh {
fill: none;
stroke: #fff;
stroke-width: 0.2px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
}
.town {
fill: #ccc ;
}
.town:hover, .city:hover {
fill: orange;
}
</style>
</head>
<body>
<script>
// feature zooming to polygons : https://bl.ocks.org/mbostock/2206590
// extract administrative geojson for whole turkey
// put the data layer on map
const d3 = require('d3');
const topojson = require('topojson')
var townData = []
var cityData = []
var townGeo = {};
var cityGeo = {};
var width = 700;
var height = 500;
var active = d3.select(null);
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
svg.append('rect')
.attr('class', 'background')
.attr('width', width)
.attr('height', height)
.on('click', reset);
const g = svg.append('g');
const projection = d3.geoMercator()
const zoom = d3.zoom()
.scaleExtent([1, 8])
.on("zoom", zoomed);
svg.call(zoom);
var path = d3.geoPath().projection(projection);
var color = d3.scaleThreshold()
.domain([0, 50, 100, 125, 150, 500, 1000, 2000])
.range(['rgba(247,251,255,0.8)', 'rgb(222,235,247)', 'rgb(198,219,239)', 'rgb(158,202,225)', 'rgb(107,174,214)', 'rgb(66,146,198)', 'rgb(33,113,181)', 'rgb(8,81,156)', 'rgb(8,48,107)']);
d3.queue()
.defer(d3.json, './geodata/tr_simple.json')
.defer(d3.csv, './miscdata/pivot.csv')
.awaitAll(draw)
d3.request("http://localhost:8080/miscdata/tr_pop_per_region.txt")
.mimeType("application/json")
.response(function(xhr) {
return xhr.responseText
})
.get(parseTowns)
var cities;
var towns;
function draw(err, results) {
const tr = results[0]; //topojson
const data = results[1]; // city pop data
console.log('Exported population data:\n', data);
/* color.domain([
d3.min(data, function(d) {
return d.population;
}),
d3.max(data, function(d) {
return d.population;
})
]);
*/
cities = topojson.feature(tr, tr.objects.cities); // carry these to findPolygon
towns = topojson.feature(tr, tr.objects.towns)
cities.features.map(function(e, i) {
for (let i = 0; i < data.length; i++) {
if (e.properties.NAME_1 === data[i].city) {
var newProps = {
tr_id: data[i].tr_id,
name: e.properties.NAME_1,
provider_data : [{
name: "JTI",
value: 0
}, {
name: "PMI",
value: 0
}, {
name: "IT",
value: 0
}, {
name: "TEKEL",
value: 0
}, {
name: "ET",
value: 0
}, {
name: "BAT",
value: 0
}, {
name: "KTG",
value: 0
}, {
name: "BOGAZICI",
value : 0
}],
id: e.properties.ID_1
}
return e.properties = newProps;
}
}
})
console.log(cities)
projection.fitExtent([
[0, 0],
[width, height]
], cities);
g.append('g')
.attr('id', 'town-layer')
.selectAll('path')
.data(towns.features)
.enter()
.append('path')
.attr('d', path)
.attr('class', 'town')
.on('click', clicked)
.on('mouseover', function(d) {
var props = d.properties;
return document.getElementById('name').innerHTML = props;
})
// cities first
g.append('g')
.attr('id', 'city-layer')
.selectAll('path')
.data(cities.features)
.enter()
.append('path')
.attr('d', path)
.attr('class', 'city')
.on('click', clicked)
.on('mouseover', function(d) {
var props = d.properties;
return document.getElementById('name').innerHTML =
"<pre>" +
"Name: " + props.name + "\n" +
"Value: " + props.population + '\n' +
"ID: " + props.tr_id +
"</pre>"
})
update()
g.append('path')
.datum(topojson.mesh(tr, tr.objects.towns, function(a, b) {
return a !== b;
}))
.attr('id', 'town-mesh')
.attr('d', path)
g.append('path')
.datum(topojson.mesh(tr, tr.objects.cities, function(a, b) {
return a !== b;
}))
.attr('id', 'city-mesh')
.attr('d', path)
}
d3.interval(function(){
d3.request("https://jti-test.tsmgateway.com/api/analytics/location_sales?scope=last_90_days")
.mimeType("application/json")
.response(function(xhr) {
return JSON.parse(xhr.responseText).data
})
.get(findPolygon)
update()
}, 2000)
function clicked(d) {
if (active.node() === this) return reset();
active.classed("active", false);
active = d3.select(this).classed("active", true);
var bounds = path.bounds(d),
dx = bounds[1][0] - bounds[0][0],
dy = bounds[1][1] - bounds[0][1],
x = (bounds[0][0] + bounds[1][0]) / 2,
y = (bounds[0][1] + bounds[1][1]) / 2,
scale = Math.max(1, Math.min(8, 0.9 / Math.max(dx / width, dy / height))),
translate = [width / 2 - scale * x, height / 2 - scale * y];
svg.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity.translate(translate[0], translate[1]).scale(scale));;
}
function reset() {
active.classed("active", false);
active = d3.select(null);
svg.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity);
}
function zoomed() {
g.style("stroke-width", 1.5 / d3.event.scale + "px");
g.attr("transform", d3.event.transform);
function stopped() {
if (d3.event.defaultPrevented) d3.event.stopPropagation();
}
}
/*
// zoom to bounding box v1
function clicked(d) {
if (active.node() === this) return reset();
active.classed('active', false);
active = d3.select(this).classed('active', true);
var bounds = path.bounds(d),
dx = bounds[1][0] - bounds[0][0],
dy = bounds[1][1] - bounds[0][1],
x = (bounds[0][0] + bounds[1][0]) / 2,
y = (bounds[0][1] + bounds[1][1]) / 2,
scale = .9 / Math.max(dx / width, dy / height),
translate = [width / 2 - scale * x, height / 2 - scale * y];
g.transition()
.duration(750)
.style('stroke-width', 1.5 / scale + 'px')
.attr('transform', 'translate(' + translate + ')scale(' + scale + ')');
}
function reset() {
active.classed('active', false);
active = d3.select(null);
g.transition()
.duration(750)
.style('stroke-width', '1.5px')
.attr('transform', '');
}
*/
/* Bar chart için
svg.selectAll('rect')
.data(geojson.features)
.enter()
.append('rect')
.attr('transform', function(d) { return 'translate(' + path.centroid(d) + ')rotate(180)'; })
.attr('width','10px')
.attr('height',function(d){
return d.properties.value * 0.001
}).style('fill', function(d) {
var value = d.properties.value;
if (value) {
return color(value);
} else {
return '#ccc';
}
});
*/
function unwind(topojson) {
console.log('inside');
topojson.features.forEach(item => {
if (d3.geoArea(item) > 2 * Math.PI) {
item.geometry.coordinates = item.geometry.coordinates.map(f => f.map(e => e.reverse()));
item.properties.error = true;
}
})
}
function parseTowns(text) {
var lines = text.split(/\n/);
lines.forEach(function(e) {
let items = e.split(/\s/);
let dataObj = {
id: items[0],
name: items[1],
parent: items[2],
population: items[3],
admin_level: 2,
}
townData.push(dataObj)
})
}
function findPolygon(salesobj) {
salesobj.forEach(function(sale) {
var points = [sale.lon, sale.lat]
console.log(points)
cities.features.forEach(function(feature) {
if (d3.geoContains(feature, points)) {
feature.properties.provider_data[0].value++
}
})
})
}
function update(){
generateRandom();
d3.select("#city-layer").selectAll('path')
.data(cities.features)
.style('fill', function(d) {
var value = d.properties.provider_data[0].value
if (value) {
return color(value);
} else {
return '#ccc';
}
})
}
function generateRandom(){
console.log(towns.features);
var istanbul_towns = towns.features.filter(function(feature){
if( feature.properties.NAME_1 == "Istanbul")
return feature;
})
console.log(istanbul_towns);
istanbul_towns.forEach()
}
</script>
</body>
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