Custom Map in Datamaps - javascript

Hello I'm using d3 js with datamaps and I want to show the few countries of the world. I have checked the online forum for the help but not get cleared idea or response.
Source code :
<div id="container" style="position: relative; width: 900px; height: 500px;"></div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="http://datamaps.github.io/scripts/0.4.4/datamaps.world.min.js"></script>
<script>
var map = new Datamap({
element: document.getElementById('container'),
fills: {
HIGH: '#afafaf',
LOW: '#123456',
MEDIUM: 'blue',
UNKNOWN: 'rgb(0,0,0)',
defaultFill: 'green'
},
dataType: 'json', //for use with dataUrl, currently 'json' or 'csv'. CSV should have an `id` column
dataUrl: null,
geographyConfig: {
dataUrl: null, //if not null, datamaps will fetch the map JSON (currently only supports topojson)
hideAntarctica: true,
borderWidth: 1,
borderOpacity: 1,
borderColor: '#FDFDFD',
popupTemplate: function(geography, data) { //this function should just return a string
return '<div class="hoverinfo"><strong>' + geography.properties.name + '</strong></div>';
},
popupOnHover: true, //disable the popup while hovering
highlightOnHover: true,
highlightFillColor: '#FC8D59',
highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
highlightBorderWidth: 2,
highlightBorderOpacity: 1
},
done: function(datamap) {
datamap.svg.selectAll('.datamaps-subunit').on('click', function(geography) {
console.log(geography);
var url = window.location.href;
var arr = url.split("/");
var result = arr[0] + "//" + arr[2]
window.open(result+'/countries/view/'+geography.properties.name);
});
}
});
</script>
It'll display all the countries. but i want to show few country.
How can I pass the country list over there?
I think with the help of custom.json or topojson. I don't know. Let me know if you have any solution or guidance.

Related

Highcharts Local CSV Issues

I am having issues creating my Highcharts graph out of my csv data. I have the following code that seems that it should work but it produces a blank graph on my server, I think it has something to do with the way that I'm pulling my data. I am using a ajax requests to pull from the csv file and plot the points. My csv is formatted like this.
0,0,0,12:45:37
5,26,130,12:45:37
1,28,28,12:45:42
4,35,140,12:45:47
1,32,32,12:45:52
3,16,48,12:45:57
1,29,29,12:46:02
1,25,25,12:46:07
5,16,80,12:46:12
4,35,140,12:46:17
5,25,125,12:46:22
4,37,148,12:46:27
With new points being added to the csv file every 30 seconds.
This is my code producing a blank graph.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Load cells data</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var t = [];
var Cell1 = [];
var Cell2 = [];
var Cell3 = [];
$.get('test.csv',function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var date = items[0].split('/');
Cell1.push([date, parseFloat(items[1])]);
Cell2.push([date, parseFloat(items[2])]);
Cell3.push([date, parseFloat(items[0])]);
});
var options = {
chart: {
zoomType: 'x',
renderTo: 'chart',
defaultSeriesType: 'line',
animation: Highcharts.svg,
events: {
load: requestData
}
},
title: {
text: 'Reading chart'
},
xAxis: {
title: {
text: 'Date'
},
type: 'datetime'
},
yAxis: {
title: {
text: 'kN'
}
},
series: [{
data: Cell1},{data: Cell2
}, {data: Cell3}],
//barra vertical que une puntos
tooltip: {
backgroundColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1,
x3: 0,
y3: 2
},
stops: [
[0, 'rgba(96, 96, 96, .8)'],
[1, 'rgba(16, 16, 16, .8)'],
[2, 'rgba(50, 50, 50, .8)']
]
},
borderWidth: 0,
style: {
color: '#FFF'
},
crosshairs: true,
shared: true
},
// quitar link Highcharts
credits: {
position: {
align: 'left',
verticalAlign: 'bottom',
x: 0,
y: -10
},
style: {
cursor: 'pointer',
fontSize: '20px',
color: 'rgba(0, 0, 0, 0)'
},
text: 'R E M t i m er.com',
href: 'http://Google.com'
},
// finn quitar link highcharts
};
var chart = new Highcharts.StockChart(options);
function requestData() {
$.ajax({
csv: '\\server\\test.csv',
success: function(csv) {
var items = csv.split(',');
var date = items[0].split('/');
Cell1 = parseFloat(items[1]),
Cell2 = parseFloat(items[2]),
Cell3 = parseFloat(items[3]),
point = [date, Cell1];
point2 = [date, Cell2];
point3 = [date, Cell3];
chart.series[0].addPoint(point);
chart.series[1].addPoint(point2)
chart.series[2].addPoint(point3)
// call it again after one second
setTimeout(requestData, 30000);
},
cache: false
});
}
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="chart" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Please help.
You need to put date as timestamp.
Since the csv date doesn't contain the day, I suggest put the current date (but check your requirements).
Try this (create a new date based on string in ISO 8601 format):
var date = new Date(new Date().toISOString().substr(0,10) + 'T' + items[3])

Highcharts load before the dialog has opened

I have a dynamic highchart that is shown in a dialog on a click event. I am close to where I want to be on this, with the exception of the following:
1: My chart has an event: load included, which means the chart is loaded before the click event. I want it to load on the click event. My first instinct was to place the highchart code in the onclick event, but that had unexpected impacts on the chart rendering itself. How can I have the chart load on the click event without impacting the chart behavior?
2: The left hand side of my chart does not disappear from the chart, as shown in the jsfiddle example from the highcharts website: http://jsfiddle.net/gh/get/jquery/3.1.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/dynamic-update/ and I do not see any difference between the example and my code that would impact this. How can I have my chart copy the example and have my points disappear on the left?
3: When my chart has reached the end of the data array, I want it to start over, but instead it seems to keep running without data, eventually flatlining. My dataset includes 3 arrays, each of 40 elements; apiData, calculatedData (both numbers), and apiDate (universal time values). How can I have the chart run a continuous loop on my data?
Example of my data:
var apiData = [75, 76, 89, 91, 86, 56, 46, 89, 87, 96];
var calculatedData = [78, 81, 98, 95, 89, 70, 59, 91, 90, 78];
var apiDate = [1482613200,1482624000,1482634800,1482645600,1482656400
,1482667200,1482678000,1482688800,1482699600,1482710400,1482721200];
These divs have the onClick event attached:
<div class="wrap">
<div class="left col-xs-4"
id="8d450007-9cbf-11e6-a7da-14109fd4bd8b">
</div>
<div class="center col-xs-4"
id="8d45001c-9cbf-11e6-a7da-14109fd4bd8b">
</div>
<div class="right col-xs-4"
id="8d450008-9cbf-11e6-a7da-14109fd4bd8b">
</div>
</div>
Dialog that contains the chart:
<!-- Div to hold the line chart -->
<div id="dialog" title="Basic dialog">
<div id="canvas" width="600" height="400"></div>
</div>
Dialog setup:
//Initialize the dialog and set options
var opt = {
autoOpen: false,
modal: true,
width: 660,
height:460,
title: 'Hourly Temperature'
};
var theDialog = $("#dialog").dialog(opt);
var divIdList = ["#8d45001c-9cbf-11e6-a7da-14109fd4bd8b", "#8d450007-9cbf-11e6-a7da-14109fd4bd8b", "#8d450008-9cbf-11e6-a7da-14109fd4bd8b"]
$(function () {
divIdList.forEach(function(id) {
$(id).click(function () {
theDialog.dialog('open');
});
})
});
Highchart code:
$(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
Highcharts.chart('canvas', {
chart: {
type: 'spline',
animation: Highcharts.svg,
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each 3 seconds
var series1 = this.series[0];
var series2 = this.series[1];
var seriesCount = 0;
setInterval(function () {
var x = (new Date(apiDate[seriesCount] * 1000)).getTime(),
y1 = apiData[seriesCount],
y2 = calculatedData[seriesCount];
series1.addPoint([x, y1], true, true);
series2.addPoint([x, y2], true, true);
seriesCount++;
}, 3000);
if (seriesCount > 10) {
char
}
}
}
},
title: {
text: 'Live data'
},
xAxis: {
title: {
text: 'Date/Time'
},
type: 'datetime',
tickPixelInterval: 150
},
yAxis: [{
title: {
text: 'Temperature'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
}
],
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 0);
}
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
series: [{
name: 'API Temperature data',
data: (function () {
// use api predicted data
var data = [],
time = (new Date(apiDate[0])).getTime(),
dataCount = 0,
i;
for (i = 0; i <= 40; i ++) {
data.push({
x: time,
y: apiData[dataCount]
});
}
return data;
}())
},
{
name: 'Calculated Temperature data',
data: (function () {
var data = [],
time = (new Date(apiDate[0])).getTime(),
dataCount = 0,
i;
for (i = 0; i <= 40; i ++) {
data.push({
x: time,
y: calculatedData[dataCount]
});
}
return data;
}())
}
]
});
});
I would really appreciate some help on this. Maybe it is really simple but I have been staring at it so long now, I'm driving myself crazy.

Load popup on hover data from json file for datamaps

The datamaps "Getting started" page has a section on customizing the text when a user hovers over a specific country. However, they do so by hard-coding that info:
<script>
var map = new Datamap({
element: document.getElementById('container'),
fills: {
HIGH: '#afafaf',
LOW: '#123456',
MEDIUM: 'blue',
UNKNOWN: 'rgb(0,0,0)',
defaultFill: 'green'
},
data: {
IRL: {
fillKey: 'LOW',
numberOfThings: 2002
},
USA: {
fillKey: 'MEDIUM',
numberOfThings: 10381
}
},
geographyConfig: {
popupTemplate: function(geo, data) {
return ['<div class="hoverinfo"><strong>',
'Number of things in ' + geo.properties.name,
': ' + data.numberOfThings,
'</strong></div>'].join('');
}
}
});
</script>
I would like to load that info from an external .json file so that I can update it easily. How can I do this? I've tried setting dataURL, but that expects a complete topojson file, which I don't need to update.
Any help greatly appreciated!
dataUrl at the root level can take a json or csv file, like this example here: http://bl.ocks.org/markmarkoh/11331459
var election = new Datamap({
scope: 'usa',
element: document.getElementById('container1'),
geographyConfig: {
popupTemplate: function(geo, data) {
return data && data.info && "<div class='hoverinfo'><strong>" + data.info + "</strong></div>";
},
highlightOnHover: false,
borderColor: '#444',
borderWidth: 0.5
},
dataUrl: 'data.json',
dataType: 'json',
data: {},
fills: {
'Visited': '#306596',
'neato': '#0fa0fa',
'Trouble': '#bada55',
defaultFill: '#dddddd'
}
});
While the resource at data.json looks like:
{
"NY": {"fillKey": "Visited", "anotherProperty": "Born here"},
"TX": {"fillKey": "Visited", "anotherProperty": "Live here"},
"CA": {"fillKey": "Visited", "anotherProperty": "Here while writing this code"}
}

Adding a highchart to a Leaflet Popup

I'm currently working on a project where the map I create displays all communities the akdatagateway tracks and when a marker is clicked a popup opens displaying a highchart of the population over time char along with some other data. I've gotten all markers to display and was able to get the desired data through the website's API. The problem lies in the generating the highchart in the popup. I cant figure out how to pass in or get the array to the onPopupOpen() to make the subsequent function calls.
Reverent Functions:
function addMarker(array){
for (i in array){
var communityData = array[i]
L.marker([array[i].latitude,array[i].longitude], {bounceOnAdd: true, bounceOnAddOptions: {duration: 250, height: 50}}).addTo(map).on('popupopen', onPopUpOpen)
.bindPopup('<p style="font-size:130%;"><b>'+ array[i].name +'</b></p><div id="container" style="min-width: 300px; height: 200px; margin: 0 auto"></div><p><br />PCE for Electricity: ' + pcePrice + '<br />EIA for Electricity: ' + eiaPrice + '</p>').addTo(community);
}
}
function getPopulationData(array){
var id = array.id
var years = ""
var populations = ""
var populationData = []
var community_pop = $.ajax({type: "GET", url: "/api/models/population/?community=" + id +"", async: false}).responseText
community_pop = JSON.parse(community_pop)
community_pop = community_pop.results
for ( i = 0; i < community_pop.length; i++){
years += "'" + community_pop[i].year + "',";
populations += community_pop[i].total_population +",";
}
populationData[0] = years
populationData[1] = populations
return populationData;
}
function onPopUpOpen (e) {
//some code to get the community id from popup to use the function.
// getPopulationData()
$('#container').highcharts({
chart: {
type: 'line'
},
title: {
text: 'Population Over Time'
},
subtitle: {
text: 'Source: AEDG'
},
xAxis: {
categories: [popData[0]]
},
yAxis: {
title: {
text: 'Population'
}
},
plotOptions: {
line: {
dataLabels: {
enabled: false
},
enableMouseTracking: true
}
},
series: [{
name: '',
data: [popData[1]]
}]
});
}
I've tested the functions on elements of the Community array and they do produce the correct data I just can't figure out how to make call them on the pop up and thus generate the highchart. Any commentary is appreciated!
Links to Reference info:
http://leafletjs.com/reference.html
http://www.highcharts.com/docs
It looks like your code should work, so without a full reproducible example, it's tough to troubleshoot. So, instead I'll offer a working example:
var popup = L.popup().setContent('<p style="font-size:130%;"><b>Some Name</b></p><div id="container" style="min-width: 300px; height: 200px; margin: 0 auto">Loading...</div>');
L.circle([51.49, -0.09], 500, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5
}).addTo(map).bindPopup(popup);
map.on('popupopen', function(e) {
$.ajax({
type: "GET",
url: "data.json"
})
.done(function(data) {
$('#container').highcharts({
chart: {height: 175, width: 295},
title: {text: ''},
series: data
});
});
});
map.on('popupclose', function(e){
$('#container').html("Loading...");
});
Also, I'd warn you not to make async: false calls. Not only is it deprecated, but it can make for a poor user experience and it's totally unnecessary here.
Complete code sample is runnable here.

Full Graphic(javascript flot plugin) to image(png)

i'm using the flot plugin for javascript to plot some graphics on a web software, it works perfectly..I can plot the graphic, export the data to an .xls file, save the graphic figure as a .png file(both you can choose the name of the file)
Anyway, it plot something like the image below..
How the plot shows in the web-site
but when I click the button to save it to .png, the image is the below..How the plot shows in the downloaded file
I need that the downloaded file includes the axis numbers(in the exemple 0,10,...,100 and the y-axis too)
how to?
the importants part of the code are below(... is for code that is not needed here):
function gerar_graficos(varArray, eixo_x, eixo_y) {
...
$.ajax({
type: "POST",
url: '{% url "micro:micro_graficos_calc" %}', // micro.views.micro_graficos_calc
data: JSON.stringify({
fibra:fibra, matriz:matriz, fibra_nome:fibra_nome, matriz_nome:matriz_nome,
abordagem:abordagem, varArray:varArray, eixo_x:eixo_x, eixo_y:eixo_y, vf:vf, sigma2:sig2
}),
success: function(response) {
var pan_buttons = $("#pan_buttons");
var zoom_buttons = $("#zoom_buttons");
var placeholder = $("#placeholder_grafico");
var data = response.curvas;
var nome_eixo_x = $('#id_select_eixo_x').select2('data').text;
var nome_eixo_y = $('#id_select_eixo_y').select2('data').text;
...
}
$("#flot-tooltip").hide();
...
var tick;
if($('#id_select_eixo_x').val() == 'angulo')
tick = [0, 30, 60, 90, 120, 150, 180]
else
tick = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
var plot = $.plot(placeholder, data, {
xaxis: {
//axisLabel: $('#id_select_eixo_x').select2('data').text,
axisLabel: nome_eixo_x,
axisLabelUseCanvas: true,
axisLabelPadding: 5,
min: response.min_x,
max: response.max_x,
panRange: [response.min_x, response.max_x],
ticks: tick,
},
yaxis: {
//axisLabel: $('#id_select_eixo_y').select2('data').text,
axisLabel: nome_eixo_y,
axisLabelUseCanvas: true,
axisLabelPadding: 5,
tickFormatter: tickFormatter_y,
min: response.min_y,
max: response.max_y,
panRange: [response.min_y, response.max_y],
},
series: {
lines: {
show: true
},
shadowSize: 0
},
grid: {
clickable: true,
},
legend: {
show: false,
//container: $('#legenda_grafico')
},
zoom: {
interactive: true,
},
pan: {
interactive: true
}
});
...
$('#salvarImagemGrafico').show();
$("#ImagemGrafico").on("click", function(){
var myCanvas = plot.getCanvas();
dialogNomeImagem(myCanvas);
});
...
function dialogNomeImagem(myCanvas){
bootbox.dialog( 'Digite o nome do arquivo(não necessário colocar .png no final): <br>\
<form><input class = "input-block-level" id = "dialogIMG" type = "text"/>Padrão: imagem.png</form>',
[
{
"label": "OK",
"class": "btn-primary primary",
"callback": function(){
var MIME_TYPE = "image/png";
var imgURL = myCanvas.toDataURL(MIME_TYPE);
var dlLink = document.createElement('a');
var nome;
if(!$("#dialogIMG").val())
nome = 'imagem';
else
nome = $("#dialogIMG").val();
dlLink.download = nome;
dlLink.href = imgURL;
dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
document.body.appendChild(dlLink);
dlLink.click();
document.body.removeChild(dlLink);
}
},
{
"label": "Cancelar",
"class": "btn-primary",
}
],
{
"header": "",
"onEspace": true,
} );
}
HTML:
<div id="divResultados">
<div id='buttons_grafico'>
<span id='pan_buttons'>
</span>
<span id='zoom_buttons'>
</span>
<span id='flot-tooltip'>
</span>
</div>
<div id='placeholder_grafico'></div>
<div id='legenda_grafico'></div>
...
<div id='salvarImagemGrafico'>
<input type="submit" id="ImagemGrafico" class="btn btn-primary" value="Salvar Imagem">
</div>
...
</div>
big post..I know, I'm sorry, but really hope that you guys can help me..
and yes, I've looked for other topics here and found some, but my problem is that I need to keep changing the name of the file and none of the codes worked for that..
Using the jquery.flot.canvas.js plugin you need canvas: true in your options. See this example and its source on the Flot page.

Categories

Resources