JQVMap - How to show data values onregionclick - javascript

var setMap = function (name) {
var data = {
map: 'world_en',
backgroundColor: null,
borderColor: '#333333',
borderOpacity: 0.5,
borderWidth: 1,
color: '#c6c6c6',
enableZoom: true,
hoverColor: '#c9dfaf',
hoverOpacity: null,
values: sample_data,
normalizeFunction: 'linear',
scaleColors: ['#b6da93', '#909cae'],
selectedColor: '#c9dfaf',
selectedRegion: null,
showTooltip: true,
onLabelShow: function (event, label, code) {
},
onRegionOver: function (event, code) {
if (code == 'ca') {
event.preventDefault();
}
},
onRegionClick: function (element, code, region) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert(message);
}
};
data.map = name + '_en';
var map = jQuery('#vmap_' + name);
map.width(map.parent().parent().width());
map.show();
map.vectorMap(data);
map.hide();
}
Anyone knows how to use the values of the clicked region in the onRegionClick function?
I use this map to provide website statistics and want to alert on click something like "1000 Views in US (United States)"

As i said in my comment, i found out the solution right after i asked the question, but for those who have this little problem, too i just post my solution.
You just have to append the string you want to display to the label.
onLabelShow: function (event, label, code) {
if(sample_data[code] > 0)
label.append(': '+sample_data[code]+' Views');
}
hope it helps.

Related

Javascript force insert string into JS object (JSON) leaflet vectortiles

I am using leaflet mapping library
for styling purposes this code works for the data_oh.parcel layer if I hardcode the layer name like this
var vectorTileOptions = {
interactive: true,
vectorTileLayerStyles: {
'data_oh.parcel': {
fillColor: "yellow",
fill: true,
color: "red"
}
}
};
However as I am going to be adding multiple layers I need to add that layer name as a variable so I have something like this
var layers={parcels: ["#Parcels","http://localhost:7800/data_oh.parcel/{z}/{x}/{y}.pbf",'#ffe4c4','data_oh.parcel'],
footpring: ["#Footprints","http://localhost:7800/data_oh.footprint/{z}/{x}/{y}.pbf",'#8b8878','data_oh.footprint']
};
var idArray = [];
var layerArray = [];
function legend_click(id, layer_api, color_layer,layer_name) {
$(id).click(function () {
var layer_add;
var i = idArray.indexOf(id);
if (i < 0) {
layer_add = L.vectorGrid.protobuf(layer_api, {
interactive: true,
rendererFactory: L.svg.tile,
vectorTileLayerStyles: {
layer_name: {
fillColor: "yellow",fill: true, color: "red"
}
}
})
layerArray.push(layer_add);
idArray.push(id);
}
else {
layer_add = layerArray[i];
};
if ($(id).prop('checked') == true) {
layer_add.addTo(map);
}
else if ($(id).prop('checked') == false) {
map.removeLayer(layer_add);
}
})
};
for (var key in layers){
legend_click(layers[key][0],layers[key][1],layers[key][2],layers[key][3])
};
In the legend_click function the 4th input is for that layer name but the color is not changing on the map, this means the 4th input is not being recognized correctly in the vectorTileLayerStyles portion of the code. Again if I hardcode the values it works but passing through on a variable holding a string it does not.
You can use computed property names inside legend_click:
vectorTileLayerStyles: {
[`${layer_name}`]: {
fillColor: "yellow",fill: true, color: "red"
}
}
so if that did not work this should work:
vectorTileLayerStyles: Object.fromEntries([[layer_name,{fillColor: "yellow", fill: true, color: "red"}]])

Custom Map in Datamaps

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.

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"}
}

how to add click event to angular js directive for plotting flot bar chart

I am pretty new to angularjs and flot charts. I am trying to add click events to my stacked bar charts so that once I click a stack it displays the categories information but I am not sure if am doing it right.
Please help take a look
I already plot my chart in angularjs directive
see http://jsfiddle.net/6h1gL2sh/10/ here
App.directive('chart', function () {
return {
restrict: 'EA',
link: function (scope, elem, attrs) {
var chart = null,
options = {
series: {
stack: true,
bars: {
show: true,
clickable: true,
barWidth: 0.1,
align: "center"
}
},
axisLabels: {
show: true
},
xaxis: {
axisLabel: 'Products',
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelPadding: 5,
mode: "categories",
tickLength: 0
},
yaxis: {
axisLabel: 'Pass/Fail Count',
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelPadding: 5
},
grid: {
hoverable: true,
clickable: true
}
}
var data = scope[attrs.ngModel];
scope.$watch(attrs.ngModel, function (v) {
if (!chart) {
chart = $.plot(elem, v, options);
elem.show();
} else {
chart.setData(v);
chart.setupGrid();
chart.draw();
}
});
$(elem).bind("plotclick", function (event, pos, item) {
scope.$apply(function () {
if (item) {
scope.dis = item.series.xaxis.categories[item.dataIndex].label
}
});
});
}
};
});
Since you're trying to get an object's Key by value, you can't really access it as an array using bracket notation. I used a function that can be found on this SO question: JavaScript object get key by value
Then, I simply changed your click part to this:
elem.bind("plotclick", function (event, pos, item) {
if(item){
scope.dis= getKeyByValue(item.series.xaxis.categories, item.dataIndex);
scope.$apply();
}
});
Fiddle

How to display a popup with data of a data point in Flot graph?

I got the Flot-created graph. What I wanted to acomplish is to get some kind of information when user moves the mouse over it - best would be to show the data (from x and y axis) in some kind of javascript popup.
It's probably trivial question, but I can't figure it out...
Right now my javascript looks like this:
<script id="source" language="javascript" type="text/javascript">
$(function () {
var data = [[1251756000000, 122.68],[1251842400000, 122.68],[1251928800000, 125.13],[1252015200000, 112.62],[1252101600000, 122.76]]
$.plot($("#graph_placeholder"), [ data ], {
xaxis: { mode: "time", minTickSize: [1, "day"], timeformat : "%y/%m/%d", },
lines: { show: true },
points: { show: false },
} );
});
</script>
So best would be to get the x: 1251756000000 y: 122.68 when hovering the point (x: 1251756000000, y: any). Or even have the x value formatted as defined in the timeformat (2009/11/14).
This example shows how to enable a tooltip (if you click the Enable Tooltip checkbox). Here's a starting point using your example code:
<script id="source" language="javascript" type="text/javascript">
$(function () {
var data = [[1251756000000, 122.68],[1251842400000, 122.68],[1251928800000, 125.13],[1252015200000, 112.62],[1252101600000, 122.76]]
$.plot($("#graph_placeholder"), [ data ], {
xaxis: { mode: "time", minTickSize: [1, "day"], timeformat : "%y/%m/%d", },
lines: { show: true },
points: { show: true },
grid: { hoverable: true },
} );
});
var previousPoint = null;
$("#graph_placeholder").bind("plothover", function (event, pos, item) {
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip").remove();
showTooltip(item.pageX, item.pageY, '(' + item.datapoint[0] + ', ' + item.datapoint[1]+')');
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
border: '1px solid #fdd',
padding: '2px',
'background-color': '#fee',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
</script>

Categories

Resources