How to display the value (sum) rather than count of markers in a dc.leaflet.js - leaflet

I want to use crossfilter's reduceSum function dc.leaflet.js, and display the sum instead of the number of clustered markers.
The first example for dc.leaflet.js uses reduceCount. Additionally it doesn't use the reduced value; it just displays the number of markers in the cluster.
I want to use the sum of data using reduceSum.
Here is my data as tsv:
type geo say
wind 38.45330,28.55529 10
wind 38.45330,28.55529 10
solar 39.45330,28.55529 10
Here is my code:
<script type="text/javascript" src="../js/d3.js"></script>
<script type="text/javascript" src="../js/crossfilter.js"></script>
<script type="text/javascript" src="../js/dc.js"></script>
<script type="text/javascript" src="../js/leaflet.js"></script>
<script type="text/javascript" src="../js/leaflet.markercluster.js"></script>
<script type="text/javascript" src="../js/dc.leaflet.js"></script>
<script type="text/javascript">
/* Markers */
d3.csv("demo1.csv", function(data) {
drawMarkerSelect(data);
});
function drawMarkerSelect(data) {
var xf = crossfilter(data);
var facilities = xf.dimension(function(d) { return d.geo; });
var facilitiesGroup = facilities.group().reduceSum(function(d){return d.say});
dc.leafletMarkerChart("#demo1 .map")
.dimension(facilities)
.group(facilitiesGroup)
.width(1100)
.height(600)
.center([39,36])
.zoom(6)
.cluster(true);
var types = xf.dimension(function(d) { return d.type; });
var typesGroup = types.group().reduceSum(function(d){return d.say});
dc.pieChart("#demo1 .pie")
.dimension(types)
.group(typesGroup)
.width(200)
.height(200)
.renderLabel(true)
.renderTitle(true)
.ordering(function (p) {
return -p.value;
});
dc.renderAll();
}
</script>

I have rewritten the question because it was very unclear. I agree with #Kees that the intention was probably to display the sum in a clustered marker chart, rather than "reduceSum doesn't work".
#Kees also pointed out a Leaflet.markercluster issue which gives basic information about how to display a sum inside a marker cluster.
The question becomes, how to apply these customizations to dc.leaflet.js?
First, I've created a version of the example data with another column rnd:
type geo rnd
wind 43.45330,28.55529 1.97191
wind 43.44930,28.54611 3.9155
wind 43.45740,28.54814 3.9922
...
We can use reduceSum like this:
var facilitiesGroup = facilities.group().reduceSum(d => +d.rnd);
And annotate each marker with its value by overriding .marker(), wrapping the default callback:
const old_marker_function = marker.marker();
marker.marker(function(d, map) {
const m = old_marker_function(d, map);
m.value = d.value;
return m;
});
And we can specify a different rendering of the icon using .clusterOptions():
marker.clusterOptions({
iconCreateFunction: function(cluster) {
var children = cluster.getAllChildMarkers();
var sum = 0;
for (var i = 0; i < children.length; i++) {
sum += children[i].value;
}
sum = sum.toFixed(0);
var c = ' marker-cluster-';
if (sum < 10) {
c += 'small';
} else if (sum < 100) {
c += 'medium';
} else {
c += 'large';
}
return new L.DivIcon({ html: '<div><span>' + sum + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });
}
});
The example given in the above issue was missing any styling, so I copied the implementation of _defaultIconCreateFunction from the Leaflet.markercluster sources, and modified it.
Demo fiddle
As expected, the numbers are close to 2.5 times the original numbers (since the new column is a random number from 0 to 5).
Putting numbers on the individual markers
marker.icon() allows you change the icon for individual markers, so you can use DivIcon with similar styling to display the numbers:
marker.icon(function(d, map) {
return new L.DivIcon({
html: '<div><span>' + d.value.toFixed(0) + '</span></div>',
className: 'marker-cluster-indiv marker-cluster',
iconSize: new L.Point(40, 40) });
});
This introduces a new class .marker-cluster-indiv to distinguish it from the others; in the new fiddle I've colored them blue with
.marker-cluster-indiv {
background-color: #9ecae1;
}
.marker-cluster-indiv div {
background-color: #6baed6;
}
The interaction is perhaps less clear since clicking blue dots brings up a popup instead of expanding. Perhaps a different icon should be used.

The reduceSum part should work fine, since that is just a different crossfilter function.
Are you sure that your data is getting read correctly? You state that it is a tsv file, and show code that looks like it is tab-separated, but then you use d3.csv to load it, which would have pretty bad effects considering there is a comma in the middle of the second field.
Please try console.log(data) after your data is loaded, and verify that it is loading correctly.
Also, you do not state what problem you encounter. "It doesn't work" does not help us help you.

Related

How to prevent Google Charts from changing x-axis order?

I'm trying to draw a Google Chart whose x-axis represents the week numbers. As we're crossing a new year, the axis goes 50, 51, 52, 1, 2, 3, ....
I'm properly ordering my data, but Google Charts insists on reordering my x-axis, and I end up with a weird graph:
var chartData = [
["Week","Revenue"],
[40,227],
[41,317],
[42,320],
[43,482],
[44,418],
[45,345],
[46,313],
[47,316],
[48,380],
[49,467],
[50,349],
[51,256],
[52,393],
[1,276],
[2,349],
[3,312]
];
google.load("visualization", "1", {
packages:["corechart"],
callback: function() {
var div = document.getElementById('chart');
var chartDataTable = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization['LineChart'](div);
chart.draw(chartDataTable);
}});
<div id="chart" style="height: 400px;">test</div>
<script src="//www.google.com/jsapi"></script>
How can I prevent it from reordering my data?
google's object notation allows you to provide a value (v:) and a formatted value (f:)
thus, you can use a value of 1 with a format of '40'
e.g. --> {v: 1, f: '40'}
in a row --> [{v: 1, f: '40'},227]
the following working snippet uses object notation to re-format the values for the x-axis,
and re-use those values for the x-axis labels (hAxis.ticks)
var chartData = [
["Week","Revenue"],
[40,227],
[41,317],
[42,320],
[43,482],
[44,418],
[45,345],
[46,313],
[47,316],
[48,380],
[49,467],
[50,349],
[51,256],
[52,393],
[1,276],
[2,349],
[3,312]
];
var hAxisTicks = [];
chartData.forEach(function (row, index) {
if (index === 0) {
return;
}
row[0] = {
v: index,
f: row[0].toString()
};
hAxisTicks.push(row[0]);
});
google.charts.load('current', {
callback: function () {
var div = document.getElementById('chart');
var chartDataTable = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization['LineChart'](div);
chart.draw(chartDataTable, {
hAxis: {
ticks: hAxisTicks
}
});
},
packages:['corechart']
});
<div id="chart"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>
note:
recommend using loader.js to load the the library, instead of jsapi
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
this only changes the load statement, see snippet above...
EDIT:
there are more options available for continuous axis
which must be sorted, or in reverse sort order ('number', 'date' values)
but the chart will respect the original sort order for a discrete axis ('string' values)
see following snippet for 'string' values
and discrete vs. continuous for more...
var chartData = [
["Week","Revenue"],
[40,227],
[41,317],
[42,320],
[43,482],
[44,418],
[45,345],
[46,313],
[47,316],
[48,380],
[49,467],
[50,349],
[51,256],
[52,393],
[1,276],
[2,349],
[3,312]
];
chartData.forEach(function (row, index) {
if (index === 0) {
return;
}
row[0] = row[0].toString();
});
google.charts.load('current', {
callback: function () {
var div = document.getElementById('chart');
var chartDataTable = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization['LineChart'](div);
chart.draw(chartDataTable);
},
packages:['corechart']
});
<div id="chart"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>

Google Visualization Chart Data Range

I have this code,
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1ntnhvfMhYtFNwFjkoKu8cUZOQPCaT5_U1Z6piB_w0-E/edit#gid=0');
query.setQuery('order by A');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
title: 'TEMP & HUMID',
hAxis: {
direction: -1
},
legend: 'none'
};
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.getElementById('columnchart'));
chart.draw(data, options);
}
</script>
<title>Data from a Spreadsheet</title>
</head>
<body>
<div id="columnchart" style="width: 900px; height: 500px"></div>
</body>
</html>
And here is my spreadsheet data: https://docs.google.com/spreadsheets/d/1ntnhvfMhYtFNwFjkoKu8cUZOQPCaT5_U1Z6piB_w0-E
What I want to do is to plot last 5 data. i.e) row 8 - 12 in my spreadsheet.
I tried the limit and range queries, but what I want to do is, if a new data comes in, I want the chart to refer the updated last 5 data i.e) row 9 -13
How could I achieve this?
I don't know if this is a best approach, but I work it out.
So, before drawing the table, I actually called the spreadsheet in JSON format and retrieve its column length.
Then I subtracted the column length by number of data I want to display (limit query) which will give me offset to start.
Then I made a string with the value of limit and offset to pass the query option to query.setQuery.
Here is the code for the part.
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1NSEbUWojJsMzhH0hi8kx8ic7Xxuq29z0c7BXs-inzb8/edit#gid=0');
$.getJSON("https://spreadsheets.google.com/feeds/list/1NSEbUWojJsMzhH0hi8kx8ic7Xxuq29z0c7BXs-inzb8/od6/public/basic?hl=en_US&alt=json", function(data) {
colLen = data.feed.entry.length;
console.log(colLen);
limit = 4;
var offset = colLen - limit;
console.log(offset);
queryOption = "limit "+limit+" offset "+offset;
console.log(queryOption);
query.setQuery(queryOption);
query.send(handleQueryResponse);
});
}

Destroy leaflet map trouble

I use several leaflet maps at one time. They can be created and deleted dynamically. But when a map is destroyed by using the map.remove() there is a memory leak. Detached DOM trees appears. You can see it in Chrome Dev Tools.
Screenshot with a leak.
Example function I use to recreate div and map:
var map, mapDiv;
recreateMap = function(){
// destroy previous map and div
if(map) map.remove();
if(mapDiv) mapDiv.parentNode.removeChild(mapDiv);
// create new map div
var randomDivId = 'mapId' + new Date().getTime();
mapDiv = document.createElement('div');
mapDiv.id = randomDivId;
mapDiv.style.height = '200px';
mapDiv.style.width = '200px';
document.getElementsByTagName('body')[0].appendChild(mapDiv);
// attach map to div
map = L.map(randomDivId).setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);
map.invalidateSize();
};
Working example here.
How to properly destroy the leaflet maps?
Assume you create a leaflet map with some thing like the following
var lat =39, long = 40;
var coords=[lat,long];
var zoomLevel=13;
var mapInstance = leafLet.map(mapContainerId).setView(coords, zoomLevel);
You can remove it using the following code
if (mapInstance && mapInstance.remove) {
mapInstance.off();
mapInstance.remove();
}
If you are working with non blocking javascript code or async calls, if required you can use a timer to ensure that your code does not error out. Following is a sample implementation of the same
var timeoutIndex=0;
var watcher=window.setInterval(function(){
timeoutIndex++;
if (mapInstance && mapInstance.remove) {
mapInstance.off();
mapInstance.remove();
window.clearInterval(watcher);
}
if(timeoutIndex >50) { //wait for 5 seconds before giving up
window.clearInterval(watcher);
}
},100);
It worked for me. Guess it helps you too
If you have several maps, you need to put each map into diffents var.
var map1 = L.map(mapDiv1);
var map2 = L.map(mapDiv2);
You can also create a function to control map initialisation and container :
function BoolMapInit(map, mapDiv) {
return (map != null && map._container.id == divMap);
}
And the fonction to remove existing map :
function RemoveExistingMap(map) {
if (map != null) {
map.remove();
map = null;
}
}
Hope this help ;)
I had the same problem, and after spending much time on it, the best solution for this problem is to put the map container in a div, and when you want to regenerate the map, remove all of the div's HTML and create a new map container:
<div id="map-bx">
<div id="map"></div>
</div>
<script type="text/javascript">
// Map init
</script>
and when you want to regenerate (destroy) the map like so:
<script type="text/javascript">
$("#map-box").html("");
$("#map-box").html('<div id="map"></div>');
// map init code
</script>
in my case, map.remove() or map.unload() do not work.
maybe try to unload map first? (documentation says that map is being unloaded automatically when using remove method but it's worth to give an additional shot and try unload it manually first)

Why is childNodes not working in this script?

I am new to JS and trying to learn some basic stuff. I have spent hours on this but i don't think it should be that difficult. For some reason, my computer is not recognizing that I am asking for childNodes.
This is a simply script that is only trying to count the number of li tags I have. I know there are other ways to do this but i am trying to learn this way.
<title>To-Do List</title>
<script>
function findComments(){
var bodyTag = document.getElementsByTagName("ol");
var count = 0;
for(var i=0;i<bodyTag.childNodes.length;i++){
if(bodyTag.childNodes[i].nodeType == 1){
count++;
}
}
alert(count);
}
window.onload = findComments;
</script>
<!--List is declared-->
<ol id="toDoList">
<!--List Items are created-->
<li>Mow the lawn</li>
<li>Clean the windows</li>
<li>Answer your email</li>
</ol>
<!--Main paragraph-->
<p id="toDoNotes">Make sure all these are completed by 8pm so you can watch the game on TV!</p>
<script>
</script>
getElementsByTagName returns an array, you need to retrieve its first element (and change the name from bodyTag to olTag or something since it's not the body tag and confused the heck out of me trying to make sense of your code)
function findComments(){
var ol = document.getElementsByTagName("ol")[0];
var count = 0;
for(var i=0;i<ol.childNodes.length;i++){
if(ol.childNodes[i].nodeType == 1){
count++;
}
}
alert(count);
}
And here's what you really should do now that you know what's wrong with your code
var ol = document.getElementsByTagName("ol")[0];
var liCount = ol.getElementsByTagName("li").length;

D3 filtering data points

I'm implementing the classic mercator example (https://github.com/mbostock/d3/blob/master/examples/mercator/mercator.html), which I've changed to zoom into Afghanistan and to use only one custom slider. I'm reading in GeoJSON data of places where explosions have happened and the graph maps them all at load. I want to use the slider to view only a month of explosion points at a time but am having trouble filtering the results. I've tried several things based on posts in the Google group but fail to understand how to filter the data read in previously from 'explosions.json'. Thanks for the help!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>IED Attacks in Afghanistan (2004-2009)</title>
<script type="text/javascript" src="../d3.v2.js"></script>
<script type="text/javascript" src="../lib/jquery/jquery.min.js"></script>
<script type="text/javascript" src="../lib/jquery-ui/jquery-ui.min.js"></script>
<style type="text/css">
#import url("../lib/jquery-ui/jquery-ui.css");
body, .ui-widget {
font: 14px Helvetica Neue;
}
svg {
width: 960px;
height: 600px;
border: solid 1px #ccc;
background: #eee;
}
line {
stroke: brown;
stroke-dasharray: 4,2;
}
path {
fill: #ccc;
stroke: #fff;
}
div {
width: 960px;
}
</style>
</head>
<body>
<h3>IED Attacks in Afghanistan (2004-2009)</h3>
<script type="text/javascript">
// Create the Mercator Projection (Map)
var xy = d3.geo.mercator(),
path = d3.geo.path().projection(xy);
// Create the states variable
var states = d3.select("body")
.append("svg")
.append("g")
.attr("id", "states");
// Create the equator variable
var equator = d3.select("svg")
.append("line")
.attr("x1", "0%")
.attr("x2", "100%");
// Create the explosions variable
var explosions = d3.select("svg")
.append("g")
.attr("id","explosions");
// Load in the states & equator data from the file 'world-countries.json'
d3.json("world-countries.json", function(collection) {
states
.selectAll("path")
.data(collection.features)
.enter().append("path")
.attr("d", path)
.append("title")
.text(function(d) { return d.properties.name; });
equator
.attr("y1", xy([0, 0])[1])
.attr("y2", xy([0, 0])[1]);
});
// the variable that holds our translate, center on Afghanistan
var translate = xy.translate(); //create translation to center gride in different area
translate[0] = -1741;
translate[1] = 1487;
xy.translate(translate); // center
xy.scale(12000); //zoom in
// Load in the explosions data from the file 'explosions.json'
d3.json("explosions.json", function(collection) {
explosions
.selectAll("path") //make a path and attach data
.data(collection.features)
.enter().append("path")
.attr("d", path)
.style("stroke","red") //color the path points
.style("stroke-width",2) //size of point stroke
.attr("class","explosionpoint")
.append("title") //title is the 'name' field in the json file
.text(function(d) { return d.properties.name; });
});
</script>
<p></p>
<!-- Slider -->
<div id="scale"></div><p></p>
<script type="text/javascript">
$("#scale").slider({
min: 20040101, //min : 1/1/04
max: 20100101, //max: 1/1/10
value: 20060601, //default slider value
step: 100, // step is the allow increments the slider can move. 100 = one month
slide: function(event, ui) {
/* REMOVE ALL EXPLOSION PATHS EXCEPT FOR A PARTICULAR MONTH OR RELOAD WITH FILTERED RESULTS */
}
});
</script>
You'll need to post part or all of your explosions.json object for a concrete answer. However, something like this will filter a JSON if it's structured like {explosion1:{data1:true, data2:true}, explosion2:{data1:true, data2:false}}:
function filterJSON(json, key, value) {
var result = {};
for (var explosionIndex in json) {
if (json[explosionIndex][key] === value) {
result[explosionIndex] = json[explosionIndex];
}
}
return result;
}
(e.g. filterJSON(myjson, "data1", true) will give all explosions with data1:true)
This is not specific to d3.
Then you could use something like this for the d3-side of things:
explosions.data(myFilteredData).exit().remove(); // remove ones you don't want
explosions.enter().append("path")... // add back ones you do want
If I understand your application, it would actually be better to just toggle the visiblity attribute of the SVG elements.
var sliderrange = [20040101, 20040201]; //replace with code based on your slider
explosions.selectAll(".explosionpoint").attr("visibility", function(d) {
//Replace with the correct date comparison logic
return d.date < sliderrange[1] && d.date > sliderrange[0] ? "visible" : "hidden";
});
D3 does have a very natural way of doing this. I'll assume your data looks something like this:
[{name: explosion1name, day: 20040110,...}, {name: explosion2name, day: 20040111,...}]
...and that you've got some variable, we'll call it explosionsData, to reference the data.
You can then draw your explosions with a function that takes the values from your slider. See the .filter I've added below.
function drawExplosions(startDay, endDay) {
explosions.selectAll("path") //make a path and attach data
.data(collection.features)
.enter().append("path")
.filter( function (d) { return ( (d.day > startDay) && (d.day < endDay) )})
.attr("d", path)
.style("stroke","red") //color the path points
.style("stroke-width",2) //size of point stroke
.attr("class","explosionpoint")
.append("title") //title is the 'name' field in the json file
.text(function(d) { return d.properties.name; });
Just call this function whenever your slider values changes.