I want to create map that display USA state, when user click on state it will show that's state's cities. I'm using highchart - highcharts

I'm using highchart map, that displays the USA state and its counties, but I want to show all cities of the selected state and when someone clicks on the city map it will display pop up model
I want to display all cities of the selected state and when someone clicks on the city map it will display a pop-up model.
The code I'm using right now
<div id="container"></div>
<script>
const drilldown = async function (e) {
// console.log('hover key', e.point.drilldown)
if (!e.seriesOptions) {
const chart = this,
mapKey = `countries/us/${e.point.drilldown}-all`;
// Handle error, the timeout is cleared on success
let fail = setTimeout(() => {
if (!Highcharts.maps[mapKey]) {
chart.showLoading(`<i class="icon-frown"></i> Failed loading ${e.point.name}`);
fail = setTimeout(() => {
chart.hideLoading();
}, 1000);
}
}, 3000);
// Show the Font Awesome spinner
chart.showLoading('<i class="icon-spinner icon-spin icon-3x"></i>');
var topology = await
fetch(https://code.highcharts.com/mapdata/${mapKey}.topo.json)
.then(response => response.json());
// Load the drilldown map
// const topology = await fetch(`https://code.highcharts.com/mapdata/${mapKey}.topo.json`)
// .then(response => response.json());
const data = Highcharts.geojson(topology);
// Set a non-random bogus value
data.forEach((d, i) => {
d.value = i;
console.log('data',d)
});
// Apply the recommended map view if any
chart.mapView.update(
Highcharts.merge(
{ insets: undefined },
topology.objects.default['hc-recommended-mapview']
),
false
);
// Hide loading and add series
chart.hideLoading();
clearTimeout(fail);
chart.addSeriesAsDrilldown(e.point, {
name: e.point.name,
data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
}
};
// On drill up, reset to the top-level map view
const drillup = function (e) {
if (e.seriesOptions.custom && e.seriesOptions.custom.mapView) {
e.target.mapView.update(
Highcharts.merge(
{ insets: undefined },
e.seriesOptions.custom.mapView
),
false
);
}
};
(async () => {
const topology = await fetch(
'https://code.highcharts.com/mapdata/countries/us/us-all.topo.json'
).then(response => response.json());
const data = Highcharts.geojson(topology);
const mapView = topology.objects.default['hc-recommended-mapview'];
// Set drilldown pointers
data.forEach((d, i) => {
d.drilldown = d.properties['hc-key'];
d.value = i; // Non-random bogus data
});
// Instantiate the map
Highcharts.mapChart('container', {
chart: {
events: {
drilldown,
drillup,
thrilup
}
},
title: {
text: 'Highcharts Map Drilldown'
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapView,
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
series: [{
data,
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
},
custom: {
mapView
}
}],
drilldown: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'spacingBox',
position: {
x: 0,
y: 60
}
}
},
thrilup: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'spacingBox',
position: {
x: 0,
y: 60
}
}
}
});
})();

Related

Can I assign a different radius when click a pie slice using Highcharts?

I am using Highcharts it is working fine but i want to change in pie slice when i click on single pie slice then that slice overlap two slice(right or left slice).
Below is the image attached tha i have done in pie chart.
Below is the image attached of the expexted pie chart result
You can add your own method, which will resize shape on click, for example: http://jsfiddle.net/BlackLabel/8vd6cod1/
function resizeSlice(point, change) {
// Original shape params are stored in shapeArgs:
var shape = point.shapeArgs;
if (point.graphic) {
point.graphic.attr({
// "r" is outer radius:
r: shape.r + change,
// "innerR" is inner radius:
innerR: shape.innerR - change
});
}
}
// Build the chart
Highcharts.chart('container', {
chart: {
type: 'pie',
events: {
// On window resize, apply change:
redraw: function() {
Highcharts.each(this.series[0].points, function(point) {
resizeSlice(point, point.customResized ? 5 : 0)
});
}
}
},
plotOptions: {
pie: {
innerSize: '90%',
cursor: 'pointer',
dataLabels: {
enabled: false
},
point: {
events: {
click: function() {
var change = 0;
// Custom param, can be called whatever we want:
this.customResized = !this.customResized;
if (this.customResized) {
// Let's resize!
change = 5;
}
resizeSlice(this, change);
}
}
}
}
},
series: [{
data: [3, 4, 5, 6]
}]
});
I have make some change to this code for re size all other pie.
: http://jsfiddle.net/8vd6cod1/2/
function resizeSlice(point, change) {
// Original shape params are stored in shapeArgs:
var shape = point.shapeArgs;
if (point.graphic) {
point.graphic.attr({
// "r" is outer radius:
r: shape.r + change,
// "innerR" is inner radius:
innerR: shape.innerR - change
});
}
}
// Build the chart
Highcharts.chart('container', {
chart: {
type: 'pie',
events: {
// On window resize, apply change:
redraw: function() {
Highcharts.each(this.series[0].points, function(point) {
resizeSlice(point, point.customResized ? 5 : 0)
});
}
}
},
plotOptions: {
pie: {
innerSize: '90%',
cursor: 'pointer',
dataLabels: {
enabled: false
},
point: {
events: {
click: function() {
Highcharts.each(this.series.points, function(point) {
resizeSlice(point, 0)
});
var change = 0;
// Custom param, can be called whatever we want:
this.customResized = !this.customResized;
if (this.customResized) {
// Let's resize!
change = 5;
}
resizeSlice(this, change);
}
}
}
}
},
series: [{
data: [3, 4, 5, 6]
}]
});

Missing line on chart in popup

I wonder if anyone can see where I am going wrong. I am trying to get my line to appear on my chart in a popup. It works OK if I have the chart in a separate div but not in a popup. I am pulling data from Geoserver and I can see all the data fine. I am using leaflet and Highcharts.
Here is the relevant code.
var field_boundaries = L.tileLayer.wms("http://localhost:1997/geoserver/RSAC/wms", {
layers: 'RSAC:results_clipped_with_growth_small_new',
format: 'image/png',
transparent: true,
version: '1.1.0',
attribution: "myattribution"
});
//loads the geojson layer
var owsrootUrl = 'http://localhost:1997/geoserver/RSAC/wms';
var defaultParameters = {
service : 'WFS',
version : '1.1.0',
request : 'GetFeature',
typeName : 'RSAC:results_clipped_with_growth_small_new',
outputFormat : 'json',
format_options : 'callback:getJson',
SrsName : 'EPSG:4326'
};
var parameters = L.Util.extend(defaultParameters);
var URL = owsrootUrl + L.Util.getParamString(parameters);
var ajax = $.ajax({
url : URL,
dataType : 'json',
jsonpCallback : 'getJson',
success : function (response) {
new L.geoJson(response, {
onEachFeature: function (feature, url) {
// Create div with class name highchart
var div = L.DomUtil.create('div', 'highchart');
// Bind popup to layer with div as content
url.bindPopup(div);
// Handle event when popup opens
url.on('popupopen', function (e) {
console.log(e.target); // layer object
console.log(e.target.feature); // layer's feature object
console.log(e.popup); // popup object
console.log(e.popup.getContent()); // the div
$(".highchart").on('click', function onPopUpOpen(e){
$(".highchart")(e.popup.getContent(),{
chart: {
type: 'line',
renderTo: 'bindPopup'
},
title: {
text: 'Growth'
},
series: {
lineWidth:1,
colour: '#FF0000'
},
xAxis: {
allowDecimals: true,
categories: ['20151114', '20151126', '20151208', '20151220', '20160113', '20160125', '20160206', '20160218', '20160301', '20160313', '20160325', '20160406', '20160418', '20160430', '20160512', '20160524', '20160605', '20160629', '20160723', '20160804', '20160816'],
labels: {
formatter: function () {
return this.value;
}
}
},
yAxis: {
startOnTick: false,
minPadding: 0.05,
title: {
text: 'Crop Growth',
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name}{point.y}'
},
plotOptions: {
line: {
dataLabels: {
enabled: false
},
enableMouseTracking: true
}
},
series: [{
cursor: 'pointer',
color: '#4D4D4D',
lineWidth: 3,
name: 'Growth',
data: [parseFloat(feature.properties.Date_20151114),parseFloat(feature.properties.Date_20151126),parseFloat(feature.properties.Date_20151208), parseFloat(feature.properties.Date_20151220), parseFloat(feature.properties.Date_20160113), parseFloat(feature.properties.Date_20160125), parseFloat(feature.properties.Date_20160206), parseFloat(feature.properties.Date_20160218), parseFloat(feature.properties.Date_20160301), parseFloat(feature.properties.Date_20160313), parseFloat(feature.properties.Date_20160325), parseFloat(feature.properties.Date_20160406), parseFloat(feature.properties.Date_20160418), parseFloat(feature.properties.Date_20160430), parseFloat(feature.properties.Date_20160512), parseFloat(feature.properties.Date_20160524), parseFloat(feature.properties.Date_20160605), parseFloat(feature.properties.Date_20160629), parseFloat(feature.properties.Date_20160723), parseFloat(feature.properties.Date_20160804), parseFloat(feature.properties.Date_20160816)]
},
]
});
// Create the chart
//var chart = new Highcharts.Chart(options);
});
}).addTo(mymap);
}
});
}
});

How to display extra data in highcharts bubble chart tooltip with datetime x-axis

I am trying to display some more data in highcharts bubble chart tooltip with no success. How can I access this.point.comments inside the tooltip formatter?
The bubble chart I am using has datetime as x-axis.
$('#chart-bubble').highcharts({
chart: {
type: 'bubble',
zoomType: 'xy',
plotBorderWidth: 1
},
title: {
text: 'Risk & Profit Vs Date'
},
tooltip: {
useHTML: true,
formatter: function(){
var expectedProfit = '';
if( this.point.z !== 'none' )
{
expectedProfit = formatExpectedProfit(this.point.z);
}
var tooltip = '<table class="table table-bordered" style="width: 300px;"><tbody><tr><td colspan="2"><h5>'+this.series.name.substr(0,75)+'...</h5></td></tr>' +
'<tr><td>Risk:</td><td>'+this.y+'</td></tr>';
if( expectedProfit !== '' )
{
tooltip += '<tr><td>Profit:</td><td>'+expectedProfit+'</td></tr>';
}
else
{
tooltip += '<tr><td>Comments:</td><td>'+this.point.comments+'</td></tr>';
}
tooltip += '</tbody></table>';
return tooltip;
},
followPointer: false
},
rangeSelector: {
enabled:true
},
xAxis:{
type: 'datetime',
dateTimeLabelFormats: {
day: '%e of %b'
}
},
yAxis: {
title: {
text: 'Ri'
}
},
series: prepareData(res.bubble)
});
Here is the prepareData function:
function prepareData(data)
{
for( var i in data )
{
var item = data[i];
for( var k in item.data )
{
var itemData = item.data[k];
if( itemData[0] )
{
var split = itemData[0].split("-");
var y = split[0];
var m = split[1]-1;
var d = split[2];
itemData[0] = Date.UTC(y,m,d);
item.data[k] = itemData;
}
}
data[i] = item;
}
return data;
}
And the res.bubble json returned from PHP:
$list = array();
$list[] = array('name'=>'project 1','color'=>'#FF0000','data'=>array(new \DateTime(),20,'none'),'pointInterval'=>86400000,'comments'=>'this is a comment');
//.... repeating by adding some more elements to this array
You can access all additional properties via point.options[/* property */.
Highcharts.chart('container', {
chart: {
type: 'bubble',
},
tooltip: {
formatter: function () {
return this.point.options.comments[0];
}
},
series: [{
data: [
{ x: 95, y: 95, z: 13.8, name: 'BE', comments: ['this is a comment'] },
]
}]
});
example: http://jsfiddle.net/yd1vjfmp/

Highcharts pie graph with two rings filtering

I have a pie chart here that I'm working on that has two "rings" in it. The inner ring is just a summation of the outer ring for that given category.
Here is the fiddle: http://jsfiddle.net/jeffvan576/a50859s7/1/
(Apologies for the code - it's a bit of a mess right now)
I've been messing around with the showInLegend functionality but that will (as it's intended) only pull out the given piece of the pie chart. So, for instance, if you click google, it pulls out that piece of the pie chart but leaves the outer ring. To completely eliminate google you need to click "google", "match", "funds added" and "organic" for google.
My question is, is there a way to remove the entire slice (google and all it's children) from the chart at once?
The issue is that in order to get the functionality / layout on the chart that I need, this pie chart is actually built out of two series.
ShowInLegend code:
pie: {
shadow: false,
center: ['50%', '50%'],
showInLegend: true
}
I started building a custom visibility function at the bottom of the fiddle but dialed it back until I understood showInLegend a little better.
Thanks in advance!
you can achieve this by getting name of series on which clicked by using http://api.highcharts.com/highcharts#plotOptions.pie.events.click of plotoptions -> pie.
after that calling visibility function to hide Channel series along with its children to hide/show.
Event:
plotOptions: {
pie: {
shadow: false,
center: ['50%', '50%'],
showInLegend: true,
point: {
events: {
}
}
}
}
also static line put into visibility function to hide/show need to remove.
// chart.series[0].data[0].visible = false;
http://jsfiddle.net/a50859s7/27/
Full code:
$(function () {
var dataObject = {
facebook: {
'organic': 10.85,
'match': 7.35,
'fundsadded': 33.06,
'total': 0,
'status': 'disabled'
},
google: {
'organic': 10.85,
'match': 7.35,
'fundsadded': 33.06,
'total': 0,
'status': 'disabled'
},
email: {
'organic': 10.85,
'match': 7.35,
'fundsadded': 33.06,
'total': 0,
'status': 'enabled'
},
colorSelections: {
'facebook': '#3b5998',
'google': '#dd4b39',
'disabled': '#c6c6c6'
}
}
var sumObjects = function () {
for (var channel in dataObject) {
if (channel === 'colorSelections') continue;
var sum = 0;
for (var key in dataObject[channel]) {
if (key === 'status') continue;
sum += dataObject[channel][key];
}
dataObject[channel].total = sum;
}
}
sumObjects();
var colors = Highcharts.getOptions().colors,
categories = ['Facebook', 'Google', 'Email'],
data = [{
y: dataObject.facebook.total + 1,
//color: dataObject.facebook.status === 'disabled' ? dataObject.colorSelections.disabled : dataObject.colorSelections.facebook,
color: 'rgba(59, 89, 152, 0.3)',
drilldown: {
name: 'Facebook',
categories: ['organic', 'match', 'funds added'],
data: [
dataObject.facebook.organic,
dataObject.facebook.match,
dataObject.facebook.fundsadded],
color: 'rgba(59, 89, 152, 0.3)'
},
}, {
y: dataObject.google.total + 1,
color: '#dd4b39',
drilldown: {
name: 'Google',
categories: ['organic', 'match', 'funds added'],
data: [
dataObject.google.organic,
dataObject.google.match,
dataObject.google.fundsadded],
color: '#e46f61'
}
}, {
y: dataObject.email.total + 1,
color: colors[2],
drilldown: {
name: 'Email',
categories: ['organic', 'match', 'funds added'],
data: [
dataObject.email.organic,
dataObject.email.match,
dataObject.email.fundsadded],
color: colors[2]
}
}],
browserData = [],
versionsData = [],
i,
j,
dataLen = data.length,
drillDataLen,
brightness;
// Build the data arrays
for (i = 0; i < dataLen; i += 1) {
// add browser data
browserData.push({
name: categories[i],
y: data[i].y,
color: data[i].color
});
// add version data
drillDataLen = data[i].drilldown.data.length;
for (j = 0; j < drillDataLen; j += 1) {
brightness = 0.2 - (j / drillDataLen) / 5;
versionsData.push({
name: data[i].drilldown.categories[j],
y: ((data[i].drilldown.data[j] / browserData[0].y) * 100),
color: Highcharts.Color(data[i].color).brighten(brightness).get()
});
}
}
// Create the chart
$('#container').highcharts({
chart: {
type: 'pie'
},
title: {
text: 'Browser market share, April, 2011'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
plotOptions: {
pie: {
shadow: false,
center: ['50%', '50%'],
showInLegend: true,
point: {
events: {
click: function (event) {
var seriesIndex;
var secondarySeriesIndex;
if (this.name == 'Facebook') {
seriesIndex = 0;
secondarySeriesIndex = 0;
} else if (this.name == 'Google') {
seriesIndex = 1;
secondarySeriesIndex = 3;
} else if (this.name == 'Email') {
seriesIndex = 2;
secondarySeriesIndex = 6;
}
var chart = $('#container').highcharts();
visibility(chart.series[0].data[seriesIndex]);
visibility(chart.series[1].data[secondarySeriesIndex]);
visibility(chart.series[1].data[secondarySeriesIndex + 1]);
visibility(chart.series[1].data[secondarySeriesIndex + 2]);
}
}
}
}
},
tooltip: {
valueSuffix: '%'
},
series: [{
name: 'Channel',
type: 'pie',
data: browserData,
size: '120%',
dataLabels: {
formatter: function () {
return this.y > 5 ? this.point.name : null;
},
color: 'white',
distance: -30
}
}, {
name: 'Added',
type: 'pie',
data: versionsData,
size: '120%',
innerSize: '80%',
dataLabels: {
formatter: function () {
// display only if larger than 1
return this.y > 1 ? '<b>' + this.point.name + ':</b> ' + this.y + '%' : null;
}
}
}]
});
var visibility = function (series) {
series.visible ? series.graphic.hide() : series.graphic.show();
// chart.series[0].data[0].visible = false;
}
var chart = $('#container').highcharts();
$('.update').click(function () {
visibility(chart.series[0].data[0]);
visibility(chart.series[1].data[0]);
visibility(chart.series[1].data[1]);
visibility(chart.series[1].data[2]);
chart.redraw();
});
function synchronizePieSeries(event, slice) {
debugger;
$(chart.series[1].data).each(function (i, e) {
if (slice.name === e.name) {
slice.visible ? e.graphic.hide() : e.graphic.show();
}
});
}
//$('.update').click(function (event) {
// synchronizePieSeries(event, this);
//});
});

highchart autoupdate(addpoint) cause corrupted chart view

Im using multiple highchart chart inside my page and i use addpoint function to update the chart.
the problem is after some time the chart will be compressed into less than a half of original chart size.
i captured my screen which could be found here for make the problem clear:
http://www.screenr.com/f3E7
sample chart generation code:
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
//var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'ch_trafficio',
type: 'spline',
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
var series1= this.series[1];
}
}
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
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, 2);
}
},
plotOptions : {
area : {
lineWidth : 1,
marker : {
enabled : false,
states : {
hover : {
enabled : true,
radius : 5
}
}
},
shadow : false,
states : {
hover : {
lineWidth : 1
}
}
}
},
legend: {
enabled: true
},
exporting: {
enabled: true
},
series: [{
name: 'InBound',
type : "area",
color: '#89A54E',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -119; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
},{
name: 'OutBound',
type : "area",
color: '#AA4643',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -119; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}
]
});
chart update functions:
chart.series[0].addPoint([x,data.oid1], false, true);
chart.series[1].addPoint([x,data.oid2], true, true);
chart1.series[0].addPoint([x,data.oid5], true, true);
chart2.series[0].addPoint([x,data.oid3], false, true);
chart2.series[1].addPoint([x,data.oid4], true, true);
chart3.series[0].addPoint([x,data.oid7], true, true);
thanks in advance
you need to add a shifting parameter for your points to shift over the chart
var series = chart.series[0],
shift = series.data.length > 100; // shift if the series is longer than 100
and to change adding point like below
chart.series[0].addPoint([x,data.oid1], true, shift);
example here

Resources