transcend-charts
Version:
Transcend is a charting and graph library for NUVI
959 lines (835 loc) • 36.3 kB
JavaScript
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
var _Charts = require('../helpers/Charts');
var _Charts2 = _interopRequireDefault(_Charts);
var _Numbers = require('../helpers/Numbers');
var _Numbers2 = _interopRequireDefault(_Numbers);
var _Color = require('./Color');
var _Color2 = _interopRequireDefault(_Color);
var _Geometry = require('./Geometry');
var _Geometry2 = _interopRequireDefault(_Geometry);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var PieMap = function PieMap(htmlContainer, mapData, mapOptions, mapBoundaries) {
var self = this;
var htmlCanvas = null;
var options = mapOptions;
if (!options.backgroundColor) {
options.backgroundColor = new _Color2.default.Color('transparent');
} else {
options.backgroundColor = new _Color2.default.Color(options.backgroundColor);
}
if (!options.borderColor) {
options.borderColor = new _Color2.default.Color('#00ffff');
} else {
options.borderColor = new _Color2.default.Color(options.borderColor);
}
if (!options.zeroFillColor) {
options.zeroFillColor = new _Color2.default.Color(options.backgroundColor);
} else {
options.zeroFillColor = new _Color2.default.Color(options.zeroFillColor);
}
if (!options.highlightFillColor) {
options.highlightFillColor = 'none';
} else {
options.highlightFillColor = new _Color2.default.Color(options.highlightFillColor);
}
if (!options.mapFillColor) {
options.mapFillColor = new _Color2.default.Color('#000000');
} else {
options.mapFillColor = new _Color2.default.Color(options.mapFillColor);
}
// stripes
if (!options.stripeWidth) {
options.stripeWidth = 0;
} else {
options.stripeWidth = parseFloat(options.stripeWidth);
}
if (!options.stripeSpacing) {
options.stripeSpacing = 10;
} else {
options.stripeSpacing = parseFloat(options.stripeSpacing);
}
if (!options.stripeColor) {
options.stripeColor = new _Color2.default.Color('#ffffff');
} else {
options.stripeColor = new _Color2.default.Color(options.stripeColor);
}
// mouse controls
if (options.allowZoomAndPan === undefined || options.allowZoomAndPan === null || options.allowZoomAndPan === true) {
options.allowZoomAndPan = true;
} else {
options.allowZoomAndPan = false;
}
// values
if (!options.valueFontColor) {
options.valueFontColor = new _Color2.default.Color('#444444');
} else {
options.valueFontColor = new _Color2.default.Color(options.valueFontColor);
}
if (!options.valueFontFamily) {
options.valueFontFamily = 'Arial';
}
if (!options.valueFontWeight) {
options.valueFontWeight = '400';
}
if (!options.valueFontSize) {
options.valueFontSize = null;
options.valueFontSizeAsPct = 0.08;
} else if (typeof options.valueFontSize === 'string' && options.valueFontSize.indexOf('%') !== -1) {
options.valueFontSizeAsPct = parseFloat(options.valueFontSize) / 100;
} else {
options.valueFontSize = parseFloat(options.valueFontSize);
}
if (options.showValues === false) {
options.showValues = false;
} else {
options.showValues = true;
}
var data = null;
var pxRatio = window.devicePixelRatio || 1;
var backingStoreRatio = 1;
var canvasWidth = 0;
var canvasHeight = 0;
var needsRender = false;
var DEBUG = false;
var fullScreenChangeListener;
var webkitFullScreenChangeListener;
var mozFullScreenChangeListener;
var msFullScreenChangeListener;
var resizeListener;
var isDestroyed = false;
var resizeTimer = null;
var countryOutlines = mapBoundaries['110m'];
if (!countryOutlines) countryOutlines = mapBoundaries['50m'];
var minViewport = {
minLng: -180,
maxLng: 180,
minLat: -70,
maxLat: 90
};
if (mapBoundaries.minViewport) {
minViewport = {
minLng: mapBoundaries.minViewport.minLng,
maxLng: mapBoundaries.minViewport.maxLng,
minLat: mapBoundaries.minViewport.minLat,
maxLat: mapBoundaries.minViewport.maxLat
};
}
var viewport = {
minLng: minViewport.minLng,
maxLng: minViewport.maxLng,
minLat: minViewport.minLat,
maxLat: minViewport.maxLat
};
var mapRatio = 2.25;
if (mapBoundaries.mapRatio) mapRatio = mapBoundaries.mapRatio;
var maxScale = 0.1;
this.render = function () {
//console.log('map start: ' + new Date().getTime());
// If there's no HTML canvas made something went horribly wrong. Abort!
if (!htmlCanvas) return;
// Get the context of the canvas
var ctx = htmlCanvas.getContext('2d');
// upscale this thang if the device pixel ratio is higher than 1
ctx.save();
if (pxRatio > 1) ctx.scale(pxRatio / backingStoreRatio, pxRatio / backingStoreRatio);
// clear the background, ready to re-render
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
if (options.backgroundColor.toString() !== 'transparent') {
ctx.fillStyle = options.backgroundColor.toString();
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
}
// calculate the ratio between lat/lng and px
var lngperpx = (viewport.maxLng - viewport.minLng) / canvasWidth;
var latperpx = (viewport.maxLat - viewport.minLat) / canvasHeight;
// iterate over features and draw the outlines of all of them
ctx.lineWidth = 1;
ctx.strokeStyle = options.borderColor.toString();
ctx.fillStyle = options.mapFillColor.toString();
for (var i = 0; i < countryOutlines.features.length; i++) {
if (countryOutlines.features[i].bbox[0] > viewport.maxLng || countryOutlines.features[i].bbox[2] < viewport.minLng || countryOutlines.features[i].bbox[1] > viewport.maxLat || countryOutlines.features[i].bbox[3] < viewport.minLat) {
continue;
}
if ((countryOutlines.features[i].bbox[2] - countryOutlines.features[i].bbox[0]) / lngperpx < 4 && (countryOutlines.features[i].bbox[3] - countryOutlines.features[i].bbox[1]) / latperpx < 4) {
continue;
}
// if multipolygon
if (countryOutlines.features[i].geometry.type === 'MultiPolygon') {
for (var j = 0; j < countryOutlines.features[i].geometry.coordinates.length; j++) {
ctx.beginPath();
for (var k = 0; k < countryOutlines.features[i].geometry.coordinates[j].length; k++) {
var lastPt = undefined;
for (var l = 0; l < countryOutlines.features[i].geometry.coordinates[j][k].length; l++) {
var lng = countryOutlines.features[i].geometry.coordinates[j][k][l][0];
var lat = countryOutlines.features[i].geometry.coordinates[j][k][l][1];
var x = (lng - viewport.minLng) / lngperpx;
var y = canvasHeight - (lat - viewport.minLat) / latperpx; // invert this sucker
if (lastPt !== undefined && lastPt.x === Math.round(x) && lastPt.y === Math.round(y)) continue;
if (l === 0) ctx.moveTo(x, y);else ctx.lineTo(x, y);
lastPt = { x: Math.round(x), y: Math.round(y) };
}
ctx.closePath();
}
ctx.fill();
ctx.stroke();
}
}
// if polygon
else if (countryOutlines.features[i].geometry.type === 'Polygon') {
for (var j = 0; j < countryOutlines.features[i].geometry.coordinates.length; j++) {
ctx.beginPath();
var lastPt = undefined;
for (var k = 0; k < countryOutlines.features[i].geometry.coordinates[j].length; k++) {
var lng = countryOutlines.features[i].geometry.coordinates[j][k][0];
var lat = countryOutlines.features[i].geometry.coordinates[j][k][1];
var x = (lng - viewport.minLng) / lngperpx;
var y = canvasHeight - (lat - viewport.minLat) / latperpx; // invert this sucker
if (lastPt !== undefined && lastPt.x === Math.round(x) && lastPt.y === Math.round(y)) continue;
if (k === 0) ctx.moveTo(x, y);else ctx.lineTo(x, y);
lastPt = { x: Math.round(x), y: Math.round(y) };
}
ctx.closePath();
ctx.fill();
ctx.stroke();
}
}
}
// determine now whether something is highlighted or not
var somethingIsHighlighted = data.some(function (datum) {
return datum.segments.some(function (segment) {
return segment.isHighlighted;
});
});
// render the circles
var movingRadian = -Math.PI / 2;
for (var a = 0; a < data.length; a++) {
if (data[a].lat !== undefined && data[a].lng !== undefined && data[a].radius) {
var lng = data[a].lng;
var lat = data[a].lat;
var pieRadius = data[a].radius;
var x = (lng - viewport.minLng) / lngperpx;
var y = canvasHeight - (lat - viewport.minLat) / latperpx; // invert this sucker
var pieCenter = { x: x, y: y };
for (var s = 0; s < data[a].segments.length; s++) {
var percent = data[a].segments[s].value / data[a].value;
var fillColor = new _Color2.default.Color(data[a].segments[s].fillColor).fade(0.2);
if (somethingIsHighlighted && !data[a].segments[s].isHighlighted) {
fillColor.fade(0.7);
}
ctx.fillStyle = fillColor.toString();
var strokeColor = new _Color2.default.Color(data[a].segments[s].borderColor).fade(0.2);
ctx.strokeStyle = strokeColor.toString();
ctx.lineWidth = options.borderWidth;
ctx.beginPath();
ctx.moveTo(pieCenter.x, pieCenter.y);
ctx.lineTo(pieCenter.x + Math.cos(movingRadian) * pieRadius, pieCenter.y + Math.sin(movingRadian) * pieRadius);
ctx.arc(pieCenter.x, pieCenter.y, pieRadius, movingRadian, movingRadian + percent * Math.PI * 2);
ctx.lineTo(pieCenter.x, pieCenter.y);
ctx.fill();
if (percent < 1) {
ctx.stroke();
}
if (options.stripeWidth && (!somethingIsHighlighted || data[a].segments[s].isHighlighted)) {
ctx.save();
ctx.clip();
ctx.lineWidth = options.stripeWidth;
ctx.strokeStyle = options.stripeColor.toString();
ctx.beginPath();
for (var x = pieCenter.x - pieRadius - pieRadius * 2; x < pieCenter.x + pieRadius; x += options.stripeSpacing) {
ctx.moveTo(x, pieCenter.y + pieRadius);
ctx.lineTo(x + pieRadius * 2, pieCenter.y - pieRadius);
}
ctx.stroke();
ctx.restore();
}
movingRadian += percent * Math.PI * 2;
}
}
var pie_x = (data[a].lng - viewport.minLng) / lngperpx;
var pie_y = canvasHeight - (data[a].lat - viewport.minLat) / latperpx; // invert this sucker
// show value for highlighted circle (if any)
for (var s = 0; s < data[a].segments.length; s++) {
if (data[a].segments[s].isHighlighted) {
ctx.fillStyle = options.valueFontColor.toString();
var displayValue = data[a].segments[s].prefix + data[a].segments[s].value + data[a].segments[s].suffix;
if (data[a].segments[s].displayValue) {
displayValue = data[a].segments[s].displayValue;
}
if (options.valueFontSizeAsPct) {
options.valueFontSize = options.valueFontSizeAsPct * canvasHeight;
}
var labelFontSize = options.valueFontSize * 0.5;
var totalLabelHeight = options.valueFontSize + labelFontSize;
var valueTop = pie_y + data[a].radius + 2;
if (valueTop + totalLabelHeight > canvasHeight - options.padding) {
valueTop = canvasHeight - options.padding - totalLabelHeight;
}
ctx.textBaseline = 'top';
ctx.textAlign = 'center';
// label
ctx.font = '300 ' + labelFontSize + 'px ' + options.valueFontFamily;
ctx.fillText(data[a].segments[s].name, pie_x, valueTop);
// value
ctx.font = options.valueFontWeight + ' ' + options.valueFontSize + 'px ' + options.valueFontFamily;
ctx.fillText(displayValue, pie_x, valueTop + labelFontSize);
// whole pie label
var labelBottom = pie_y - data[a].radius - 2;
if (labelBottom - labelFontSize < options.padding) {
labelBottom = options.padding + labelFontSize;
}
ctx.textBaseline = 'bottom';
ctx.font = '300 ' + labelFontSize + 'px ' + options.valueFontFamily;
ctx.fillText(data[a].name, pie_x, labelBottom);
}
}
}
// draw fps
if (DEBUG) {
ctx.fillStyle = '#666666';
ctx.fillRect(canvasWidth - 40, canvasHeight - 15, 40, 15);
ctx.textAlign = 'right';
ctx.textBaseline = 'bottom';
ctx.fillStyle = '#000000';
ctx.font = '11px sans-serif';
ctx.fillText(String(Math.round(fps)) + ' fps', canvasWidth - 5, canvasHeight - 1);
}
ctx.restore();
//console.log('map end: ' + new Date().getTime());
};
function getCentroidByISO(iso_a2) {
for (var i = 0; i < countryOutlines.features.length; i++) {
if (countryOutlines.features[i].properties.iso_a2 === iso_a2) {
if (countryOutlines.features[i].centroid) {
return {
lng: countryOutlines.features[i].centroid[0],
lat: countryOutlines.features[i].centroid[1]
};
} else if (countryOutlines.features[i].bbox) {
return {
lng: (countryOutlines.features[i].bbox[0] + countryOutlines.features[i].bbox[2]) / 2,
lat: (countryOutlines.features[i].bbox[1] + countryOutlines.features[i].bbox[3]) / 2
};
}
}
}
return null;
}
function containViewport() {
// if we're too zoomed out to make the map fill the canvas, let's just fill the canvas
if (viewport.maxLng - viewport.minLng > minViewport.maxLng - minViewport.minLng || viewport.maxLat - viewport.minLat > minViewport.maxLat - minViewport.minLat) {
// determine whether the lng or lat will fill the mapSize
var canvasRatio = htmlCanvas.width / htmlCanvas.height;
var lngspan = 0;
var latspan = 0;
if (canvasRatio > mapRatio) {
latspan = minViewport.maxLat - minViewport.minLat;
lngspan = latspan * canvasRatio;
} else {
lngspan = minViewport.maxLng - minViewport.minLng;
latspan = lngspan / canvasRatio;
}
viewport = {
minLat: (minViewport.maxLat + minViewport.minLat) / 2 - latspan / 2,
maxLat: (minViewport.maxLat + minViewport.minLat) / 2 + latspan / 2,
minLng: (minViewport.maxLng + minViewport.minLng) / 2 - lngspan / 2,
maxLng: (minViewport.maxLng + minViewport.minLng) / 2 + lngspan / 2
};
} else {
// prevent zooming out or in to space on the outside of the map's minViewport
if (viewport.minLng < minViewport.minLng) {
var diff = minViewport.minLng - viewport.minLng;
viewport.minLng += diff;
viewport.maxLng += diff;
}
if (viewport.maxLng > minViewport.maxLng) {
var diff = viewport.maxLng - minViewport.maxLng;
viewport.minLng -= diff;
viewport.maxLng -= diff;
}
if (viewport.minLat < minViewport.minLat) {
var diff = minViewport.minLat - viewport.minLat;
viewport.minLat += diff;
viewport.maxLat += diff;
}
if (viewport.maxLat > minViewport.maxLat) {
var diff = viewport.maxLat - minViewport.maxLat;
viewport.minLat -= diff;
viewport.maxLat -= diff;
}
}
}
/***
* Handles mouse scrolling on the map's canvas
***/
function handleScroll(e) {
var delta = e.wheelDelta ? e.wheelDelta : e.detail;
var ctx = htmlCanvas.getContext('2d');
backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
canvasWidth = htmlCanvas.width / (pxRatio / backingStoreRatio);
canvasHeight = htmlCanvas.height / (pxRatio / backingStoreRatio);
var rect = htmlCanvas.getBoundingClientRect();
var pt = {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
var canvasRatio = htmlCanvas.width / htmlCanvas.height;
// get lng span in viewport
var lngspan = viewport.maxLng - viewport.minLng;
var latspan = viewport.maxLat - viewport.minLat;
// get lat/lng of mouse pt
var mouseLatLng = {
lng: viewport.minLng + pt.x / canvasWidth * lngspan,
lat: viewport.maxLat - pt.y / canvasHeight * latspan // upside-down y axis
};
// weight new span toward mouse x,y
var relativePt = {
x: pt.x / canvasWidth,
y: pt.y / canvasHeight
};
var newlngspan = lngspan;
var newlatspan = latspan;
// zoom in
if (delta > 0) {
newlngspan = lngspan * 0.92; // why do we zoom in 92%? because it feels right
newlatspan = newlngspan / canvasRatio;
}
// zoom out
else if (delta < 0) {
newlngspan = lngspan * 1.07; // why do we zoom out 107%? because it's the recipericol of 92%.
newlatspan = newlngspan / canvasRatio;
}
// if the new viewport is going to be more zoomed out than minViewport, let's just set the map to fill the canvas
if (newlngspan >= minViewport.maxLng - minViewport.minLng && newlatspan >= minViewport.maxLat - minViewport.minLat) {
if (canvasRatio > mapRatio) {
newlatspan = minViewport.maxLat - minViewport.minLat;
newlngspan = newlatspan * canvasRatio;
} else {
newlngspan = minViewport.maxLng - minViewport.minLng;
newlatspan = newlngspan / canvasRatio;
}
}
// if we haven't zoomed in past the maxScale
if (newlngspan > maxScale * (minViewport.maxLng - minViewport.minLng)) {
// calculate new viewport
viewport = {
minLng: mouseLatLng.lng - relativePt.x * newlngspan,
maxLng: mouseLatLng.lng + (1 - relativePt.x) * newlngspan,
minLat: mouseLatLng.lat - (1 - relativePt.y) * newlatspan, // upside down y axis crap
maxLat: mouseLatLng.lat + relativePt.y * newlatspan
};
// prevent zooming out to space on the outside of the map's minViewport
if (newlngspan > lngspan) {
// if zooming out
if (viewport.minLng < minViewport.minLng) {
var diff = minViewport.minLng - viewport.minLng;
viewport.minLng += diff;
viewport.maxLng += diff;
}
if (viewport.maxLng > minViewport.maxLng) {
var diff = viewport.maxLng - minViewport.maxLng;
viewport.minLng -= diff;
viewport.maxLng -= diff;
}
if (viewport.minLat < minViewport.minLat) {
var diff = minViewport.minLat - viewport.minLat;
viewport.minLat += diff;
viewport.maxLat += diff;
}
if (viewport.maxLat > minViewport.maxLat) {
var diff = viewport.maxLat - minViewport.maxLat;
viewport.minLat -= diff;
viewport.maxLat -= diff;
}
}
}
if (viewport.maxLng - viewport.minLng < 90 || viewport.maxLat - viewport.minLat < 40) countryOutlines = mapBoundaries['50m'];else {
countryOutlines = mapBoundaries['110m'];
if (!countryOutlines) countryOutlines = mapBoundaries['50m'];
}
e.stopPropagation();
e.preventDefault();
needsRender = true;
}
var mouseProperties = {
isDown: false,
isDragging: false,
lastPt: { x: 0, y: 0 }
};
/***
* Handles mouse down events on the map canvas
***/
function handleMouseDown(e, pt) {
// set some kind of flag indicating that the mouse is down (so we can track dragging)
mouseProperties.isDown = true;
mouseProperties.isDragging = false;
// update the mouseProperties.lastPt
mouseProperties.lastPt = { x: pt.x, y: pt.y };
e.stopPropagation();
e.preventDefault();
needsRender = true;
}
/***
* Handles mouse move events on the map canvas
***/
function handleMouseMove(e, pt) {
if (!options.showValues) return;
var ctx = htmlCanvas.getContext('2d');
backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
canvasWidth = htmlCanvas.width / (pxRatio / backingStoreRatio);
canvasHeight = htmlCanvas.height / (pxRatio / backingStoreRatio);
// if the mouse down flag is set, we should set a flag indicating that we're dragging now
if (mouseProperties.isDown) mouseProperties.isDragging = true;
// if we're dragging, adjust the viewport
if (mouseProperties.isDragging) {
// calculate the ratio between lat/lng and px
var lngperpx = (viewport.maxLng - viewport.minLng) / canvasWidth;
var latperpx = (viewport.maxLat - viewport.minLat) / canvasHeight;
// add the differences to the viewport
viewport.minLng -= (pt.x - mouseProperties.lastPt.x) * lngperpx;
viewport.maxLng -= (pt.x - mouseProperties.lastPt.x) * lngperpx;
viewport.minLat += (pt.y - mouseProperties.lastPt.y) * latperpx;
viewport.maxLat += (pt.y - mouseProperties.lastPt.y) * latperpx;
// check for out of bounds
containViewport();
} else {
// check for hover
// get lng span in viewport
var lngspan = viewport.maxLng - viewport.minLng;
var latspan = viewport.maxLat - viewport.minLat;
// mouse coordinates in lat/lng
var mouseLatLng = {
lng: viewport.minLng + pt.x / canvasWidth * lngspan,
lat: viewport.minLat + (1 - pt.y / canvasHeight) * latspan // freakin frackin inverted y axis
};
// set all segments to 'not highlighted'
unhighlightAllSlices();
// if no circles are being dragged, let's see if one is highlighted
var hoveredDataSlice = hitTestPieSlices(mouseLatLng, null, null);
if (hoveredDataSlice) {
hoveredDataSlice.isHighlighted = true;
}
}
// update the mouseProperties.lastPt
mouseProperties.lastPt = { x: pt.x, y: pt.y };
e.stopPropagation();
e.preventDefault();
needsRender = true;
}
function unhighlightAllSlices() {
for (var a = 0; a < data.length; a++) {
for (var s = 0; s < data[a].segments.length; s++) {
data[a].segments[s].isHighlighted = false;
}
}
}
function hitTestPieSlices(mouseLatLng, onHit, onMiss) {
var ctx = htmlCanvas.getContext('2d');
backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
canvasWidth = htmlCanvas.width / (pxRatio / backingStoreRatio);
canvasHeight = htmlCanvas.height / (pxRatio / backingStoreRatio);
// calculate the ratio between lat/lng and px
var lngperpx = (viewport.maxLng - viewport.minLng) / canvasWidth;
var latperpx = (viewport.maxLat - viewport.minLat) / canvasHeight;
var highlightedDataSlice = null;
for (var a = 0; a < data.length; a++) {
var pieCenter = { lng: data[a].lng, lat: data[a].lat };
var pieRadius = data[a].radius * ((lngperpx + latperpx) / 2);
// calculate the theta and radius based on the x, y
var theta = Math.atan((mouseLatLng.lat - pieCenter.lat) / (mouseLatLng.lng - pieCenter.lng));
if (mouseLatLng.lat >= pieCenter.lat && mouseLatLng.lng >= pieCenter.lng) {
// quadrant 1
theta += 0;
} else if (mouseLatLng.lat >= pieCenter.lat && mouseLatLng.lng < pieCenter.lng) {
// quadrant 2
theta += Math.PI;
} else if (mouseLatLng.lat < pieCenter.lat && mouseLatLng.lng < pieCenter.lng) {
// quadrant 3
theta += Math.PI;
} else if (mouseLatLng.lat < pieCenter.lat && mouseLatLng.lng >= pieCenter.lng) {
// quadrant 4
theta += 0;
}
if (theta < 0) {
theta += Math.PI * 2;
}
theta = Math.PI * 2 - theta; // invert this because the latitude axis grows from bottom to top (inverse from the canvas's y axis)
if (theta >= Math.PI * 1.5) {
theta -= Math.PI * 2;
}
var radius = Math.sqrt((mouseLatLng.lng - pieCenter.lng) * (mouseLatLng.lng - pieCenter.lng) + (mouseLatLng.lat - pieCenter.lat) * (mouseLatLng.lat - pieCenter.lat));
var totalValue = _lodash2.default.sum(data[a].segments, function (segment) {
return segment.value;
});
var movingRadian = -Math.PI / 2;
for (var s = 0; s < data[a].segments.length; s++) {
var percent = data[a].segments[s].value / totalValue;
var startRadian = movingRadian;
var endRadian = movingRadian + percent * Math.PI * 2;
// if the mouse is over this pie slice, mark it as highlighted
if (theta >= startRadian && theta < endRadian && radius <= pieRadius) {
if (onHit) {
onHit(data[a].segments[s]);
}
highlightedDataSlice = data[a].segments[s];
} else {
if (onMiss) {
onMiss(data[a].segments[s]);
}
}
movingRadian += percent * Math.PI * 2;
}
}
return highlightedDataSlice;
}
/***
* Handles mouse up events on the map canvas
***/
function handleMouseUp(e, pt) {
if (!mouseProperties.isDragging) {
var ctx = htmlCanvas.getContext('2d');
backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
canvasWidth = htmlCanvas.width / (pxRatio / backingStoreRatio);
canvasHeight = htmlCanvas.height / (pxRatio / backingStoreRatio);
// get lng span in viewport
var lngspan = viewport.maxLng - viewport.minLng;
var latspan = viewport.maxLat - viewport.minLat;
// mouse coordinates in lat/lng
var mouseLatLng = {
lng: viewport.minLng + pt.x / canvasWidth * lngspan,
lat: viewport.minLat + (1 - pt.y / canvasHeight) * latspan // freakin frackin inverted y axis
};
var hoveredDataSlice = hitTestPieSlices(mouseLatLng, null, null);
if (hoveredDataSlice && hoveredDataSlice.onClick) {
hoveredDataSlice.onClick(e);
}
}
// set the mousedown and dragging flags to false
mouseProperties.isDown = false;
mouseProperties.isDragging = false;
e.stopPropagation();
e.preventDefault();
needsRender = true;
}
/***
* Handles the mouse out event (so we can stop dragging if you were.)
* Thanks, Blake for finding this issue
***/
function handleMouseOut(e) {
mouseProperties.isDragging = false;
mouseProperties.isDown = false;
e.stopPropagation();
e.preventDefault();
needsRender = true;
}
/***
* The animateFrame method is called many times per second to calculate any
* movement needed in the graph. It then calls render() to update the display.
* Even if there is no animation in the graph this method ensures the view is updated frequently in case
* mouse events change the view
***/
function animateFrame() {
var thisFrame = new Date().getTime();
var elapsed = thisFrame - lastFrame; // elapsed time since last render
fps = 1000 / elapsed;
var ctx = htmlCanvas.getContext('2d');
backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
canvasWidth = htmlCanvas.width / (pxRatio / backingStoreRatio);
canvasHeight = htmlCanvas.height / (pxRatio / backingStoreRatio);
// animation effects
// none for now. we still need this method, though, because it ensures the graph will re-render quickly whenever mouse events update the view
if (needsRender) {
self.render();
needsRender = false;
}
lastFrame = thisFrame;
if (!isDestroyed) {
if (window.requestAnimationFrame) {
window.requestAnimationFrame(animateFrame);
} else if (window.webkitRequestAnimationFrame) {
window.webkitRequestAnimationFrame(animateFrame);
} else if (window.mozRequestAnimationFrame) {
window.mozRequestAnimationFrame(animateFrame);
} else if (window.oRequestAnimationFrame) {
window.oRequestAnimationFrame(animateFrame);
}
}
}
var lastFrame = new Date().getTime(); // the timestamp of the last time the frame was last rendered
var fps = 0;
/***
* Handles the window.resize event so the canvas can be made to fill the parent automatically
***/
function fillParent() {
if (htmlCanvas && htmlCanvas.parentNode) {
var style = window.getComputedStyle(htmlCanvas.parentNode);
var width = htmlCanvas.parentNode.offsetWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
var height = htmlCanvas.parentNode.offsetHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom);
// upscale this thang if the device pixel ratio is higher than 1
var pxRatio = window.devicePixelRatio || 1;
htmlCanvas.width = width * pxRatio;
htmlCanvas.height = height * pxRatio;
htmlCanvas.style.width = width + 'px';
htmlCanvas.style.height = height + 'px';
// determine whether the lng or lat will fill the mapSize
var canvasRatio = width / height;
var lngspan = 0;
var latspan = 0;
if (canvasRatio > mapRatio) {
latspan = minViewport.maxLat - minViewport.minLat;
lngspan = latspan * canvasRatio;
} else {
lngspan = minViewport.maxLng - minViewport.minLng;
latspan = lngspan / canvasRatio;
}
viewport = {
minLat: (minViewport.maxLat + minViewport.minLat) / 2 - latspan / 2,
maxLat: (minViewport.maxLat + minViewport.minLat) / 2 + latspan / 2,
minLng: (minViewport.maxLng + minViewport.minLng) / 2 - lngspan / 2,
maxLng: (minViewport.maxLng + minViewport.minLng) / 2 + lngspan / 2
};
}
needsRender = true;
}
/***
* Initialize the canvas on the DOM and add event listening
***/
function _init() {
var _this = this;
htmlCanvas = document.createElement('CANVAS');
htmlContainer.innerHTML = '';
htmlContainer.appendChild(htmlCanvas);
fillParent();
data = mapData;
var ctx = htmlCanvas.getContext('2d');
backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
var canvasWidth = htmlCanvas.width / (pxRatio / backingStoreRatio);
var canvasHeight = htmlCanvas.height / (pxRatio / backingStoreRatio);
var maxPieArea = canvasWidth * canvasHeight * 0.0120;
var minPieArea = canvasWidth * canvasHeight * 0.0010;
// calculate which fill amount is the max for this map so we can scale pies
var maxValue = _lodash2.default.max(data, function (datum) {
return datum.value;
}).value;
var minValue = _lodash2.default.min(data, function (datum) {
return datum.value;
}).value;
for (var a = 0; a < data.length; a++) {
var parts = _Numbers2.default.separateNumberUnits(data[a].value);
if (data[a].prefix === undefined) data[a].prefix = parts.prefix;
if (data[a].suffix === undefined) data[a].suffix = parts.suffix;
data[a].value = parts.value;
var coords = getCentroidByISO(data[a].iso_a2);
if (coords) {
data[a].lat = coords.lat;
data[a].lng = coords.lng;
}
if (maxValue - minValue === 0) {
// all pies are the same size
data[a].radius = Math.sqrt(maxPieArea / Math.PI);
} else {
var valuePct = (data[a].value - minValue) / (maxValue - minValue);
var area = valuePct * (maxPieArea - minPieArea) + minPieArea;
data[a].radius = Math.sqrt(area / Math.PI);
}
}
// Set up some event handling, please
if (options.allowZoomAndPan) {
htmlCanvas.addEventListener('mousewheel', handleScroll, false); // IE9, Chrome, Safari, Opera
htmlCanvas.addEventListener('DOMMouseScroll', handleScroll, false); // Firefox
htmlCanvas.addEventListener('mousedown', function (event) {
// get the x,y offset of the mouse move point relative to the map canvas
var rect = htmlCanvas.getBoundingClientRect();
var pt = {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
handleMouseDown(event, pt);
});
htmlCanvas.addEventListener('mousemove', function (event) {
// get the x,y offset of the mouse move point relative to the map canvas
var rect = htmlCanvas.getBoundingClientRect();
var pt = {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
handleMouseMove(event, pt);
});
htmlCanvas.addEventListener('mouseup', function (event) {
// get the x,y offset of the mouse move point relative to the map canvas
var rect = htmlCanvas.getBoundingClientRect();
var pt = {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
handleMouseUp(event, pt);
});
htmlCanvas.addEventListener('mouseout', handleMouseOut, false);
}
resizeListener = window.addEventListener('resize', function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
fillParent.call(_this);
}, 50);
});
fullScreenChangeListener = window.addEventListener('webkitfullscreenchange', fullscreenChange);
webkitFullScreenChangeListener = window.addEventListener('fullscreenchange', fullscreenChange);
mozFullScreenChangeListener = window.addEventListener('mozfullscreenchange', fullscreenChange);
msFullScreenChangeListener = window.addEventListener('msfullscreenchange', fullscreenChange);
function fullscreenChange(event) {
var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;
if (!fullscreenElement) {
// exiting full screen
var targetElement = event.target;
// if this element contains a canvas, make it tiny so we don't mess up the size of its parent
// don't worry, the window.resize event that fires next will make it fill its parent just fine
var canvases = targetElement.getElementsByTagName('CANVAS');
for (var c = 0; c < canvases.length; c++) {
if (canvases[c] === htmlCanvas) {
canvases[c].width = 1;
canvases[c].height = 1;
canvases[c].style.width = '1px';
canvases[c].style.height = '1px';
break;
}
}
}
}
if (window.requestAnimationFrame) {
window.requestAnimationFrame(animateFrame);
} else if (window.webkitRequestAnimationFrame) {
window.webkitRequestAnimationFrame(animateFrame);
} else if (window.mozRequestAnimationFrame) {
window.mozRequestAnimationFrame(animateFrame);
} else if (window.oRequestAnimationFrame) {
window.oRequestAnimationFrame(animateFrame);
}
}
this.destroy = function () {
if (fullScreenChangeListener) {
window.removeEventListener('fullscreenchange', fullScreenChangeListener);
}
if (webkitFullScreenChangeListener) {
window.removeEventListener('webkitfullscreenchange', webkitFullScreenChangeListener);
}
if (mozFullScreenChangeListener) {
window.removeEventListener('mozfullscreenchange', mozFullScreenChangeListener);
}
if (msFullScreenChangeListener) {
window.removeEventListener('msfullscreenchange', msFullScreenChangeListener);
}
if (resizeListener) {
window.removeEventListener('resize', resizeListener);
}
if (htmlCanvas && htmlCanvas.parentNode) {
htmlCanvas.parentNode.removeChild(htmlCanvas);
}
isDestroyed = true;
};
// Initialize
_init.call(this);
};
exports.default = PieMap;