Compare commits

..

114 Commits

Author SHA1 Message Date
Michelle Tilley
838bf92265
Bump to 1.1.13 2018-10-30 11:52:33 -07:00
Michelle Tilley
24ad38a824
Merge pull request #23 from christiannaths/master
Fixes incorrect dependency notation
2018-10-30 11:45:49 -07:00
Christian Naths
1a388e7c4a
Fixes incorrect dependency notation
Locks dependencies down to:
  - topojson version 1
  - d3 version 3

As described in the docs
2018-08-25 15:14:22 -06:00
BinaryMuse
801ccb28e5 v1.1.2 2015-11-22 02:14:02 -08:00
BinaryMuse
52716cba5b Name update 2015-11-22 02:04:36 -08:00
Brandon Tilley
80ef60d6cf Update planet#draw docs 2014-12-13 12:04:48 -08:00
Brandon Tilley
f4d9536f17 v1.1.1 2014-05-18 10:37:03 -07:00
Rolf Sommerhalder
9344299298 Set planetaryjs global when using AMD
While using RequireJS to AMD load ng-planetaryjs, planetaryjs, and their
dependencies, ng-planetaryjs still looks for global object planetaryjs
(such as in `var globe = planetaryjs.planet();`). Thus use the UMD
pattern "AMD with global, Node, or global" instead of "AMD, Node, or
browser global" from https://sublime.wbond.net/packages/UMD%20snippets
2014-05-18 10:32:26 -07:00
Brandon Tilley
3d6ca445f8 Update devDependencies 2014-05-18 10:25:51 -07:00
Brandon Tilley
c86479db1f Update changelog retroactively to match release notes on GitHub 2014-02-03 00:25:33 -08:00
Brandon Tilley
5e807f52e0 v1.1.0 2014-02-03 00:16:47 -08:00
Brandon Tilley
cfb059369e Update CHANGELOG 2014-02-03 00:14:39 -08:00
Brandon Tilley
4edb647564 (core) Add stop method 2014-02-03 00:13:37 -08:00
Brandon Tilley
74013bde29 v1.0.3 2014-01-22 20:45:13 -08:00
Brandon Tilley
62e8d08bd9 (core) Don't disable adaptive resampling on the projection 2014-01-22 20:43:26 -08:00
Brandon Tilley
f5bf0743fb (site) Fix broken markup around 'download source' link 2014-01-15 21:39:35 -08:00
Brandon Tilley
53b7a3b2b7 v1.0.2 2014-01-15 21:33:16 -08:00
Brandon Tilley
2aa72ca45e (site) Update CommonJS installation instructions 2014-01-15 21:31:48 -08:00
Brandon Tilley
d873121c08 (core) Update dependencies on D3 and TopoJSON 2014-01-15 14:17:50 -08:00
Brandon Tilley
1eae3fb7c9 Merge pull request #5 from darul75/master
(site) Fix ID of globe in rotating example
2014-01-11 15:18:50 -08:00
Julien Valéry
c8c4bfa4bd fix id globe name
great job, thanks
2014-01-11 17:11:14 +01:00
Brandon Tilley
6350c397b2 (site) Fix broken DOM 2014-01-06 18:37:17 -08:00
Brandon Tilley
bbe2e15283 (site) Count clicks to GH as non-bounce visitors 2014-01-03 15:11:16 -08:00
Brandon Tilley
b9a070ab76 Don't forget important things like creating releases 2014-01-03 07:32:03 -08:00
Brandon Tilley
964dfbc366 v1.0.1 2014-01-02 09:06:06 -08:00
Brandon Tilley
05313d79f8 (core) Depend on D3 and TopoJSON 2014-01-02 09:04:40 -08:00
Brandon Tilley
461561340b (site) Note TopoJSON PR in CommonJS installation instructions 2014-01-02 09:04:20 -08:00
Brandon Tilley
fe1de35576 (site) Add installation section; move AMD and CommonJS info there 2014-01-01 18:18:51 -08:00
Brandon Tilley
1764ee07f7 (site) Fix incorrect plugins in quake example 2014-01-01 11:49:02 -08:00
Brandon Tilley
19ed44d67b (site) Add FB meta tags 2013-12-31 12:41:49 -08:00
Brandon Tilley
03b52fb10d v1.0.0 2013-12-31 10:56:27 -08:00
Brandon Tilley
d28358568c Remove version name 2013-12-31 10:52:52 -08:00
Brandon Tilley
ac192b779b (site) Increase number of pings on homepage/rotating example 2013-12-28 21:45:22 -08:00
Brandon Tilley
5aa5f5633f (site) Add AMD and CommonJS info to FAQ 2013-12-28 16:18:29 -08:00
Brandon Tilley
4927fedc20 Add 'main' entry to package.json 2013-12-28 16:18:09 -08:00
Brandon Tilley
5a140ab914 Add script to set version number 2013-12-28 13:09:12 -08:00
Brandon Tilley
50b283aa5e (site) Add link to release notes and tree/tag from download page 2013-12-28 13:07:02 -08:00
Brandon Tilley
e37d657a61 (core) Ensure built files use newlines everywhere 2013-12-28 13:02:54 -08:00
Brandon Tilley
35d3ca0d9d (site) Update world-110m.json download link 2013-12-28 11:59:50 -08:00
Brandon Tilley
f21450fd2a (site) Add TopoJSON feature information to 'land' and 'borders' plugin documentation 2013-12-28 11:47:23 -08:00
Brandon Tilley
c698e7ac84 (site) Add line numbers to examples' displayed code 2013-12-28 11:21:49 -08:00
Brandon Tilley
2814b849de (site) Increase visibility of play link for quake demo 2013-12-27 21:25:00 -08:00
Brandon Tilley
a7e10b9a92 (site) Update color key for quake example 2013-12-27 15:59:50 -08:00
Brandon Tilley
a8aa5c88c2 (site) Minor update to quake example 2013-12-27 15:36:13 -08:00
Brandon Tilley
d83290146a (site) Update quake data to include up to Dec 27 2013-12-27 10:45:06 -08:00
Brandon Tilley
f1f39d8e01 Add script to compress earthquake data from usgs.gov 2013-12-27 10:41:12 -08:00
Brandon Tilley
aa69976987 (topojson) Recreate world-110m.json with topojson utility to decrease file size 2013-12-26 15:27:11 -08:00
Brandon Tilley
50d12ad7c6 (site) Add lakes to rotating example 2013-12-26 15:26:29 -08:00
Brandon Tilley
c50c3a8a1a (site) Fix wrapping on examples page on mobile 2013-12-26 10:35:27 -08:00
Brandon Tilley
99a3a9374f (site) Fix highlighting code 2013-12-25 23:40:37 -08:00
Brandon Tilley
72b6b68b25 v1.0.0-rc.2 2013-12-25 23:30:59 -08:00
Brandon Tilley
7524006ca0 (site) Fix typos, style issues, etc 2013-12-25 23:25:35 -08:00
Brandon Tilley
3e141e7734 (site) Expand FAQ to include question about loading data via Ajax 2013-12-25 19:15:48 -08:00
Brandon Tilley
16bbb57af0 (site) Fix menu styling on download page 2013-12-25 17:07:44 -08:00
Brandon Tilley
7db6071812 (site) Add download page 2013-12-25 17:06:38 -08:00
Brandon Tilley
4a8860ec1e Refactor examples page 2013-12-25 16:21:26 -08:00
Brandon Tilley
277b7f587b (site) Add GA tracking 2013-12-25 14:18:29 -08:00
Brandon Tilley
3deb35de6b (site) Tweaks to copy and stying of homepage 2013-12-25 14:18:17 -08:00
Brandon Tilley
2fe52ec148 (drag, zoom): Expose planet instance as this in event callbacks 2013-12-24 21:54:33 -08:00
Brandon Tilley
c69f749747 (core): Fix load order of global plugins 2013-12-24 21:19:28 -08:00
Brandon Tilley
5be5a97a19 (site) Tweak homepage styles 2013-12-24 10:41:39 -08:00
Brandon Tilley
48c3eb5d5f (site) Fix broken styling on small displays 2013-12-24 10:34:58 -08:00
Brandon Tilley
b3732450be Fix typo and styling of rotating example 2013-12-24 10:25:01 -08:00
Brandon Tilley
3b1c80e656 v1.0.0-rc.1 2013-12-24 08:36:58 -08:00
Brandon Tilley
54f75ff627 zoom plugin's initialScale can be set to 0 2013-12-24 08:29:01 -08:00
Brandon Tilley
deb0caff44 Add jshint and gulp task; implement hints 2013-12-24 08:28:19 -08:00
Brandon Tilley
e45f703c9b Minor tweaks to earthquake example 2013-12-23 22:59:55 -08:00
Brandon Tilley
9ddbee97f9 Fix broken link in quake example 2013-12-23 22:49:19 -08:00
Brandon Tilley
2fec3977be Update quake docs to match code 2013-12-23 22:46:51 -08:00
Brandon Tilley
091fe63700 Tweak quake example UI 2013-12-23 22:43:42 -08:00
Brandon Tilley
f2d15f6470 Tweak quake example 2013-12-23 22:38:26 -08:00
Brandon Tilley
3d63db9058 Fix changelog 2013-12-23 22:25:40 -08:00
Brandon Tilley
4bff52356c Update quake example 2013-12-23 22:23:31 -08:00
Brandon Tilley
2c85e4d92e v0.3.0 2013-12-23 22:09:49 -08:00
Brandon Tilley
ef285150ee Reverse the order of lat and lng parameters of the add method of the pings plugin 2013-12-23 22:08:03 -08:00
Brandon Tilley
b2964f0dc7 Fix various typos in site 2013-12-23 21:52:49 -08:00
Brandon Tilley
e0bb02d461 v0.2.2 2013-12-23 15:11:59 -08:00
Brandon Tilley
72cbd4990d Update rotating example 2013-12-23 15:02:27 -08:00
Brandon Tilley
bae0d216e6 Add link to download page to readme 2013-12-23 14:57:46 -08:00
Brandon Tilley
ab92e0a472 Add afterZoom and afterDrag hooks to the zoom and drag plugins 2013-12-23 14:57:00 -08:00
Brandon Tilley
bb92a25d99 Update mobile style 2013-12-23 14:36:51 -08:00
Brandon Tilley
1a0cf23685 Update link to index page 2013-12-23 14:19:47 -08:00
Brandon Tilley
fe7a959a9e Update homepage 2013-12-23 14:15:41 -08:00
Brandon Tilley
09be66da35 Add FAQ 2013-12-23 14:15:36 -08:00
Brandon Tilley
14a0b8fdf4 Implement basic and rotating globe examples 2013-12-23 14:15:23 -08:00
Brandon Tilley
8c9848a492 Update quake page from JS 2013-12-23 13:24:52 -08:00
Brandon Tilley
f149583f0b v0.2.1 2013-12-22 14:19:59 -08:00
Brandon Tilley
5317fa2214 Fix site typos 2013-12-22 14:13:06 -08:00
Brandon Tilley
0d6eca2330 Update examples index page 2013-12-22 14:08:40 -08:00
Brandon Tilley
5e402da7ae Implement zoom/drag in quake demo with built-in plugins 2013-12-22 14:02:14 -08:00
Brandon Tilley
823a938a4b Add the 'drag' and 'zoom' plugins 2013-12-22 13:59:41 -08:00
Brandon Tilley
b06c3779dc Add earthquake example 2013-12-22 13:30:43 -08:00
Brandon Tilley
48c93f4853 Clarify plugin documentation 2013-12-22 11:11:33 -08:00
Brandon Tilley
90b74a6a94 Add 'Getting Help' doc 2013-12-21 23:56:08 -08:00
Brandon Tilley
335cd859ca v0.2.0 2013-12-21 23:35:36 -08:00
Brandon Tilley
d76e2ad919 Add documentation on default plugins 2013-12-21 23:34:49 -08:00
Brandon Tilley
626d01c2d7 Allow default configuration options to be passed to the pings plugin 2013-12-21 23:33:39 -08:00
Brandon Tilley
4bb0202bc9 Add the type configuration option to the borders plugin 2013-12-21 23:11:24 -08:00
Brandon Tilley
069f4c4901 Add the lineWidth configuration option to the land and borders plugins 2013-12-21 23:03:05 -08:00
Brandon Tilley
b8f302c8f5 Add plugin 'best practices' documentation 2013-12-21 22:47:25 -08:00
Brandon Tilley
321822f983 Remove the 'stroke' configuration option from the 'oceans' plugin 2013-12-21 22:45:19 -08:00
Brandon Tilley
2a6237411c Add more documentation 2013-12-21 21:04:59 -08:00
Brandon Tilley
6ac19dd19c Remove duplicate readme 2013-12-21 20:34:47 -08:00
Brandon Tilley
4b8363ebc0 Add more documentation 2013-12-21 20:33:35 -08:00
Brandon Tilley
4563d9bda4 Change topojson plugin to store on planet.plugins.topojson 2013-12-21 20:29:31 -08:00
Brandon Tilley
7c57a54d36 Add build instructions to readme 2013-12-21 19:49:01 -08:00
Brandon Tilley
e428e6818a Modify withSavedContext documentation 2013-12-21 19:44:57 -08:00
Brandon Tilley
5b64dd81db Add Prism syntax highlighting 2013-12-21 19:44:30 -08:00
Brandon Tilley
27b2add22d Tweak site CSS 2013-12-21 19:22:13 -08:00
Brandon Tilley
d5862b3818 Initial documentation pages 2013-12-21 19:17:43 -08:00
Brandon Tilley
0571225149 Fix typo in site readme 2013-12-21 16:10:20 -08:00
Brandon Tilley
53d21e0b96 Add more bower metadata 2013-12-21 15:09:42 -08:00
Brandon Tilley
ba22cb6496 Add bower keywords 2013-12-21 15:07:56 -08:00
Brandon Tilley
67072bbbc9 Add bower link 2013-12-21 15:02:21 -08:00
75 changed files with 7233 additions and 180 deletions

78
CHANGELOG.md Normal file
View File

@ -0,0 +1,78 @@
v1.1.2 (2015/11/22)
-------------------
* Update LICENSE and copyright notices
v1.1.1 (2014/05/18)
-------------------
* Set `planetaryjs` on root when using AMD
v1.1.0 (2014/02/03)
-------------------
**Core**
* Add `stop` method
* Add `onStop` hooks
v1.0.3 (2014/01/23)
-------------------
* Don't disable adaptive resampling on the projection
v1.0.2 (2014/01/16)
-------------------
* Update version dependencies for D3 and TopoJSON
v1.0.1 (2013/01/02)
-------------------
* Add D3 and TopoJSON as dependencies in `package.json`
v1.0.0 (2013/12/31)
-------------------
First stable release
v1.0.0-rc.2 (2013/12/26)
------------------------
* Fix load order of global plugins
* Expose planet instance as `this` in event callbacks
v1.0.0-rc.1 (2013/12/24)
------------------------
* `zoom` plugin's `initialScale` can be set to `0`
v0.3.0
------
* Reverse the order of `lat` and `lng` parameters of the `add` method of the `pings` plugin
v0.2.2
------
* Add `afterZoom` and `afterDrag` hooks to the `zoom` and `drag` plugins
v0.2.1
------
* Implement the `drag` and `zoom` plugins
v0.2.0
------
* Convert the built-in `topojson` plugin to store data on `planet.plugins.topojson.world` instead of `planet.world`
* Convert the built-in `land` and `borders` plugins to read world data from `planet.plugins.topojson.world`
* Remove the `stroke` configuration option from the `oceans` plugin
* Add the `lineWidth` configuration option to the `land` and `borders` plugins
* Add the `type` configuration option to the `borders` plugin
* Allow default configuration options to be passed to the `pings` plugin
v0.1.1
------
* Initial pre-release version

View File

@ -1,4 +1,4 @@
Copyright (c) 2013 Brandon Tilley Copyright (c) 2013 Michelle Tilley
Permission is hereby granted, free of charge, to any person Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation obtaining a copy of this software and associated documentation

View File

@ -15,6 +15,11 @@ Requirements
* [D3](http://d3js.org/) version 3 * [D3](http://d3js.org/) version 3
* [TopoJSON](https://github.com/mbostock/topojson) version 1 * [TopoJSON](https://github.com/mbostock/topojson) version 1
Download
--------
Download Planetary.js from the [Planetary.js web site](http://planetaryjs.com/download/).
Quick Start Quick Start
----------- -----------
@ -58,6 +63,11 @@ Documentation
In-depth documentation can be found at [planetaryjs.com](http://planetaryjs.com). In-depth documentation can be found at [planetaryjs.com](http://planetaryjs.com).
Building
--------
Building the project requires [Node.js](http://nodejs.org/). Once you've installed the project's dependencies with `npm install`, you can build the JavaScript to the `dist` directory with `npm run build`.
License License
------- -------

View File

@ -1,7 +1,13 @@
{ {
"name": "planetary.js", "name": "planetary.js",
"version": "0.1.1", "version": "1.1.2",
"main": "dist/planetaryjs.min.js", "main": "dist/planetaryjs.min.js",
"description": "Awesome interactive globes for the web",
"homepage": "http://planetaryjs.com",
"authors": [
"Michelle Tilley <michelle@michelletilley.net>"
],
"license": "MIT",
"ignore": [ "ignore": [
".git", ".git",
".gitignore", ".gitignore",
@ -15,5 +21,13 @@
"dependencies": { "dependencies": {
"d3": "3.x", "d3": "3.x",
"topojson": "1.x" "topojson": "1.x"
} },
"keywords": [
"globe",
"globes",
"planet",
"planets",
"d3",
"topojson"
]
} }

View File

@ -1,12 +1,14 @@
/*! Planetary.js v0.0.0 /*! Planetary.js v1.1.3
* Copyright (c) 2013 Brandon Tilley * Copyright (c) 2013 Michelle Tilley
* *
* Released under the MIT license * Released under the MIT license
* Date: 2013-12-21T22:36:57.273Z * Date: 2018-10-30T18:49:58.804Z
*/ */
(function (root, factory) { (function (root, factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
define(['d3', 'topojson'], factory); define(['d3', 'topojson'], function(d3, topojson) {
return (root.planetaryjs = factory(d3, topojson, root));
});
} else if (typeof exports === 'object') { } else if (typeof exports === 'object') {
module.exports = factory(require('d3'), require('topojson')); module.exports = factory(require('d3'), require('topojson'));
} else { } else {
@ -21,7 +23,11 @@
var doDrawLoop = function(planet, canvas, hooks) { var doDrawLoop = function(planet, canvas, hooks) {
d3.timer(function() { d3.timer(function() {
planet.context.clearRect(0, 0, canvas.width, canvas.height) if (planet.stopped) {
return true;
}
planet.context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < hooks.onDraw.length; i++) { for (var i = 0; i < hooks.onDraw.length; i++) {
hooks.onDraw[i](); hooks.onDraw[i]();
} }
@ -30,19 +36,19 @@
var initPlugins = function(planet, localPlugins) { var initPlugins = function(planet, localPlugins) {
// Add the global plugins to the beginning of the local ones // Add the global plugins to the beginning of the local ones
for (var i = 0; i < plugins.length; i++) { for (var i = plugins.length - 1; i >= 0; i--) {
localPlugins.unshift(plugins[i]); localPlugins.unshift(plugins[i]);
} }
// Load the default plugins if none have been loaded so far // Load the default plugins if none have been loaded so far
if (localPlugins.length == 0) { if (localPlugins.length === 0) {
if (planetaryjs.plugins.earth) if (planetaryjs.plugins.earth)
planet.loadPlugin(planetaryjs.plugins.earth()); planet.loadPlugin(planetaryjs.plugins.earth());
if (planetaryjs.plugins.pings) if (planetaryjs.plugins.pings)
planet.loadPlugin(planetaryjs.plugins.pings()); planet.loadPlugin(planetaryjs.plugins.pings());
} }
for (var i = 0; i < localPlugins.length; i++) { for (i = 0; i < localPlugins.length; i++) {
localPlugins[i](planet); localPlugins[i](planet);
} }
}; };
@ -68,7 +74,7 @@
var check = function() { var check = function() {
if (completed >= hooks.onInit.length) doDrawLoop(planet, canvas, hooks); if (completed >= hooks.onInit.length) doDrawLoop(planet, canvas, hooks);
else doNext(check); else doNext(check);
} };
doNext(check); doNext(check);
} else { } else {
doDrawLoop(planet, canvas, hooks); doDrawLoop(planet, canvas, hooks);
@ -76,11 +82,14 @@
}; };
var startDraw = function(planet, canvas, localPlugins, hooks) { var startDraw = function(planet, canvas, localPlugins, hooks) {
initPlugins(planet, localPlugins);
planet.canvas = canvas; planet.canvas = canvas;
planet.context = canvas.getContext('2d'); planet.context = canvas.getContext('2d');
if (planet.stopped !== true) {
initPlugins(planet, localPlugins);
}
planet.stopped = false;
runOnInitHooks(planet, canvas, hooks); runOnInitHooks(planet, canvas, hooks);
}; };
@ -100,7 +109,8 @@
var localPlugins = []; var localPlugins = [];
var hooks = { var hooks = {
onInit: [], onInit: [],
onDraw: [] onDraw: [],
onStop: []
}; };
var planet = { var planet = {
@ -118,13 +128,24 @@
hooks.onDraw.push(fn); hooks.onDraw.push(fn);
}, },
onStop: function(fn) {
hooks.onStop.push(fn);
},
loadPlugin: function(plugin) { loadPlugin: function(plugin) {
localPlugins.push(plugin); localPlugins.push(plugin);
}, },
stop: function() {
planet.stopped = true;
for (var i = 0; i < hooks.onStop.length; i++) {
hooks.onStop[i](planet);
}
},
withSavedContext: function(fn) { withSavedContext: function(fn) {
if (!this.context) { if (!this.context) {
throw new Error("No canvas to fetch context for") throw new Error("No canvas to fetch context for");
} }
this.context.save(); this.context.save();
@ -134,8 +155,7 @@
}; };
planet.projection = d3.geo.orthographic() planet.projection = d3.geo.orthographic()
.clipAngle(90) .clipAngle(90);
.precision(0);
planet.path = d3.geo.path().projection(planet.projection); planet.path = d3.geo.path().projection(planet.projection);
return planet; return planet;

View File

@ -1,2 +1,2 @@
/*! Planetary.js 0.0.0 | (c) 2013 Brandon Tilley | Released under MIT License */ /*! Planetary.js 1.1.3 | (c) 2013 Michelle Tilley | Released under MIT License */
!function(n,t){"function"==typeof define&&define.amd?define(["d3","topojson"],t):"object"==typeof exports?module.exports=t(require("d3"),require("topojson")):n.planetaryjs=t(n.d3,n.topojson,n)}(this,function(n,t,o){"use strict";var e=null;o&&(e=o.planetaryjs);var i=[],r=function(t,o,e){n.timer(function(){t.context.clearRect(0,0,o.width,o.height);for(var n=0;n<e.onDraw.length;n++)e.onDraw[n]()})},u=function(n,t){for(var o=0;o<i.length;o++)t.unshift(i[o]);0==t.length&&(s.plugins.earth&&n.loadPlugin(s.plugins.earth()),s.plugins.pings&&n.loadPlugin(s.plugins.pings()));for(var o=0;o<t.length;o++)t[o](n)},c=function(n,t,o){if(o.onInit.length){var e=0,i=function(n){var t=o.onInit[e];t.length?t(function(){e++,n()}):(t(),e++,setTimeout(n,0))},u=function(){e>=o.onInit.length?r(n,t,o):i(u)};i(u)}else r(n,t,o)},a=function(n,t,o,e){u(n,o),n.canvas=t,n.context=t.getContext("2d"),c(n,t,e)},s={plugins:{},noConflict:function(){return o.planetaryjs=e,s},loadPlugin:function(n){i.push(n)},planet:function(){var t=[],o={onInit:[],onDraw:[]},e={plugins:{},draw:function(n){a(e,n,t,o)},onInit:function(n){o.onInit.push(n)},onDraw:function(n){o.onDraw.push(n)},loadPlugin:function(n){t.push(n)},withSavedContext:function(n){if(!this.context)throw new Error("No canvas to fetch context for");this.context.save(),n(this.context),this.context.restore()}};return e.projection=n.geo.orthographic().clipAngle(90).precision(0),e.path=n.geo.path().projection(e.projection),e}};return s}); !function(n,t){"function"==typeof define&&define.amd?define(["d3","topojson"],function(o,e){return n.planetaryjs=t(o,e,n)}):"object"==typeof exports?module.exports=t(require("d3"),require("topojson")):n.planetaryjs=t(n.d3,n.topojson,n)}(this,function(n,t,o){"use strict";var e=null;o&&(e=o.planetaryjs);var i=[],r=function(t,o,e){n.timer(function(){if(t.stopped)return!0;t.context.clearRect(0,0,o.width,o.height);for(var n=0;n<e.onDraw.length;n++)e.onDraw[n]()})},u=function(n,t){for(var o=i.length-1;o>=0;o--)t.unshift(i[o]);for(0===t.length&&(s.plugins.earth&&n.loadPlugin(s.plugins.earth()),s.plugins.pings&&n.loadPlugin(s.plugins.pings())),o=0;o<t.length;o++)t[o](n)},p=function(n,t,o){if(o.onInit.length){var e=0,i=function(n){var t=o.onInit[e];t.length?t(function(){e++,n()}):(t(),e++,setTimeout(n,0))},u=function(){e>=o.onInit.length?r(n,t,o):i(u)};i(u)}else r(n,t,o)},c=function(n,t,o,e){n.canvas=t,n.context=t.getContext("2d"),n.stopped!==!0&&u(n,o),n.stopped=!1,p(n,t,e)},s={plugins:{},noConflict:function(){return o.planetaryjs=e,s},loadPlugin:function(n){i.push(n)},planet:function(){var t=[],o={onInit:[],onDraw:[],onStop:[]},e={plugins:{},draw:function(n){c(e,n,t,o)},onInit:function(n){o.onInit.push(n)},onDraw:function(n){o.onDraw.push(n)},onStop:function(n){o.onStop.push(n)},loadPlugin:function(n){t.push(n)},stop:function(){e.stopped=!0;for(var n=0;n<o.onStop.length;n++)o.onStop[n](e)},withSavedContext:function(n){if(!this.context)throw new Error("No canvas to fetch context for");this.context.save(),n(this.context),this.context.restore()}};return e.projection=n.geo.orthographic().clipAngle(90),e.path=n.geo.path().projection(e.projection),e}};return s});

186
dist/planetaryjs.js vendored
View File

@ -1,12 +1,14 @@
/*! Planetary.js v0.0.0 /*! Planetary.js v1.1.3
* Copyright (c) 2013 Brandon Tilley * Copyright (c) 2013 Michelle Tilley
* *
* Released under the MIT license * Released under the MIT license
* Date: 2013-12-21T22:36:57.373Z * Date: 2018-10-30T18:49:58.667Z
*/ */
(function (root, factory) { (function (root, factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
define(['d3', 'topojson'], factory); define(['d3', 'topojson'], function(d3, topojson) {
return (root.planetaryjs = factory(d3, topojson, root));
});
} else if (typeof exports === 'object') { } else if (typeof exports === 'object') {
module.exports = factory(require('d3'), require('topojson')); module.exports = factory(require('d3'), require('topojson'));
} else { } else {
@ -21,7 +23,11 @@
var doDrawLoop = function(planet, canvas, hooks) { var doDrawLoop = function(planet, canvas, hooks) {
d3.timer(function() { d3.timer(function() {
planet.context.clearRect(0, 0, canvas.width, canvas.height) if (planet.stopped) {
return true;
}
planet.context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < hooks.onDraw.length; i++) { for (var i = 0; i < hooks.onDraw.length; i++) {
hooks.onDraw[i](); hooks.onDraw[i]();
} }
@ -30,19 +36,19 @@
var initPlugins = function(planet, localPlugins) { var initPlugins = function(planet, localPlugins) {
// Add the global plugins to the beginning of the local ones // Add the global plugins to the beginning of the local ones
for (var i = 0; i < plugins.length; i++) { for (var i = plugins.length - 1; i >= 0; i--) {
localPlugins.unshift(plugins[i]); localPlugins.unshift(plugins[i]);
} }
// Load the default plugins if none have been loaded so far // Load the default plugins if none have been loaded so far
if (localPlugins.length == 0) { if (localPlugins.length === 0) {
if (planetaryjs.plugins.earth) if (planetaryjs.plugins.earth)
planet.loadPlugin(planetaryjs.plugins.earth()); planet.loadPlugin(planetaryjs.plugins.earth());
if (planetaryjs.plugins.pings) if (planetaryjs.plugins.pings)
planet.loadPlugin(planetaryjs.plugins.pings()); planet.loadPlugin(planetaryjs.plugins.pings());
} }
for (var i = 0; i < localPlugins.length; i++) { for (i = 0; i < localPlugins.length; i++) {
localPlugins[i](planet); localPlugins[i](planet);
} }
}; };
@ -68,7 +74,7 @@
var check = function() { var check = function() {
if (completed >= hooks.onInit.length) doDrawLoop(planet, canvas, hooks); if (completed >= hooks.onInit.length) doDrawLoop(planet, canvas, hooks);
else doNext(check); else doNext(check);
} };
doNext(check); doNext(check);
} else { } else {
doDrawLoop(planet, canvas, hooks); doDrawLoop(planet, canvas, hooks);
@ -76,11 +82,14 @@
}; };
var startDraw = function(planet, canvas, localPlugins, hooks) { var startDraw = function(planet, canvas, localPlugins, hooks) {
initPlugins(planet, localPlugins);
planet.canvas = canvas; planet.canvas = canvas;
planet.context = canvas.getContext('2d'); planet.context = canvas.getContext('2d');
if (planet.stopped !== true) {
initPlugins(planet, localPlugins);
}
planet.stopped = false;
runOnInitHooks(planet, canvas, hooks); runOnInitHooks(planet, canvas, hooks);
}; };
@ -100,7 +109,8 @@
var localPlugins = []; var localPlugins = [];
var hooks = { var hooks = {
onInit: [], onInit: [],
onDraw: [] onDraw: [],
onStop: []
}; };
var planet = { var planet = {
@ -118,13 +128,24 @@
hooks.onDraw.push(fn); hooks.onDraw.push(fn);
}, },
onStop: function(fn) {
hooks.onStop.push(fn);
},
loadPlugin: function(plugin) { loadPlugin: function(plugin) {
localPlugins.push(plugin); localPlugins.push(plugin);
}, },
stop: function() {
planet.stopped = true;
for (var i = 0; i < hooks.onStop.length; i++) {
hooks.onStop[i](planet);
}
},
withSavedContext: function(fn) { withSavedContext: function(fn) {
if (!this.context) { if (!this.context) {
throw new Error("No canvas to fetch context for") throw new Error("No canvas to fetch context for");
} }
this.context.save(); this.context.save();
@ -134,8 +155,7 @@
}; };
planet.projection = d3.geo.orthographic() planet.projection = d3.geo.orthographic()
.clipAngle(90) .clipAngle(90);
.precision(0);
planet.path = d3.geo.path().projection(planet.projection); planet.path = d3.geo.path().projection(planet.projection);
return planet; return planet;
@ -144,17 +164,19 @@
planetaryjs.plugins.topojson = function(config) { planetaryjs.plugins.topojson = function(config) {
return function(planet) { return function(planet) {
planet.plugins.topojson = {};
planet.onInit(function(done) { planet.onInit(function(done) {
if (config.world) { if (config.world) {
planet.world = config.world; planet.plugins.topojson.world = config.world;
setTimeout(done, 0); setTimeout(done, 0);
} else { } else {
var file = config.file || 'world-110m.json' var file = config.file || 'world-110m.json';
d3.json(file, function(err, world) { d3.json(file, function(err, world) {
if (err) { if (err) {
throw new Error("Could not load JSON " + file); throw new Error("Could not load JSON " + file);
} }
planet.world = world; planet.plugins.topojson.world = world;
done(); done();
}); });
} }
@ -171,11 +193,6 @@
context.fillStyle = config.fill || 'black'; context.fillStyle = config.fill || 'black';
context.fill(); context.fill();
if (config.stroke != false) {
context.strokeStyle = config.stroke;
context.stroke();
}
}); });
}); });
}; };
@ -186,20 +203,22 @@
var land = null; var land = null;
planet.onInit(function() { planet.onInit(function() {
land = topojson.feature(planet.world, planet.world.objects.land); var world = planet.plugins.topojson.world;
}) land = topojson.feature(world, world.objects.land);
});
planet.onDraw(function() { planet.onDraw(function() {
planet.withSavedContext(function(context) { planet.withSavedContext(function(context) {
context.beginPath(); context.beginPath();
planet.path.context(context)(land); planet.path.context(context)(land);
if (config.fill != false) { if (config.fill !== false) {
context.fillStyle = config.fill || 'white'; context.fillStyle = config.fill || 'white';
context.fill(); context.fill();
} }
if (config.stroke) { if (config.stroke) {
if (config.lineWidth) context.lineWidth = config.lineWidth;
context.strokeStyle = config.stroke; context.strokeStyle = config.stroke;
context.stroke(); context.stroke();
} }
@ -211,11 +230,23 @@
planetaryjs.plugins.borders = function(config) { planetaryjs.plugins.borders = function(config) {
return function(planet) { return function(planet) {
var borders = null; var borders = null;
planet.onInit(function() { var borderFns = {
var countries = planet.world.objects.countries; internal: function(a, b) {
borders = topojson.mesh(planet.world, countries, function(a, b) {
return a.id !== b.id; return a.id !== b.id;
}); },
external: function(a, b) {
return a.id === b.id;
},
both: function(a, b) {
return true;
}
};
planet.onInit(function() {
var world = planet.plugins.topojson.world;
var countries = world.objects.countries;
var type = config.type || 'internal';
borders = topojson.mesh(world, countries, borderFns[type]);
}); });
planet.onDraw(function() { planet.onDraw(function() {
@ -223,6 +254,7 @@
context.beginPath(); context.beginPath();
planet.path.context(context)(borders); planet.path.context(context)(borders);
context.strokeStyle = config.stroke || 'gray'; context.strokeStyle = config.stroke || 'gray';
if (config.lineWidth) context.lineWidth = config.lineWidth;
context.stroke(); context.stroke();
}); });
}); });
@ -230,7 +262,7 @@
}; };
planetaryjs.plugins.earth = function(config) { planetaryjs.plugins.earth = function(config) {
var config = config || {}; config = config || {};
var topojsonOptions = config.topojson || {}; var topojsonOptions = config.topojson || {};
var oceanOptions = config.oceans || {}; var oceanOptions = config.oceans || {};
var landOptions = config.land || {}; var landOptions = config.land || {};
@ -246,13 +278,22 @@
planetaryjs.plugins.pings = function(config) { planetaryjs.plugins.pings = function(config) {
var pings = []; var pings = [];
config = config || {};
var addPing = function(lat, lng, options) { var addPing = function(lng, lat, options) {
var options = options || {}; options = options || {};
options.color = options.color || 'white'; options.color = options.color || config.color || 'white';
options.ttl = options.ttl || 2000; options.angle = options.angle || config.angle || 5;
options.angle = options.angle || 5; options.ttl = options.ttl || config.ttl || 2000;
pings.push({ lat: lat, lng: lng, time: new Date(), options: options }); var ping = { time: new Date(), options: options };
if (config.latitudeFirst) {
ping.lat = lng;
ping.lng = lat;
} else {
ping.lng = lng;
ping.lat = lat;
}
pings.push(ping);
}; };
var drawPings = function(planet, context, now) { var drawPings = function(planet, context, now) {
@ -294,5 +335,76 @@
}; };
}; };
planetaryjs.plugins.zoom = function (options) {
options = options || {};
var noop = function() {};
var onZoomStart = options.onZoomStart || noop;
var onZoomEnd = options.onZoomEnd || noop;
var onZoom = options.onZoom || noop;
var afterZoom = options.afterZoom || noop;
var startScale = options.initialScale;
var scaleExtent = options.scaleExtent || [50, 2000];
return function(planet) {
planet.onInit(function() {
var zoom = d3.behavior.zoom()
.scaleExtent(scaleExtent);
if (startScale !== null && startScale !== undefined) {
zoom.scale(startScale);
} else {
zoom.scale(planet.projection.scale());
}
zoom
.on('zoomstart', onZoomStart.bind(planet))
.on('zoomend', onZoomEnd.bind(planet))
.on('zoom', function() {
onZoom.call(planet);
planet.projection.scale(d3.event.scale);
afterZoom.call(planet);
});
d3.select(planet.canvas).call(zoom);
});
};
};
planetaryjs.plugins.drag = function(options) {
options = options || {};
var noop = function() {};
var onDragStart = options.onDragStart || noop;
var onDragEnd = options.onDragEnd || noop;
var onDrag = options.onDrag || noop;
var afterDrag = options.afterDrag || noop;
return function(planet) {
planet.onInit(function() {
var drag = d3.behavior.drag()
.on('dragstart', onDragStart.bind(planet))
.on('dragend', onDragEnd.bind(planet))
.on('drag', function() {
onDrag.call(planet);
var dx = d3.event.dx;
var dy = d3.event.dy;
var rotation = planet.projection.rotate();
var radius = planet.projection.scale();
var scale = d3.scale.linear()
.domain([-1 * radius, radius])
.range([-90, 90]);
var degX = scale(dx);
var degY = scale(dy);
rotation[0] += degX;
rotation[1] -= degY;
if (rotation[1] > 90) rotation[1] = 90;
if (rotation[1] < -90) rotation[1] = -90;
if (rotation[0] >= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
afterDrag.call(planet);
});
d3.select(planet.canvas).call(drag);
});
};
};
return planetaryjs; return planetaryjs;
})); }));

View File

@ -1,2 +1,2 @@
/*! Planetary.js 0.0.0 | (c) 2013 Brandon Tilley | Released under MIT License */ /*! Planetary.js 1.1.3 | (c) 2013 Michelle Tilley | Released under MIT License */
!function(n,t){"function"==typeof define&&define.amd?define(["d3","topojson"],t):"object"==typeof exports?module.exports=t(require("d3"),require("topojson")):n.planetaryjs=t(n.d3,n.topojson,n)}(this,function(n,t,o){"use strict";var e=null;o&&(e=o.planetaryjs);var i=[],r=function(t,o,e){n.timer(function(){t.context.clearRect(0,0,o.width,o.height);for(var n=0;n<e.onDraw.length;n++)e.onDraw[n]()})},l=function(n,t){for(var o=0;o<i.length;o++)t.unshift(i[o]);0==t.length&&(s.plugins.earth&&n.loadPlugin(s.plugins.earth()),s.plugins.pings&&n.loadPlugin(s.plugins.pings()));for(var o=0;o<t.length;o++)t[o](n)},u=function(n,t,o){if(o.onInit.length){var e=0,i=function(n){var t=o.onInit[e];t.length?t(function(){e++,n()}):(t(),e++,setTimeout(n,0))},l=function(){e>=o.onInit.length?r(n,t,o):i(l)};i(l)}else r(n,t,o)},a=function(n,t,o,e){l(n,o),n.canvas=t,n.context=t.getContext("2d"),u(n,t,e)},s={plugins:{},noConflict:function(){return o.planetaryjs=e,s},loadPlugin:function(n){i.push(n)},planet:function(){var t=[],o={onInit:[],onDraw:[]},e={plugins:{},draw:function(n){a(e,n,t,o)},onInit:function(n){o.onInit.push(n)},onDraw:function(n){o.onDraw.push(n)},loadPlugin:function(n){t.push(n)},withSavedContext:function(n){if(!this.context)throw new Error("No canvas to fetch context for");this.context.save(),n(this.context),this.context.restore()}};return e.projection=n.geo.orthographic().clipAngle(90).precision(0),e.path=n.geo.path().projection(e.projection),e}};return s.plugins.topojson=function(t){return function(o){o.onInit(function(e){if(t.world)o.world=t.world,setTimeout(e,0);else{var i=t.file||"world-110m.json";n.json(i,function(n,t){if(n)throw new Error("Could not load JSON "+i);o.world=t,e()})}})}},s.plugins.oceans=function(n){return function(t){t.onDraw(function(){t.withSavedContext(function(o){o.beginPath(),t.path.context(o)({type:"Sphere"}),o.fillStyle=n.fill||"black",o.fill(),0!=n.stroke&&(o.strokeStyle=n.stroke,o.stroke())})})}},s.plugins.land=function(n){return function(o){var e=null;o.onInit(function(){e=t.feature(o.world,o.world.objects.land)}),o.onDraw(function(){o.withSavedContext(function(t){t.beginPath(),o.path.context(t)(e),0!=n.fill&&(t.fillStyle=n.fill||"white",t.fill()),n.stroke&&(t.strokeStyle=n.stroke,t.stroke())})})}},s.plugins.borders=function(n){return function(o){var e=null;o.onInit(function(){var n=o.world.objects.countries;e=t.mesh(o.world,n,function(n,t){return n.id!==t.id})}),o.onDraw(function(){o.withSavedContext(function(t){t.beginPath(),o.path.context(t)(e),t.strokeStyle=n.stroke||"gray",t.stroke()})})}},s.plugins.earth=function(n){var n=n||{},t=n.topojson||{},o=n.oceans||{},e=n.land||{},i=n.borders||{};return function(n){s.plugins.topojson(t)(n),s.plugins.oceans(o)(n),s.plugins.land(e)(n),s.plugins.borders(i)(n)}},s.plugins.pings=function(){var t=[],o=function(n,o,e){var e=e||{};e.color=e.color||"white",e.ttl=e.ttl||2e3,e.angle=e.angle||5,t.push({lat:n,lng:o,time:new Date,options:e})},e=function(n,o,e){for(var r=[],l=0;l<t.length;l++){var u=t[l],a=e-u.time;a<u.options.ttl&&(r.push(u),i(n,o,e,a,u))}t=r},i=function(t,o,e,i,r){var l=1-i/r.options.ttl,u=n.rgb(r.options.color);u="rgba("+u.r+","+u.g+","+u.b+","+l+")",o.strokeStyle=u;var a=n.geo.circle().origin([r.lng,r.lat]).angle(i/r.options.ttl*r.options.angle)();o.beginPath(),t.path.context(o)(a),o.stroke()};return function(n){n.plugins.pings={add:o},n.onDraw(function(){var t=new Date;n.withSavedContext(function(o){e(n,o,t)})})}},s}); !function(n,t){"function"==typeof define&&define.amd?define(["d3","topojson"],function(o,e){return n.planetaryjs=t(o,e,n)}):"object"==typeof exports?module.exports=t(require("d3"),require("topojson")):n.planetaryjs=t(n.d3,n.topojson,n)}(this,function(n,t,o){"use strict";var e=null;o&&(e=o.planetaryjs);var i=[],r=function(t,o,e){n.timer(function(){if(t.stopped)return!0;t.context.clearRect(0,0,o.width,o.height);for(var n=0;n<e.onDraw.length;n++)e.onDraw[n]()})},l=function(n,t){for(var o=i.length-1;o>=0;o--)t.unshift(i[o]);for(0===t.length&&(c.plugins.earth&&n.loadPlugin(c.plugins.earth()),c.plugins.pings&&n.loadPlugin(c.plugins.pings())),o=0;o<t.length;o++)t[o](n)},a=function(n,t,o){if(o.onInit.length){var e=0,i=function(n){var t=o.onInit[e];t.length?t(function(){e++,n()}):(t(),e++,setTimeout(n,0))},l=function(){e>=o.onInit.length?r(n,t,o):i(l)};i(l)}else r(n,t,o)},u=function(n,t,o,e){n.canvas=t,n.context=t.getContext("2d"),n.stopped!==!0&&l(n,o),n.stopped=!1,a(n,t,e)},c={plugins:{},noConflict:function(){return o.planetaryjs=e,c},loadPlugin:function(n){i.push(n)},planet:function(){var t=[],o={onInit:[],onDraw:[],onStop:[]},e={plugins:{},draw:function(n){u(e,n,t,o)},onInit:function(n){o.onInit.push(n)},onDraw:function(n){o.onDraw.push(n)},onStop:function(n){o.onStop.push(n)},loadPlugin:function(n){t.push(n)},stop:function(){e.stopped=!0;for(var n=0;n<o.onStop.length;n++)o.onStop[n](e)},withSavedContext:function(n){if(!this.context)throw new Error("No canvas to fetch context for");this.context.save(),n(this.context),this.context.restore()}};return e.projection=n.geo.orthographic().clipAngle(90),e.path=n.geo.path().projection(e.projection),e}};return c.plugins.topojson=function(t){return function(o){o.plugins.topojson={},o.onInit(function(e){if(t.world)o.plugins.topojson.world=t.world,setTimeout(e,0);else{var i=t.file||"world-110m.json";n.json(i,function(n,t){if(n)throw new Error("Could not load JSON "+i);o.plugins.topojson.world=t,e()})}})}},c.plugins.oceans=function(n){return function(t){t.onDraw(function(){t.withSavedContext(function(o){o.beginPath(),t.path.context(o)({type:"Sphere"}),o.fillStyle=n.fill||"black",o.fill()})})}},c.plugins.land=function(n){return function(o){var e=null;o.onInit(function(){var n=o.plugins.topojson.world;e=t.feature(n,n.objects.land)}),o.onDraw(function(){o.withSavedContext(function(t){t.beginPath(),o.path.context(t)(e),n.fill!==!1&&(t.fillStyle=n.fill||"white",t.fill()),n.stroke&&(n.lineWidth&&(t.lineWidth=n.lineWidth),t.strokeStyle=n.stroke,t.stroke())})})}},c.plugins.borders=function(n){return function(o){var e=null,i={internal:function(n,t){return n.id!==t.id},external:function(n,t){return n.id===t.id},both:function(){return!0}};o.onInit(function(){var r=o.plugins.topojson.world,l=r.objects.countries,a=n.type||"internal";e=t.mesh(r,l,i[a])}),o.onDraw(function(){o.withSavedContext(function(t){t.beginPath(),o.path.context(t)(e),t.strokeStyle=n.stroke||"gray",n.lineWidth&&(t.lineWidth=n.lineWidth),t.stroke()})})}},c.plugins.earth=function(n){n=n||{};var t=n.topojson||{},o=n.oceans||{},e=n.land||{},i=n.borders||{};return function(n){c.plugins.topojson(t)(n),c.plugins.oceans(o)(n),c.plugins.land(e)(n),c.plugins.borders(i)(n)}},c.plugins.pings=function(t){var o=[];t=t||{};var e=function(n,e,i){i=i||{},i.color=i.color||t.color||"white",i.angle=i.angle||t.angle||5,i.ttl=i.ttl||t.ttl||2e3;var r={time:new Date,options:i};t.latitudeFirst?(r.lat=n,r.lng=e):(r.lng=n,r.lat=e),o.push(r)},i=function(n,t,e){for(var i=[],l=0;l<o.length;l++){var a=o[l],u=e-a.time;u<a.options.ttl&&(i.push(a),r(n,t,e,u,a))}o=i},r=function(t,o,e,i,r){var l=1-i/r.options.ttl,a=n.rgb(r.options.color);a="rgba("+a.r+","+a.g+","+a.b+","+l+")",o.strokeStyle=a;var u=n.geo.circle().origin([r.lng,r.lat]).angle(i/r.options.ttl*r.options.angle)();o.beginPath(),t.path.context(o)(u),o.stroke()};return function(n){n.plugins.pings={add:e},n.onDraw(function(){var t=new Date;n.withSavedContext(function(o){i(n,o,t)})})}},c.plugins.zoom=function(t){t=t||{};var o=function(){},e=t.onZoomStart||o,i=t.onZoomEnd||o,r=t.onZoom||o,l=t.afterZoom||o,a=t.initialScale,u=t.scaleExtent||[50,2e3];return function(t){t.onInit(function(){var o=n.behavior.zoom().scaleExtent(u);null!==a&&void 0!==a?o.scale(a):o.scale(t.projection.scale()),o.on("zoomstart",e.bind(t)).on("zoomend",i.bind(t)).on("zoom",function(){r.call(t),t.projection.scale(n.event.scale),l.call(t)}),n.select(t.canvas).call(o)})}},c.plugins.drag=function(t){t=t||{};var o=function(){},e=t.onDragStart||o,i=t.onDragEnd||o,r=t.onDrag||o,l=t.afterDrag||o;return function(t){t.onInit(function(){var o=n.behavior.drag().on("dragstart",e.bind(t)).on("dragend",i.bind(t)).on("drag",function(){r.call(t);var o=n.event.dx,e=n.event.dy,i=t.projection.rotate(),a=t.projection.scale(),u=n.scale.linear().domain([-1*a,a]).range([-90,90]),c=u(o),s=u(e);i[0]+=c,i[1]-=s,i[1]>90&&(i[1]=90),i[1]<-90&&(i[1]=-90),i[0]>=180&&(i[0]-=360),t.projection.rotate(i),l.call(t)});n.select(t.canvas).call(o)})}},c});

File diff suppressed because one or more lines are too long

View File

@ -3,16 +3,19 @@ var uglify = require('gulp-uglify');
var concat = require('gulp-concat'); var concat = require('gulp-concat');
var rename = require('gulp-rename'); var rename = require('gulp-rename');
var header = require('gulp-header'); var header = require('gulp-header');
var jshint = require('gulp-jshint');
var replace = require('gulp-replace');
var metadata = require('./package.json'); var metadata = require('./package.json');
var shortHeader = "/*! Planetary.js {{version}} | (c) 2013 Brandon Tilley | Released under MIT License */" var shortHeader = "/*! Planetary.js <%= version %> | (c) 2013 Michelle Tilley | Released under MIT License */\n"
var fullHeader = [ var fullHeader = [
"/*! Planetary.js v{{version}}", "/*! Planetary.js v<%= version %>",
" * Copyright (c) 2013 Brandon Tilley", " * Copyright (c) 2013 Michelle Tilley",
" *", " *",
" * Released under the MIT license", " * Released under the MIT license",
" * Date: {{now}}", " * Date: <%= new Date().toISOString() %>",
" */" " */",
""
].join("\n"); ].join("\n");
var fullSource = gulp.src(['./src/_umd_header.js', './src/body.js', './src/plugins.js', './src/_umd_footer.js']); var fullSource = gulp.src(['./src/_umd_header.js', './src/body.js', './src/plugins.js', './src/_umd_footer.js']);
@ -22,9 +25,15 @@ function build(source, name, headerText, minify) {
var js = source.pipe(concat(name)); var js = source.pipe(concat(name));
if (minify) { js = js.pipe(uglify()); } if (minify) { js = js.pipe(uglify()); }
js = js.pipe(header(headerText, { version: metadata.version })); js = js.pipe(header(headerText, { version: metadata.version }));
js.pipe(gulp.dest('./dist')); js.pipe(replace("\r\n", "\n")).pipe(gulp.dest('./dist'));
} }
gulp.task('jshint', function() {
gulp.src(['./src/body.js', './src/plugins.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('build', function() { gulp.task('build', function() {
build(fullSource, 'planetaryjs.js', fullHeader, false); build(fullSource, 'planetaryjs.js', fullHeader, false);
build(fullSource, 'planetaryjs.min.js', shortHeader, true); build(fullSource, 'planetaryjs.min.js', shortHeader, true);
@ -34,6 +43,4 @@ gulp.task('build', function() {
gulp.src('./src/world-110m.json').pipe(gulp.dest('./dist')); gulp.src('./src/world-110m.json').pipe(gulp.dest('./dist'));
}); });
gulp.task('default', function() { gulp.task('default', ['jshint', 'build']);
gulp.run('build');
});

4222
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +1,35 @@
{ {
"name": "planetary.js", "name": "planetary.js",
"version": "0.1.1", "version": "1.1.3",
"description": "Awesome interactive globes for the web", "description": "Awesome interactive globes for the web",
"main": "dist/planetaryjs",
"scripts": { "scripts": {
"build": "rm -r dist/ ; gulp && cp dist/planetaryjs.min.js site/public/js/lib", "build": "rm -r dist/ ; gulp && cp dist/planetaryjs.min.js site/public/js/lib",
"jshint": "gulp jshint",
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git://github.com/BinaryMuse/planetary.js.git" "url": "git://github.com/BinaryMuse/planetary.js.git"
}, },
"author": "Brandon Tilley <brandon@brandontilley.com>", "author": "Michelle Tilley <michelle@michelletilley.net>",
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {
"url": "https://github.com/BinaryMuse/planetary.js/issues" "url": "https://github.com/BinaryMuse/planetary.js/issues"
}, },
"homepage": "http://planetaryjs.com", "homepage": "http://planetaryjs.com",
"devDependencies": { "devDependencies": {
"gulp": "~3.2.0", "gulp": "~3.6.2",
"gulp-concat": "BinaryMuse/gulp-concat", "gulp-concat": "BinaryMuse/gulp-concat",
"gulp-header": "~0.4.0", "gulp-header": "~1.0.2",
"gulp-uglify": "~0.1.0", "gulp-uglify": "~0.3.0",
"gulp-rename": "~0.2.1", "gulp-rename": "~1.2.0",
"bower": "~1.2.8" "bower": "~1.2.8",
"gulp-jshint": "~1.6.1",
"gulp-replace": "~0.3.0"
},
"dependencies": {
"topojson": "^1.4.6",
"d3": "^3.3.13"
} }
} }

39
script/set-version Executable file
View File

@ -0,0 +1,39 @@
#!/usr/bin/env node
var fs = require('fs');
var spawn = require('child_process').spawn;
var type = process.argv[2];
var version = process.argv[3];
if ("stable" !== type && "unstable" !== type) {
console.log("You must specify 'stable' or 'unstable' version type.");
process.exit(1);
}
if (!version) {
console.log("You must specify a version.");
process.exit(1);
}
if (version[0] === 'v') {
version = version.replace(/^v/, '');
}
var package = require("../package.json");
var bower = require("../bower.json");
var site = require("../site/public/download/_data.json");
package.version = version;
bower.version = version;
site[type].latest = site[type].latest || {};
site[type].latest.version = "v" + version;
fs.writeFileSync('package.json', JSON.stringify(package, null, ' ') + "\n");
fs.writeFileSync('bower.json', JSON.stringify(bower, null, ' ') + "\n");
fs.writeFileSync('site/public/download/_data.json', JSON.stringify(site, null, ' ') + "\n");
spawn('npm', ['run', 'build']);
console.log("Tasks:\n\n - Update CHANGELOG.md\n - Regenerate site\n - Create release on GH");

View File

@ -8,4 +8,4 @@ Building
1. Install [Node.js](http://nodejs.org/) 1. Install [Node.js](http://nodejs.org/)
2. Install the local dependencies with `npm install` 2. Install the local dependencies with `npm install`
3. Run the development server with `npm start` (stars on port 9000) or compile the site to `www` with `npm run compile` 3. Run the development server with `npm start` (starts on port 9000) or compile the site to `www` with `npm run compile`

View File

@ -9,7 +9,7 @@
"start": "harp server", "start": "harp server",
"compile": "harp compile" "compile": "harp compile"
}, },
"author": "Brandon Tilley <brandon@brandontilley.com>", "author": "Michelle Tilley <michelle@michelletilley.net>",
"license": "MIT", "license": "MIT",
"private": true, "private": true,
"dependencies": { "dependencies": {

View File

@ -1,11 +0,0 @@
Planetary.js Site
=================
This is the source for the Planetary.js web site.
Building
--------
1. Install [Node.js](http://nodejs.org/)
2. Install the local dependencies with `npm install`
3. Run the development server with `npm start` (stars on port 9000) or compile the site to `www` with `npm run compile`

9
site/public/_ga.ejs Normal file
View File

@ -0,0 +1,9 @@
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-46705270-1', 'planetaryjs.com');
ga('send', 'pageview');
</script>

10
site/public/_header.ejs Normal file
View File

@ -0,0 +1,10 @@
<title>Planetary.js: Awesome interactive globes for the web</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700|Open+Sans:300italic,400,300,700' rel='stylesheet' type='text/css'>
<link type="text/css" rel="stylesheet" href="/semantic/css/semantic.min.css">
<link type="text/css" rel="stylesheet" href="/css/planetaryjs.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta property="og:image" content="http://planetaryjs.com/images/ex-rotating.png">
<meta property="og:site_name" content="Planetary.js">

View File

@ -1,43 +1,17 @@
<!doctype html> <!doctype html>
<html> <html>
<head> <head>
<title>Planetary.js</title> <%- partial("_header") %>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700|Open+Sans:300italic,400,300,700' rel='stylesheet' type='text/css'>
<link type="text/css" rel="stylesheet" href="semantic/css/semantic.min.css">
<link type="text/css" rel="stylesheet" href="css/planetaryjs.css">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
</head> </head>
<body> <body>
<div class='ui fixed inverted large menu main-menu'> <%- partial("_menu") %>
<div class='items'>
<a class='item title' href='index.html'>
<i class='globe icon'></i>Planetary.js
</a>
<span class='spacer hide-on-mobile'></span>
<a class='item minor' href='https://github.com/BinaryMuse/planetary.js/releases'>
<i class='download icon'></i><span class='hide-on-mobile'>Download</span>
</a>
<a class='item minor' href='examples.html'>
<i class='laptop icon'></i><span class='hide-on-mobile'>Examples</span>
</a>
<a class='item minor' href='examples.html'>
<i class='book icon'></i><span class='hide-on-mobile'>Documentation</span>
</a>
<a class='item minor' href='https://github.com/BinaryMuse/planetary.js'>
<i class='github alternate icon'></i><span class='hide-on-mobile'>Fork on GitHub</span>
</a>
</div>
</div>
<div class='content container'> <div class='content container'>
<%- yield %> <%- yield %>
</div> </div>
<script type='text/javascript' src="js/lib/d3.v3.min.js"></script>
<script type='text/javascript' src="js/lib/topojson.v1.min.js"></script> <%- partial("_scripts") %>
<script type="text/javascript" src="js/lib/planetaryjs.min.js"></script>
<script type="text/javascript" src="js/homepage.js"></script> <script type="text/javascript" src="js/homepage.js"></script>
<%- partial("_ga") %>
</body> </body>
</html> </html>

21
site/public/_menu.ejs Normal file
View File

@ -0,0 +1,21 @@
<div class='ui fixed inverted large menu main-menu'>
<div class='items'>
<a class='item title' href='/'>
<i class='globe icon'></i>Planetary.js
</a>
<span class='spacer hide-on-mobile'></span>
<a class='item minor <%- current.path[0] == 'download' ? 'active' : '' %>' href='/download/'>
<i class='download icon'></i><span class='hide-on-mobile'>Download</span>
</a>
<a class='item minor <%- current.path[0] == 'examples' ? 'active' : '' %>' href='/examples/'>
<i class='laptop icon'></i><span class='hide-on-mobile'>Examples</span>
</a>
<a class='item minor <%- current.path[0] == 'documentation' ? 'active' : '' %>' href='/documentation/'>
<i class='book icon'></i><span class='hide-on-mobile'>Documentation</span>
</a>
<a class='item minor' href='https://github.com/BinaryMuse/planetary.js'
onclick="_gaq.push(['_trackPageview', '/redirect-to-github-project-page']);">
<i class='github alternate icon'></i><span class='hide-on-mobile'>Fork on GitHub</span>
</a>
</div>
</div>

3
site/public/_scripts.ejs Normal file
View File

@ -0,0 +1,3 @@
<script type='text/javascript' src="/js/lib/d3.v3.min.js"></script>
<script type='text/javascript' src="/js/lib/topojson.v1.min.js"></script>
<script type="text/javascript" src="/js/lib/planetaryjs.min.js"></script>

View File

@ -0,0 +1,10 @@
<html>
<head>
<title>Planetary.js AMD Test</title>
</head>
<body>
<canvas id='globe' width='500' height='500'></canavs>
<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.9/require.min.js"
data-main="/amd/test.js"></script>
</body>
</html>

View File

24
site/public/amd/test.js Normal file
View File

@ -0,0 +1,24 @@
requirejs.config({
baseUrl: '/js/lib',
shim: {
d3: { exports: 'd3' },
topojson: { exports: 'topojson' }
},
paths: {
"d3": 'd3.v3.min',
"topojson": 'topojson.v1.min'
}
});
requirejs(['planetaryjs.min'], function(planetaryjs) {
var planet = planetaryjs.planet();
// You can remove this statement if `world-110m.json`
// is in the same path as the HTML page:
planet.loadPlugin(planetaryjs.plugins.earth({
topojson: { file: '/world-110m.json' }
}));
// Make the planet fit well in its canvas
planet.projection.scale(250).translate([250, 250]);
var canvas = document.getElementById('globe');
planet.draw(canvas);
});

View File

@ -23,13 +23,19 @@ h1.title-header, h2.title-header {
.content.container { .content.container {
padding-top: 50px; padding-top: 50px;
.slim {
max-width: 1108px;
padding: 0 20px;
margin: 0 auto;
}
} }
.centered { .centered {
text-align: center; text-align: center;
} }
.feature-list { .feature-list, .download-list {
font-size: 17px; font-size: 17px;
.icon { .icon {
@ -37,6 +43,10 @@ h1.title-header, h2.title-header {
} }
} }
.ui.label.bower {
text-transform: none;
}
a.ui.icon.header { a.ui.icon.header {
text-decoration: none; text-decoration: none;
color: black; color: black;
@ -46,6 +56,10 @@ a.ui.icon.header {
} }
} }
.section-description {
min-height: 40px;
}
.divider { .divider {
.icon.huge { .icon.huge {
font-size: 2em; font-size: 2em;
@ -58,9 +72,10 @@ a.ui.icon.header {
} }
} }
canvas { canvas#homepage-globe-canvas {
width: 350px; width: 350px;
height: 350px; height: 350px;
cursor: move;
} }
@media screen and (max-width: 768px) { @media screen and (max-width: 768px) {
@ -68,12 +83,20 @@ canvas {
display: none !important; display: none !important;
} }
.ui.grid > .eight.wide.column { .ui.grid > .wide.column {
width: auto !important; width: auto !important;
min-width: 100%; min-width: 100%;
} }
} }
.column {
h1:first-child {
padding-top: 0;
margin-top: 0;
}
}
@media screen and (min-width: 769px) { @media screen and (min-width: 769px) {
.hide-on-non-mobile { .hide-on-non-mobile {
display: none !important; display: none !important;
@ -108,6 +131,55 @@ canvas {
} }
} }
.ui.dark.blue.label {
background-color: #000080 !important;
margin-top: 5px;
&:before {
background-color: #000080 !important;
}
}
.no-underline { .no-underline {
text-decoration: none; text-decoration: none;
} }
.example-segment {
.horizontal.label {
margin-top: 5px;
}
img {
width: 200px;
height: 200px;
float: left;
margin-right: 20px;
@media screen and (max-width: 768px) {
display: block;
float: none;
}
}
}
.ui.menu .item.contains-subitems {
padding-top: 0;
padding-bottom: 0;
margin-top: 0;
&:before {
width: 0;
height: 0;
}
}
pre {
font-size: 14px;
overflow-x: auto;
}
.ui.items.examples {
a.item {
text-decoration: none;
}
}

166
site/public/css/prism.css Normal file
View File

@ -0,0 +1,166 @@
/**
* prism.js default theme for JavaScript, CSS and HTML
* Based on dabblet (http://dabblet.com)
* @author Lea Verou
*/
code[class*="language-"],
pre[class*="language-"] {
color: black;
text-shadow: 0 1px white;
font-family: Consolas, Monaco, 'Andale Mono', monospace;
direction: ltr;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection,
code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection {
text-shadow: none;
background: #b3d4fc;
}
pre[class*="language-"]::selection, pre[class*="language-"] ::selection,
code[class*="language-"]::selection, code[class*="language-"] ::selection {
text-shadow: none;
background: #b3d4fc;
}
@media print {
code[class*="language-"],
pre[class*="language-"] {
text-shadow: none;
}
}
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: .5em 0;
overflow: auto;
}
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
/* background: #f5f2f0; */
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: .1em;
border-radius: .3em;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: slategray;
}
.token.punctuation {
color: #999;
}
.namespace {
opacity: .7;
}
.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol {
color: #905;
}
.token.selector,
.token.attr-name,
.token.string,
.token.builtin {
color: #690;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string,
.token.variable {
color: #a67f59;
background: hsla(0,0%,100%,.5);
}
.token.atrule,
.token.attr-value,
.token.keyword {
color: #07a;
}
.token.regex,
.token.important {
color: #e90;
}
.token.important {
font-weight: bold;
}
.token.entity {
cursor: help;
}
pre.line-numbers {
position: relative;
padding-left: 3.8em;
counter-reset: linenumber;
}
pre.line-numbers > code {
position: relative;
}
.line-numbers .line-numbers-rows {
position: absolute;
pointer-events: none;
top: 0;
font-size: 100%;
left: -3.8em;
width: 3em; /* works for line-numbers below 1000 lines */
letter-spacing: -1px;
border-right: 1px solid #999;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.line-numbers-rows > span {
pointer-events: none;
display: block;
counter-increment: linenumber;
}
.line-numbers-rows > span:before {
content: counter(linenumber);
color: #999;
display: block;
padding-right: 0.8em;
text-align: right;
}

View File

@ -0,0 +1,69 @@
<!doctype html>
<html>
<head>
<%- partial("../_header") %>
<link href="/css/prism.css" rel="stylesheet">
</head>
<body>
<%- partial("../_menu") %>
<div class='content container'>
<div class='page ui slim stackable grid'>
<div class='four wide column'>
<div class='ui fluid vertical menu'>
<a class='red item <%- current.source == 'index' ? 'active' : '' %>' href='/documentation/index.html'>
Introduction
<i class='icon home'></i>
</a>
<a class='purple item <%- current.source == 'installation' ? 'active' : '' %>' href='/documentation/installation.html'>
Installation
<i class='icon download'></i>
</a>
<a class='blue item <%- current.source == 'core' ? 'active' : '' %>' href='/documentation/core.html'>
Core API
<i class='icon setting'></i>
</a>
<a class='orange item <%- current.source == 'planet' ? 'active' : '' %>' href='/documentation/planet.html'>
Planet API
<i class='icon globe'></i>
</a>
<a class='teal item <%- current.source == 'plugins' ? 'active' : '' %>' href='/documentation/plugins.html'>
Plugins
<i class='icon edit'></i>
</a>
<a class='purple item with-subitems <%- current.source == 'builtin' ? 'active' : '' %>' href='/documentation/builtin.html'>
Built-In Plugins
<i class='icon bolt'></i>
</a>
<div class='item contains-subitems'>
<div class='menu'>
<a class='item <%- current.source == 'builtin_earth' ? 'active' : '' %>' href='/documentation/builtin_earth.html'>Earth</a>
<a class='item <%- current.source == 'builtin_topojson' ? 'active' : '' %>' href='/documentation/builtin_topojson.html'>TopoJSON</a>
<a class='item <%- current.source == 'builtin_oceans' ? 'active' : '' %>' href='/documentation/builtin_oceans.html'>Oceans</a>
<a class='item <%- current.source == 'builtin_land' ? 'active' : '' %>' href='/documentation/builtin_land.html'>Land</a>
<a class='item <%- current.source == 'builtin_borders' ? 'active' : '' %>' href='/documentation/builtin_borders.html'>Borders</a>
<a class='item <%- current.source == 'builtin_pings' ? 'active' : '' %>' href='/documentation/builtin_pings.html'>Pings</a>
<a class='item <%- current.source == 'builtin_zoom' ? 'active' : '' %>' href='/documentation/builtin_zoom.html'>Zoom</a>
<a class='item <%- current.source == 'builtin_drag' ? 'active' : '' %>' href='/documentation/builtin_drag.html'>Drag</a>
</div>
</div>
<a class='red item <%- current.source == 'faq' ? 'active' : '' %>' href='/documentation/faq.html'>
FAQ
<i class='icon help'></i>
</a>
<a class='green item <%- current.source == 'help' ? 'active' : '' %>' href='/documentation/help.html'>
Getting Help
<i class='icon phone'></i>
</a>
</div>
</div>
<div class='twelve wide column'>
<%- yield %>
</div>
</div>
</div>
<script type='text/javascript' src='/js/prism.js'></script>
<%- partial("../_ga") %>
</body>
</html>

View File

@ -0,0 +1,17 @@
Built-In Plugins
================
Planetary.js comes with several built-in plugins that provide a base set of functionality. (Note that the `planetaryjs-noplugins.js` file, as its name suggests, does not include the plugins). They are described in detail on their own pages, but are:
* [Earth](/documentation/builtin_earth.html) - a combination of the `topojson`, `oceans`, `land`, and `borders` plugins.
* [TopoJSON](/documentation/builtin_topojson.html) - loads TopoJSON data via Ajax (or via configuration) and makes it available for use by other plugins
* [Oceans](/documentation/builtin_oceans.html) - fills in the globe with a solid color
* [Land](/documentation/builtin_land.html) - uses data from the `topojson` plugin to draw Earth's land masses
* [Borders](/documentation/builtin_borders.html) - uses data from the `topojson` plugin to draw borders between Earth's countries
* [Pings](/documentation/builtin_pings.html) - draws animated, circular pings on the globe
* [Zoom](/documentation/builtin_zoom.html) - enables mouse-based zooming of the globe via the mouse wheel
* [Drag](/documentation/builtin_drag.html) - enables mouse-based rotation of the globe via dragging
Built-in plugins are exposed as properties on `planetaryjs.plugins`.
If you do not specify any plugins (globally or per-instance), Planetary.js will use the `earth` and `pings` plugins with their default settings.

View File

@ -0,0 +1,30 @@
Borders Plugin
==============
The `borders` plugin renders the borders around (and between) countries. It uses TopoJSON data published to `planet.plugins.topojson.world` by the [TopoJSON plugin](/documentation/builtin_topojson.html). It uses the feature at `objects.countries` in the TopoJSON object to calculate the borders.
API
---
**`planetaryjs.plugins.borders([config])`**
Valid keys for `config` are:
* `stroke`: the `strokeStyle` to use for the context; defaults to `"gray"`
* `lineWidth` the `lineWidth` to set on the context; defaults to no value, and the context's `lineWidth` is not modified
* `type`: valid options are `"internal"`, `"external"`, or `"both"`. `"internal"` draws borders between countries but not coastlines; `"external"` does the opposite. `"both"`, unsurprisingly, draws both. Defaults to `"internal"`.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planetaryjs.plugins.borders({
stroke: '#008000', lineWidth: 0.25, type: 'both'
});
```
</div>
See also:
* [Earth Plugin](/documentation/builtin_earth.html)
* [TopoJSON Plugin](/documentation/builtin_topojson.html)

View File

@ -0,0 +1,25 @@
Drag Plugin
===========
The `drag` plugin allows for modifying the planet's projection's rotation with the mouse. It supports dragging vertically with hard stops at the north and south poles, and dragging horizontally without restriction.
API
---
**`planetaryjs.plugins.drag([config])`**
Valid keys for `config` are:
* `onDragStart`, `onDragEnd`, `onDrag`, `afterDrag`: hooks to the `d3.behavior.drag` object's `dragstart`, `dragend`, and `drag` events; each defaults to a no-op. `onDrag` fires at the start of the `drag` event, `afterDrag` at the end. The planet instance is available as `this` inside the each of the functions.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planetaryjs.plugins.drag({
onDrag: function() {
console.log("The planet was dragged!", this, d3.event);
}
});
```
</div>

View File

@ -0,0 +1,36 @@
Earth Plugin
============
The `earth` plugin is simply a wrapper around the `topojson`, `oceans`, `land`, and `borders` plugins. It parses its configuration and passes pieces of it to the individual plugins.
API
---
**`planetaryjs.plugins.earth([config])`**
Valid keys for `config` are:
* `topojson`: options to pass to the `topojson` plugin
* `oceans`: options to pass to the `oceans` plugin
* `land`: options to pass to the `land` plugin
* `borders`: options to pass to the `borders` plugin
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planetaryjs.plugins.earth({
topojson: { file: 'world-110m.json' },
oceans: { fill: '#000080' },
land: { fill: '#339966' },
borders: { stroke: '#008000' }
});
```
</div>
See also:
* [TopoJSON Plugin](/documentation/builtin_topojson.html)
* [Oceans Plugin](/documentation/builtin_oceans.html)
* [Land Plugin](/documentation/builtin_land.html)
* [Borders Plugin](/documentation/builtin_borders.html)

View File

@ -0,0 +1,30 @@
Land Plugin
===========
The `land` plugin renders Earth's landmasses. It uses TopoJSON data published to `planet.plugins.topojson.world` by the [TopoJSON plugin](/documentation/builtin_topojson.html). It uses the feature at `objects.land` in the TopoJSON object.
API
---
**`planetaryjs.plugins.land([config])`**
Valid keys for `config` are:
* `fill`: the `fillStyle` to use for the context; defaults to `"white"`
* `stroke`: the `strokeStyle` to use for the context; defaults to no value, resulting in no stroke around the landmasses
* `lineWidth` the `lineWidth` to set on the context; only effective if `stroke` is set. Defaults to no value, resulting in no change to the context's `lineWidth`
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planetaryjs.plugins.land({
fill: '#339966', stroke: '#000000'
});
```
</div>
See also:
* [Earth Plugin](/documentation/builtin_earth.html)
* [TopoJSON Plugin](/documentation/builtin_topojson.html)

View File

@ -0,0 +1,27 @@
Oceans Plugin
=============
The `oceans` plugin simply renders the main shape of the globe, filling it in with a solid color.
API
---
**`planetaryjs.plugins.oceans([config])`**
Valid keys for `config` are:
* `fill`: the `fillStyle` to use for the globe; defaults to `"black"`
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planetaryjs.plugins.oceans({
fill: '#000080'
});
```
</div>
See also:
* [Earth Plugin](/documentation/builtin_earth.html)

View File

@ -0,0 +1,55 @@
Pings Plugin
============
The `pings` plugin allows you to display animated "pings" at any location on the planet. It publishes a method to create pings at `planet.plugins.pings.add`.
API
---
**`planetaryjs.plugins.pings([config])`**
Valid keys for `config` are:
* `color`: the default color for pings; defaults to `"white"`
* `ttl`: the default TTL for pings in milliseconds (how long they take to fade out); defaults to 2000
* `angle`: the maximum angle for the ping (it will grow to this size over the course of its TTL); defaults to `5`
* `latitudeFirst`: reverse the order of the latitudinal and longitudinal coordinates passed to the `add` function (so that the latitudinal coordinate comes first); defaults to false. See the note on `add`, below, for more information.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planetaryjs.plugins.pings({
color: 'yellow', ttl: 5000, angle: 10
});
```
</div>
**`planet.plugins.pings.add(lng, lat, [config])`**
Add a new ping to the globe at the longitudinal and latitudinal coordinates specified by `lng` and `lat`. Valid keys for `config` are:
* `color`: the default color for pings; defaults to `"white"`
* `ttl`: the default TTL for pings in milliseconds (how long they take to fade out); defaults to 2000
* `angle`: the maximum angle for the ping (it will grow to this size over the course of its TTL); defaults to `5`
Any values not set by `config` will default to the values specified in the plugin's configuration, if any were set.
<div class='ui red raised segment'>
<i class='red icon warning'></i> **Note that the longitudinal coordinate comes first, followed by the latitudinal coordinate, unless you pass `latitudeFirst` as an option to the plugin configuration function.** This corresponds to the conventions used by D3 (which Planetary.js is based on); for more information on the problem of axis ordering in software, see [this article at the GeoTools web site](http://docs.geotools.org/latest/userguide/library/referencing/order.html).
</div>
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var colors = ['red', 'yellow', 'white', 'orange', 'green', 'cyan', 'pink'];
setInterval(function() {
var lat = Math.random() * 170 - 85;
var lng = Math.random() * 360 - 180;
var color = colors[Math.floor(Math.random() * colors.length)];
var angle = Math.random() * 10;
planet.plugins.pings.add(lng, lat, { color: color, ttl: 2000, angle: angle });
}, 250);
```
</div>

View File

@ -0,0 +1,49 @@
TopoJSON Plugin
===============
The `topojson` plugin parses [TopoJSON data](https://github.com/mbostock/topojson) and publishes it on `planet.plugins.topojson.world` for other plugins to use (particularly for rendering geographical data using D3).
The plugin can load data from a file using Ajax, or can be provided an object that has come from some other source.
API
---
**`planetaryjs.plugins.topojson([config])`**
Valid keys for `config` are:
* `world`: a JavaScript object representing TopoJSON data (not a JSON string); defaults to no value, which will cause the plugin to load data from the `file` configuration option
* `file`: the path to a TopoJSON data file to be loaded via Ajax; defaults to `"world-110m.json"`, which can be downloaded with the Planetary.js library from the [download page](/download/).
If you plan on creating more than one planet from the same TopoJSON data, you can load the data once before loading the plugin and pass the parsed data to the plugin via the `world` property rather than letting the plugin load the data via Ajax each time a new planet is created.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planetaryjs.plugins.topojson({
file: '/data/world-110m.json'
});
```
</div>
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
d3.json('/data/world-110m.json', function(err, data) {
planetaryjs.plugins.topojson({
world: data
});
// Create planets inside this callback
});
```
</div>
**`planet.plugins.topojson.world`**
The plugin will publish the TopoJSON data to this key once it has been initialized by the plugin.
* [Earth Plugin](/documentation/builtin_earth.html)
* [Land Plugin](/documentation/builtin_land.html)
* [Borders Plugin](/documentation/builtin_borders.html)

View File

@ -0,0 +1,28 @@
Zoom Plugin
===========
The `zoom` plugin allows for modifying the planet's projection's scale with the mouse wheel.
API
---
**`planetaryjs.plugins.zoom([config])`**
Valid keys for `config` are:
* `initialScale`: the value to initialize the [`d3.behavior.zoom`](https://github.com/mbostock/d3/wiki/Zoom-Behavior) object's scale to; defaults to the scale of the planet's projection at the time the planet is initialized
* `scaleExtent`: the value to use for the `d3.behavior.zoom` object's `scaleExtent` property, which defines how far in and out the planet can be zoomed; defaults to `[50, 2000]`
* `onZoomStart`, `onZoomEnd`, `onZoom`, `afterZoom`: hooks to the `d3.behavior.zoom` object's `zoomstart`, `zoomend`, and `zoom` events; each defaults to a no-op. `onZoom` fires at the start of the `zoom` event, `afterZoom` at the end. The planet instance is available as `this` inside the each of the functions.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planetaryjs.plugins.zoom({
scaleExtent: [200, 1000],
onZoom: function() {
console.log("The planet was zoomed!", this, d3.event);
}
});
```
</div>

View File

@ -0,0 +1,44 @@
Core API
========
Core API
--------
**`planetaryjs.noConflict()`**
In non-AMD and non-CommonJS environments, Planetary.js takes over the global `planetaryjs` namespace (in the browser, this means `window.planetaryjs`). If, for some reason, something else useful was there before you loaded Planetary.js, you can ask for it to be returned to that spot by calling `planetaryjs.noConflict()`. The Planetary.js library will be returned from the function, so you can continue to use the library.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var planetary = planetaryjs.noConflict();
```
</div>
**`planetaryjs.loadPlugin(plugin)`**
Planetary.js uses a plugin architecture for all its functionality. Calling `planetaryjs.loadPlugin` will cause that plugin to be loaded in *all* planets created from this library. If you only want to use a plugin in some of your planets, use the `planet.loadPlugin` method (from the [Planet API](/documentation/planet.html)) instead.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planetaryjs.loadPlugin(somePlugin);
planetaryjs.loadPlugin(somePluginGenerator());
```
</div>
For more information on the plugin system and API, please see the [Plugins documentation](/documentation/plugins.html).
**`planetaryjs.planet()`**
The `planet` API call returns a new planet instance, which represents a single globe. It will be created with all the plugins registered with `planetaryjs.loadPlugin` active. It has various methods for manipulating the globe and drawing it to a canvas. The [Planet API](/documentation/planet.html) covers these methods in considerably more detail.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var planet = planetaryjs.planet();
```
</div>

View File

@ -0,0 +1,47 @@
FAQ
===
**Q:** Why are the pings I add from the [Pings plugin](/documentation/builtin_pings.html) in the wrong place?
**A:** Like D3 on which it is based, Planetary.js accepts coordinates with the longitudinal coordinate first. You can set the `latitudeFirst` option in the plugin configuration to change this. There is some additional discussion on the subject in the [Pings plugin documentation](/documentation/builtin_pings.html).
<div class="ui horizontal icon divider">
<i class="globe icon"></i>
</div>
**Q:** Why can't I access my DOM element?
**A:** Planetary.js provides no methods for DOM access or for waiting for the DOM ready event; you'll need to handle this on your own or use a third-party library.
<div class="ui horizontal icon divider">
<i class="globe icon"></i>
</div>
**Q:** Why doesn't my `canvas` element work with Planetary.js?
**A:** Planetary.js asks for raw DOM elements; if you have an element wrapped with jQuery, D3, or a similar library, you'll need to unwrap it to pass to your
planet's `draw` method.
<div class="ui horizontal icon divider">
<i class="globe icon"></i>
</div>
**Q:** Why can't I load the `world-110m.json` file with the TopoJSON plugin?
**A:** After checking to make sure you've specified the correct path to the file in the plugin's configuration options, ensure that you're viewing your page over HTTP. Your browser won't be able to make the necessary Ajax request to load the file if you're just viewing the page from your filesystem.
<div class="ui horizontal icon divider">
<i class="globe icon"></i>
</div>
**Q:** How do I manipulate my globe?
**A:** The planet object has methods and properties for manipulating the globe; most notable is the `projection` property. See the [Planet API](/documentation/planet.html) for more information.
<div class="ui horizontal icon divider">
<i class="globe icon"></i>
</div>
**Q:** I'm getting "Cannot read property 'geo' of undefined" or "Cannot call method 'feature' of undefined."
**A:** Ensure you're requiring the [D3](http://d3js.org/) and [TopoJSON](https://github.com/mbostock/topojson) libraries before Planetary.js.

View File

@ -0,0 +1,8 @@
Getting Help
============
[Stack Overflow](http://stackoverflow.com/) is a great place to get help when you're stuck on a particular issue. Tag your question with `planetary.js` when you post it.
If you think you've found a bug, hop over to [the Planetary.js issues page](https://github.com/BinaryMuse/planetary.js/issues) and file a bug (assuming the same bug hasn't already been reported).
If you have an idea for an improvement or other change, feel free to open a GitHub pull request.

View File

@ -0,0 +1,55 @@
Introduction
============
Planetary.js is a JavaScript library for building awesome interactive globes. It uses [D3](http://d3js.org/) and [TopoJSON](https://github.com/mbostock/topojson) to parse and render geographic data. Planetary.js uses a plugin-based architecture; even the default functionality is implemented as plugins! This makes Planetary.js extremely flexible.
The documentation is split up into several sections:
* [Core API](/documentation/core.html) describes the top-level Planetary.js API, including installing and configuring the library and creating new planet instances.
* [Planet API](/documentation/planet.html) describes the API associated with a planet instance, including modifying its properties and accessing a special canvas context that allows you to draw on the globe.
* [Plugins](/documentation/plugins.html) describes the plugin architecture of Planetary.js and shows how you can easily build your own plugins to modify the behavior of Planetary.js.
* [Built-In Plugins](/documentation/builtin.html) describes each of the built-in plugins in turn, including their public API and how to use them in a project.
* [FAQ](/documentation/faq.html) answers some common question and addresses a few easy-to-miss gotchas.
* [Getting Help](/documentation/help.html) describes what to do if you still need help after reading this documentation.
Quick Start
-----------
If you want to get up-and-running quickly, or like to experiment and figure things out, you can use this HTML and JavaScript to get a very simple globe up and running (once you've [installed Planetary.js](/documentation/installation.html)).
Note that you'll need to run this page from a web server of some kind so that Planetary.js can load the TopoJSON data via Ajax (Ajax requests don't work when viewing a page directly from the filesystem).
Be sure to check out [the examples](/examples/) as well!
<div class='ui raised segment'>
<div class='ui blue ribbon label'>HTML</div>
```html
<html>
<head>
<script type='text/javascript' src='http://d3js.org/d3.v3.min.js'></script>
<script type='text/javascript' src='http://d3js.org/topojson.v1.min.js'></script>
<script type='text/javascript' src='planetaryjs.min.js'></script>
</head>
<body>
<canvas id='globe' width='500' height='500'></canvas>
<script type='text/javascript' src='yourApp.js'></script>
</body>
</html>
```
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var planet = planetaryjs.planet();
// You can remove this statement if `world-110m.json`
// is in the same path as the HTML page:
planet.loadPlugin(planetaryjs.plugins.earth({
topojson: { file: 'http/path/to/world-110m.json' }
}));
// Make the planet fit well in its canvas
planet.projection.scale(250).translate([250, 250]);
var canvas = document.getElementById('globe');
planet.draw(canvas);
```
</div>

View File

@ -0,0 +1,97 @@
Installation
============
Once you've [downloaded Planetary.js](/download/), you can include it via a `script` tag on your page *after* the inclusion of D3 and TopoJSON. This example uses the CDN URLs for those libraries:
<div class='ui raised segment'>
<div class='ui blue ribbon label'>HTML</div>
```html
<html>
<head>
<script type='text/javascript' src='http://d3js.org/d3.v3.min.js'></script>
<script type='text/javascript' src='http://d3js.org/topojson.v1.min.js'></script>
<script type='text/javascript' src='path/to/planetaryjs.min.js'></script>
</head>
<body>
...
```
</div>
If you use the default `topojson` plugin (most people will), you'll also need to make sure `world-110m.json` (or some other TopoJSON data file) is available on your server. This file is also available from [the download page](/download/). See the [TopoJSON Plugin documentation](/documentation/builtin_topojson.html) for more information.
Planetary.js also supports installation via AMD and CommonJS loaders.
AMD
---
This example uses [RequireJS](http://requirejs.org/). Since neither D3 nor TopoJSON support AMD, we will use RequireJS's [shim configuration](http://requirejs.org/docs/api.html#config-shim).
<div class='ui raised segment'>
<div class='ui blue ribbon label'>HTML</div>
```html
<body>
<canvas id='globe' width='500' height='500'></canavs>
<script src='//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.9/require.min.js'
data-main='/app.js'></script>
</body>
```
<div class='ui red ribbon label'>JavaScript</div>
```javascript
requirejs.config({
// Tell RequireJS to use `window.d3` and `window.topojson`
// for those libraries, respectively
shim: {
d3: { exports: 'd3' },
topojson: { exports: 'topojson' }
},
paths: {
'd3': 'path/to/d3.v3.min',
'topojson': 'path/to/topojson.v1.min'
}
});
requirejs(['planetaryjs'], function(planetaryjs) {
// Use Planetary.js here
});
```
</div>
CommonJS
--------
First, install `browserify` from npm (as well as `planetary.js` v1.0.2+, if you haven't already). Then, create your application (here referred to as `app.js`) and bundle it with browserify.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var planetaryjs = require('planetary.js');
var planet = planetaryjs.planet();
var canvas = document.getElementById('canvas');
planet.draw(canvas);
```
<div class='ui purple ribbon label'>Shell</div>
```shell
$ npm install browserify
$ ./node_modules/.bin/browserify app.js > bundle.js
```
</div>
`bundle.js` is now ready to use! You may need to set the `charset` option on your script tag:
<div class='ui raised segment'>
<div class='ui blue ribbon label'>HTML</div>
```html
<script type='text/javascript' src='bundle.js' charset='utf-8'></script>
```
</div>

View File

@ -0,0 +1,176 @@
Planet API
==========
A "planet" represents a single globe and its rendering instructions. It is created from the `planetaryjs.planet` method; see the [Core API documentation](/documentation/core.html) for more details.
**`planet.loadPlugin(plugin)`**
Planetary.js uses a plugin architecture for all its functionality. While you can load plugins at the global library level, Planetary.js also allows you to load plugins for specific planets. **If a planet is drawn and no plugins have been loaded globally and no plugins have been loaded for the specific planet instance, it will use the default `earth` and `pings` plugins.**
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planet.loadPlugin(somePlugin);
planet.loadPlugin(somePluginGenerator());
```
</div>
For more information on the plugin system and API, please see the [Plugins documentation](/documentation/plugins.html).
**`planet.projection`**
The core of a planet's data model is an [`d3.geo.projection`](https://github.com/mbostock/d3/wiki/Geo-Projections) (specifically, an orthographic projection), which is exposed by a planet by `planet.projection`. You can use this object to control various aspects of the planet. The D3 documentation covers the methods in considerable detail, so [be sure to check it out](https://github.com/mbostock/d3/wiki/Geo-Projections); many of the examples on this site also use the projection object to operate.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planet.projection
.scale(width / 2)
.translate([width / 2, height / 2])
.rotate([60, -10, 0]);
```
</div>
**`planet.path`**
`planet.path` is a [`d3.geo.path`](https://github.com/mbostock/d3/wiki/Geo-Paths) which uses the planet's internal projection to generate path data for geographical features. Its `context` method is commonly used by internal plugins to take a canvas context and return a path generator that can be used to draw on the globe.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
canvasContext.beginPath();
planet.path.context(canvasContext)(geoFeature);
canvasContext.fill();
```
</div>
**`planet.plugins`**
Planetary.js provides an empty object that plugins may use to store public data and methods. If a plugin is well-behaved, it will keep all its properties on the object under a single key (usually one that share's the plugin's name).
**`planet.canvas` and `planet.context`**
Once you call `draw` on a planet instance, Planetary.js will set the `canvas` and `context` properties to the canvas and its context, respectively.
**`planet.onInit( function([done]){} )`**
Registers a function to be called when the planet is initialized (which happens after a call to `draw` and after any registered plugins have been loaded). This is mostly used by plugins to initialize themselves when the planet "boots."
If the provided callback function takes any parameters, it will be a "done" function that must be called once the initialization function finishes any asynchronous work before the planet will continue to initialize.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planet.onInit(function() {
doSomeSetupStuff();
});
planet.onInit(function(done) {
doSomeAsynchronousSetupStuff(function() {
done();
});
});
```
</div>
**`planet.onDraw( function(){} )`**
Registers a function to be called each time the globe redraws itself. This is mostly used by plugins to draw plugin-specific data or otherwise animate the globe.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planet.onDraw(function() {
var rotation = planet.projection.rotate();
rotation[0] += 1;
if (rotation[0] >= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
});
```
</div>
**`planet.onStop( function(){} )`**
Registers a function to be called when the planet is stopped with the `stop` method. This can be used to clean up timers and remove references to internal planet properties and plugins, if necessary, so that it can be property garbage collected.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var interval = setInterval(function() {
addRandomPing(planet); // uses `planet.plugins.pings`
}, 150);
planet.onStop(function() {
clearInterval(interval);
});
```
</div>
**`planet.withSavedContext( function(context){} )`**
Calls the function with the current canvas context as a parameter, wrapping the function call in `context.save()` and `context.restore()`. Use this function any time you're going to modify the context to ensure it gets put back to the way it was.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planet.onDraw(function() {
planet.withSavedContext(function(context) {
context.beginPath();
planet.path.context(context)({type: 'Sphere'});
context.fillStyle = 'black';
context.fill();
});
});
```
</div>
**`planet.draw(canvas)`**
Begins drawing the globe onto the given canvas. `canvas` should be a raw DOM element (e.g. as returned by `document.getElementById`). Specifically, if it is wrapped by D3 or jQuery, you need to unwrap it with something like `wrappedCanvas[0]`.
Calling `draw` will perform the following operations:
1. Initialize each loaded plugin by calling the plugin function (note: this only happens the first time you call `draw`).
2. Set `planet.canvas` and `planet.context` to the canvas and the canvas' context, respectively.
3. Run each registered `onInit` hook in the order it was registered (note that `onInit` calls made by plugins will not be made until step 1, after `draw` has been called).
4. Start the animation loop, each tick clearing the canvas and calling any registered `onDraw` hooks in order.
<div class='ui raised segment'>
<div class='ui blue ribbon label'>HTML</div>
```html
<canvas id='myCanvas' width='123' height='456'></canvas>
```
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var canvas = document.getElementById('myCanvas');
planet.draw(canvas);
```
</div>
Once you've called `draw()` on a planet, you should not call it again unless you first call `stop()`.
**`planet.stop()`**
Stop drawing the planet to the canvas. This disables the internal draw loop. You can register functions to call when the planet is stopped using the `onStop` method; if you don't plan on reusing the planet, be sure to clean up timers and references to internal properties, if necessary, so that it can be garbage collected.
You can draw the planet to a new (or the same) canvas using the `draw` method as normal. All your plugins' `onInit` functions will fire, although the plugin function itself will not be called again.
Keep in mind that, since the internal draw loop is stopped, your plugins' `onDraw` functions are not being called. If you have timers or other mechanisms that continually push data into a data structure that an `onDraw` method cleans up, you should disable or pause it.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
planet.stop();
```
</div>

View File

@ -0,0 +1,189 @@
Plugins
=======
Planetary.js uses a plugin-based architecture, and all the built-in functionality is built using this architecture. This makes Planetary.js extremely flexible.
Loading Plugins
---------------
Plugins are loaded either globally by `planetaryjs.loadPlugin` or for a specific planet instance by `planet.loadPlugin`. If you call `draw` on a planet and it has no plugins loaded at all (from either source), Planetary.js will use the default plugin stack, which consists of the `earth` and `pings` plugins.
Anatomy of a Plugin
-------------------
A plugin is simply a JavaScript function that takes a planet instance as a parameter and performs some operation on it. **The best plugins do one tiny thing.** If you want a plugin to do a lot of things at once, you should build a plugin that wraps other, smaller plugins; in fact, this is exactly how the `earth` plugin is built. See the [Earth Plugin documentation](/documentation/builtin_earth.html) for more details.
Most of the time, a plugin will implement its behavior by registering callbacks into a planet's lifecycle hooks. For example, the following simple plugin increments the planet's projection's rotation by one degree every tick (this would make for a very fast spinning globe, but demonstrates the idea nicely enough):
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var autorotate = function(planet) {
planet.onDraw(function() {
var rotation = planet.projection.rotate();
rotation[0] += 1;
if (rotation[0] >= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
});
};
planet.loadPlugin(autorotate);
```
</div>
Configurable Plugins
--------------------
Often, you'll want your plugin to be configurable with some user-defined values. In this case, you can create a higher-order function, which takes your configuration data and then *returns* the plugin function. You can then call this function to generate the plugin for use by `loadPlugin`.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var autorotate = function(degreesPerTick) {
return function(planet) {
planet.onDraw(function() {
var rotation = planet.projection.rotate();
rotation[0] += degreesPerTick;
if (rotation[0] >= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
});
};
};
planet.loadPlugin(autorotate(5));
```
</div>
Setting Yourself Up
-------------------
If you need to do some work before your plugin is ready to be used, you can add a hook to a planet's `onInit` hook to do the necessary setup.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var somePlugin = function(planet) {
planet.onInit(function() {
doSomeSetupWork();
});
};
```
</div>
If you need to do some asynchronous setup--such as fetching data with an Ajax request--before your plugin is ready, you can accept an argument to your `onInit` function. This argument is a function that tells Planetary.js when you're done setting up; simply call this function after your asynchronous operations are complete and Planetary.js will continue to initialize the planet. **If you accept the parameter but don't call it, the initialization process will stop** (and your planet will not work).
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var somePlugin = function(planet) {
planet.onInit(function(done) {
doSomeAsynchronousSetupWork(function() {
done();
});
});
};
```
</div>
Drawing on the Canvas
---------------------
Many plugins will want to draw onto the globe's canvas; you can do so by registering a function to a planet's `onDraw` hook.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var somePlugin = function(planet) {
planet.onDraw(function() {
planet.withSavedContext(function(context) {
context.beginPath();
planet.path.context(context)({type: 'Sphere'});
context.fillStyle = 'black';
context.fill();
});
});
};
```
</div>
The planet exposes properties and methods, such as `context`, `path`, and `withSavedContext` to assist with drawing to the canvas. The [Planet API documentation](/documentation/planet.html) goes into more detail on individual properties.
### Drawing Geo Paths
As explained in the `planet.path` documentation on the [Planet API page](/documentation/planet.html), `planet.path` is a [`d3.geo.path`](https://github.com/mbostock/d3/wiki/Geo-Paths) object that can be used to draw geographical geometry onto the canvas. The path will take care of transforming the coordinates to be projected onto the orthographic view of the globe.
As a demonstration of this technique, the following is a plugin that will take the land data from a TopoJSON data source (stored on `planet.plugins.topojson.world`), convert it to a GeoJSON feature, and draw it on the planet. This code is similar to (but slightly simplified from) the [Land plugin's](/documentation/builtin_land.html) implementation.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var drawLand = function(planet) {
planet.onDraw(function() {
planet.withSavedContext(function(context) {
var world = planet.plugins.topojson.world;
var land = topojson.feature(world, world.objects.land);
context.beginPath();
planet.path.context(context)(land);
context.fillStyle = 'white';
context.fill();
});
});
};
```
</div>
Exposing Data and Methods
-------------------------
Obviously, you can use private internal variables to keep track of any data your plugin needs in order to operate. However, if you want to expose a public API to users of your plugin, you should avoid attaching them directly to the planet and instead attach them to the planet's `plugins` namespace. You should use a name specific to your plugin, and this name should be well documented in your plugin's documentation.
<div class='ui raised segment'>
<div class='ui red ribbon label'>JavaScript</div>
```javascript
var autorotate = function(degreesPerTick) {
return function(planet) {
var paused = false;
// Attach our public API to `planet.plugins`
// on the `autorotate` namespace.
planet.plugins.autorotate = {
pause: function() { paused = true; },
resume: function() { paused = false; }
};
planet.onDraw(function() {
if (paused) return;
var rotation = planet.projection.rotate();
rotation[0] += degreesPerTick;
if (rotation[0] >= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
});
};
};
planet.loadPlugin(autorotate(5));
planet.draw(canvas);
setTimeout(function() {
planet.plugins.autorotate.pause();
}, 5000);
```
</div>
Best Practices
--------------
There are a few things you can do to make your plugin all it can be:
1. Make your plugin very small; ideally, it should do only *one thing* very well. Be extremely liberal with splitting plugins into smaller plugins, which makes them easier to understand, test, and compose. It's easy to say "this plugin renders the Earth," but it really renders oceans, land masses, and borders.
2. Use higher-order functions to generate your plugin (as described above in "Plugin Generators") instead of passing function references to `loadPlugin` directly, even if your plugin doesn't take any configuration options. It makes for a more consistent API, and allows you to more easily add the ability to specify configuration options in the future.
3. Make configuration optional if at all possible. Write your plugin so that it checks for missing values and uses sensible defaults.
4. Only publish public data and API methods to `planet.plugins.pluginName`, where `pluginName` is the name of your plugin.

View File

@ -0,0 +1,12 @@
{
"stable": {
"latest": {
"version": "v1.1.2"
}
},
"unstable": {
"latest": {
"version": "v1.0.0-rc.2"
}
}
}

View File

@ -0,0 +1,19 @@
<!doctype html>
<html>
<head>
<%- partial("../_header") %>
<link href="/css/prism.css" rel="stylesheet">
</head>
<body>
<%- partial("../_menu") %>
<div class='content container'>
<div class='page ui slim stackable grid'>
<div class='sixteen wide column'>
<%- yield %>
</div>
</div>
</div>
<%- partial("../_ga") %>
</body>
</html>

View File

@ -0,0 +1,99 @@
<% data = public.download._data %>
<% dl = function(version, file) { %>
<% return "https://github.com/BinaryMuse/planetary.js/releases/download/" + version + "/" + file; %>
<% } %>
<h1><i class='icon download disk'></i> Download Planetary.js</h1>
<p>Download the core Planetary.js library and supporting files here.</p>
<p>Up-to-the-minute releases, archived versions, and full release notes can be found <a href='https://github.com/BinaryMuse/planetary.js/releases'>on the GitHub releases page</a>.</p>
<% if (data.stable.latest) { %>
<h2>Latest Stable Build: <%= data.stable.latest.version %></h2>
<p><a href="https://github.com/BinaryMuse/planetary.js/releases/tag/<%= data.stable.latest.version %>">Release notes</a>
|
<a href="https://github.com/BinaryMuse/planetary.js/tree/<%= data.stable.latest.version %>">GitHub tag</a></p>
<div class='ui list download-list'>
<div class='item'>
<i class='icon download'></i>
Core library: [
<a href='<%= dl(data.stable.latest.version, 'planetaryjs.min.js') %>'>minified</a>
|
<a href='<%= dl(data.stable.latest.version, 'planetaryjs.js') %>'>unminified</a>
]
</div>
<div class='item'>
<i class='icon download'></i>
Core library (no plugins): [
<a href='<%= dl(data.stable.latest.version, 'planetaryjs-noplugins.min.js') %>'>minified</a>
|
<a href='<%= dl(data.stable.latest.version, 'planetaryjs-noplugins.js') %>'>unminified</a>
]
</div>
<div class='item'>
<i class='icon globe'></i>
Earth TopoJSON data ("land" and "countries" objects): [
<a href='<%= dl(data.stable.latest.version, 'world-110m.json') %>'>download</a>
]
</div>
<div class='item'>
<i class='icon code'></i>
Source code [
<a href='https://github.com/BinaryMuse/planetary.js/archive/<%= data.stable.latest.version %>.zip'>.zip</a>
|
<a href='https://github.com/BinaryMuse/planetary.js/archive/<%= data.stable.latest.version %>.tar.gz'>.tar.gz</a>
]
</div>
</div>
<% } else { %>
<h2>No stable builds yet</h2>
<% } %>
<% if (data.unstable.latest) { %>
<h2>Latest Unstable Build: <%= data.unstable.latest.version %></h2>
<p><a href="https://github.com/BinaryMuse/planetary.js/releases/tag/<%= data.unstable.latest.version %>">Release notes</a>
|
<a href="https://github.com/BinaryMuse/planetary.js/tree/<%= data.unstable.latest.version %>">GitHub tag</a></p>
<div class='ui list download-list'>
<div class='item'>
<i class='icon download'></i>
Core library: [
<a href='<%= dl(data.unstable.latest.version, 'planetaryjs.min.js') %>'>minified</a>
|
<a href='<%= dl(data.unstable.latest.version, 'planetaryjs.js') %>'>unminified</a>
]
</div>
<div class='item'>
<i class='icon download'></i>
Core library (no plugins): [
<a href='<%= dl(data.unstable.latest.version, 'planetaryjs-noplugins.min.js') %>'>minified</a>
|
<a href='<%= dl(data.unstable.latest.version, 'planetaryjs-noplugins.js') %>'>unminified</a>
]
</div>
<div class='item'>
<i class='icon globe'></i>
Earth TopoJSON data ("land" and "countries" objects): [
<a href='<%= dl(data.unstable.latest.version, 'world-110m.json') %>'>download</a>
]
</div>
<div class='item'>
<i class='icon code'></i>
Source code [
<a href='https://github.com/BinaryMuse/planetary.js/archive/<%= data.unstable.latest.version %>.zip'>.zip</a>
|
<a href='https://github.com/BinaryMuse/planetary.js/archive/<%= data.unstable.latest.version %>.tar.gz'>.tar.gz</a>
]
</div>
</div>
<% } else { %>
<h2>No unstable builds yet</h2>
<% } %>

View File

@ -0,0 +1,20 @@
<!doctype html>
<html>
<head>
<%- partial("../_header") %>
<link href="/css/prism.css" rel="stylesheet">
</head>
<body>
<%- partial("../_menu") %>
<div class='content container'>
<div class='page ui slim stackable grid'>
<div class='sixteen wide column'>
<%- yield %>
</div>
</div>
</div>
<script type='text/javascript' src='/js/prism.js'></script>
<%- partial("../_ga") %>
</body>
</html>

View File

@ -0,0 +1,2 @@
<%- partial('../_scripts') %>
<script type='text/javascript' src='/examples/basic.js'></script>

View File

@ -0,0 +1,2 @@
<%- partial('../_scripts') %>
<script type='text/javascript' src='/examples/rotating.js'></script>

View File

@ -0,0 +1,37 @@
<div class="ui breadcrumb">
<a href='/examples/' class="section">Examples</a>
<i class="right arrow icon divider"></i>
<div class="active section">Basic Globe</div>
</div>
<h1>Basic Globe</h1>
<p>This example shows the minimum code you need to render a basic representation of the planet Earth.</p>
<div style='text-align: center;'>
<canvas id='basicGlobe' width='400' height='400'></canvas>
</div>
<div class='ui raised segment'>
<div class='ui blue ribbon label'>HTML</div>
<pre class='line-numbers'><code class='language-html'>&lt;canvas id='basicGlobe' width='400' height='400'&gt;&lt;/canvas&gt;</code></pre>
<div class='ui red ribbon label'>JavaScript</div>
<pre class='line-numbers'><code class='language-javascript'>(function() {
var canvas = document.getElementById('basicGlobe');
var planet = planetaryjs.planet();
// Loading this plugin technically happens automatically,
// but we need to specify the path to the `world-110m.json` file.
planet.loadPlugin(planetaryjs.plugins.earth({
topojson: { file: '/world-110m.json' }
}));
// Scale the planet's radius to half the canvas' size
// and move it to the center of the canvas.
planet.projection
.scale(canvas.width / 2)
.translate([canvas.width / 2, canvas.height / 2]);
planet.draw(canvas);
})();</code></pre>
</div>
<%- partial('_scripts_basic') %>

View File

@ -0,0 +1,15 @@
(function() {
var canvas = document.getElementById('basicGlobe');
var planet = planetaryjs.planet();
// Loading this plugin technically happens automatically,
// but we need to specify the path to the `world-110m.json` file.
planet.loadPlugin(planetaryjs.plugins.earth({
topojson: { file: '/world-110m.json' }
}));
// Scale the planet's radius to half the canvas' size
// and move it to the center of the canvas.
planet.projection
.scale(canvas.width / 2)
.translate([canvas.width / 2, canvas.height / 2]);
planet.draw(canvas);
})();

View File

@ -0,0 +1,35 @@
<h1>Examples</h1>
<p>Sometimes you just need to see some code to get an idea started; here are a few examples of what you can build with Planetary.js.</p>
<div class='ui top attached segment example-segment'>
<div>
<a href='/examples/basic.html'><img src='/images/ex-basic.png'></a>
<a href='/examples/basic.html'><h2><i class='icon black globe'></i>Basic Globe</h2></a>
<p>It doesn't get any simpler than this: just a static globe, built using built-in plugins with nothing up our sleeves!</p>
<span class='ui red horizontal label'>plugins: earth</span>
<span class='ui purple horizontal label'>d3: projections</span>
</div>
</div>
<div class='ui attached segment example-segment'>
<div>
<a href='/examples/rotating.html'><img src='/images/ex-rotating.png'></a>
<a href='/examples/rotating.html'><h2><i class='icon black basic desk globe'></i>Rotating Globe with Pings</h2></a>
<p>If there's one thing that's better than a globe, it's a globe that rotates. This is the demo from the homepage of Planetaryjs.com, and so includes a custom auto-rotation plugin and zoom/drag integration.</p>
<span class='ui red horizontal label'>plugins: earth, pings, drag, zoom</span>
<span class='ui teal horizontal label'>custom plugins</span>
<span class='ui purple horizontal label'>d3: projections</span>
</div>
</div>
<div class='ui bottom attached segment example-segment'>
<div>
<a href='/examples/quake.html'><img src='/images/ex-quake.png'></a>
<a href='/examples/quake.html'><h2><i class='icon black bullseye'></i>2013 Seismic Activity Visualization</h2></a>
<p>A visualization of 2013 seismic activity. This demo shows the use of multiple custom plugins, D3 scales, fetching third party data, and DOM updates via D3.</p>
<span class='ui red horizontal label'>plugins: earth, pings, drag, zoom</span>
<span class='ui teal horizontal label'>custom plugins</span>
<span class='ui purple horizontal label'>d3: projections, scales, selections, events, external data</span>
</div>
</div>

View File

@ -0,0 +1,260 @@
<div class="ui breadcrumb">
<a href='/examples/' class="section">Examples</a>
<i class="right arrow icon divider"></i>
<div class="active section">2013 Seismic Activity Visualization</div>
</div>
<h1>2013 Seismic Activity Visualization</h1>
<p>This is a more advanced example of what you can build with Planetary.js. The demo sets up a globe with some custom plugins (defined at the bottom of the JavaScript), and also demonstrates some non-Planetary.js-specific techniques, like the use of <a href='http://momentjs.com/'>Moment.js</a>, D3 scales, DOM manipulation, and loading external data.</p>
<h2><a href="/examples/quake/index.html"><i class='black icon play circle' style='text-decoration: none;'></i>View the demo</a></h2>
<div class='ui raised segment'>
<div class='ui blue ribbon label'>HTML</div>
<pre class='line-numbers'><code class='language-html'>&lt;h1&gt;Earthquakes: 2013&lt;/h1&gt;
&lt;ul id='magnitudes'&gt;&lt;/ul&gt;
&lt;canvas id='quakeCanvas'&gt;&lt;/canvas&gt;
&lt;div id='controls'&gt;
&lt;div&gt;
&lt;input id='slider' type='range' min='0' max='100' step='0.1' value='0'&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;span id='date'&gt;&lt;/span&gt;&amp;nbsp;
&lt;/div&gt;
&lt;/div&gt;</code></pre>
<div class='ui red ribbon label'>JavaScript</div>
<pre class='line-numbers'><code class='language-javascript'>(function() {
var canvas = document.getElementById('quakeCanvas');
// Create our Planetary.js planet and set some initial values;
// we use several custom plugins, defined at the bottom of the file
var planet = planetaryjs.planet();
planet.loadPlugin(autocenter({extraHeight: -120}));
planet.loadPlugin(autoscale({extraHeight: -120}));
planet.loadPlugin(planetaryjs.plugins.earth({
topojson: { file: '/world-110m.json' },
oceans: { fill: '#001320' },
land: { fill: '#06304e' },
borders: { stroke: '#001320' }
}));
planet.loadPlugin(planetaryjs.plugins.pings());
planet.loadPlugin(planetaryjs.plugins.zoom({
scaleExtent: [50, 5000]
}));
planet.loadPlugin(planetaryjs.plugins.drag({
onDragStart: function() {
this.plugins.autorotate.pause();
},
onDragEnd: function() {
this.plugins.autorotate.resume();
}
}));
planet.loadPlugin(autorotate(5));
planet.projection.rotate([100, -10, 0]);
planet.draw(canvas);
// Create a color scale for the various earthquake magnitudes; the
// minimum magnitude in our data set is 2.5.
var colors = d3.scale.pow()
.exponent(3)
.domain([2, 4, 6, 8, 10])
.range(['white', 'yellow', 'orange', 'red', 'purple']);
// Also create a scale for mapping magnitudes to ping angle sizes
var angles = d3.scale.pow()
.exponent(3)
.domain([2.5, 10])
.range([0.5, 15]);
// And finally, a scale for mapping magnitudes to ping TTLs
var ttls = d3.scale.pow()
.exponent(3)
.domain([2.5, 10])
.range([2000, 5000]);
// Create a key to show the magnitudes and their colors
d3.select('#magnitudes').selectAll('li')
.data(colors.ticks(9))
.enter()
.append('li')
.style('color', colors)
.text(function(d) {
return &quot;Magnitude &quot; + d;
});
// Load our earthquake data and set up the controls.
// The data consists of an array of objects in the following format:
// {
// mag: magnitude_of_quake
// lng: longitude_coordinates
// lat: latitude_coordinates
// time: timestamp_of_quake
// }
// The data is ordered, with the earliest data being the first in the file.
d3.json('/examples/quake/year_quakes_small.json', function(err, data) {
if (err) {
alert(&quot;Problem loading the quake data.&quot;);
return;
}
var start = parseInt(data[0].time, 10);
var end = parseInt(data[data.length - 1].time, 10);
var currentTime = start;
var lastTick = new Date().getTime();
var updateDate = function() {
d3.select('#date').text(moment(currentTime).utc().format(&quot;MMM DD YYYY HH:mm UTC&quot;));
};
// A scale that maps a percentage of playback to a time
// from the data; for example, `50` would map to the halfway
// mark between the first and last items in our data array.
var percentToDate = d3.scale.linear()
.domain([0, 100])
.range([start, end]);
// A scale that maps real time passage to data playback time.
// 12 minutes of real time maps to the entirety of the
// timespan covered by the data.
var realToData = d3.scale.linear()
.domain([0, 1000 * 60 * 12])
.range([0, end - start]);
var paused = false;
// Pause playback and update the time display
// while scrubbing using the range input.
d3.select('#slider')
.on('change', function(d) {
currentTime = percentToDate(d3.event.target.value);
updateDate();
})
.call(d3.behavior.drag()
.on('dragstart', function() {
paused = true;
})
.on('dragend', function() {
paused = false;
})
);
// The main playback loop; for each tick, we'll see how much
// time passed in our accelerated playback reel and find all
// the earthquakes that happened in that timespan, adding
// them to the globe with a color and angle relative to their magnitudes.
d3.timer(function() {
var now = new Date().getTime();
if (paused) {
lastTick = now;
return;
}
var realDelta = now - lastTick;
// Avoid switching back to the window only to see thousands of pings;
// if it's been more than 500 milliseconds since we've updated playback,
// we'll just set the value to 500 milliseconds.
if (realDelta &gt; 500) realDelta = 500;
var dataDelta = realToData(realDelta);
var toPing = data.filter(function(d) {
return d.time &gt; currentTime &amp;&amp; d.time &lt;= currentTime + dataDelta;
});
for (var i = 0; i &lt; toPing.length; i++) {
var ping = toPing[i];
planet.plugins.pings.add(ping.lng, ping.lat, {
// Here we use the `angles` and `colors` scales we built earlier
// to convert magnitudes to appropriate angles and colors.
angle: angles(ping.mag),
color: colors(ping.mag),
ttl: ttls(ping.mag)
});
}
currentTime += dataDelta;
if (currentTime &gt; end) currentTime = start;
updateDate();
d3.select('#slider').property('value', percentToDate.invert(currentTime));
lastTick = now;
});
});
// Plugin to resize the canvas to fill the window and to
// automatically center the planet when the window size changes
function autocenter(options) {
options = options || {};
var needsCentering = false;
var globe = null;
var resize = function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
globe.canvas.width = width;
globe.canvas.height = height;
globe.projection.translate([width / 2, height / 2]);
};
return function(planet) {
globe = planet;
planet.onInit(function() {
needsCentering = true;
d3.select(window).on('resize', function() {
needsCentering = true;
});
});
planet.onDraw(function() {
if (needsCentering) { resize(); needsCentering = false; }
});
};
};
// Plugin to automatically scale the planet's projection based
// on the window size when the planet is initialized
function autoscale(options) {
options = options || {};
return function(planet) {
planet.onInit(function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
planet.projection.scale(Math.min(width, height) / 2);
});
};
};
// Plugin to automatically rotate the globe around its vertical
// axis a configured number of degrees every second.
function autorotate(degPerSec) {
return function(planet) {
var lastTick = null;
var paused = false;
planet.plugins.autorotate = {
pause: function() { paused = true; },
resume: function() { paused = false; }
};
planet.onDraw(function() {
if (paused || !lastTick) {
lastTick = new Date();
} else {
var now = new Date();
var delta = now - lastTick;
var rotation = planet.projection.rotate();
rotation[0] += degPerSec * delta / 1000;
if (rotation[0] &gt;= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
lastTick = now;
}
});
};
};
})();</code></pre>
</div>

View File

@ -0,0 +1,65 @@
<!doctype html>
<html>
<head>
<%- partial("../../_header") %>
<link href="/css/prism.css" rel="stylesheet">
<style>
body {
background-color: rgb(0, 26, 34);
background: url('sky.jpg');
color: white;
}
ul#magnitudes {
position: absolute;
top: 100px;
left: 30px;
padding: 0;
margin: 0;
list-style: none;
z-index: 10;
}
h1 {
position: absolute;
top: 50px;
left: 5px;
padding: 0;
margin: 0;
z-index: 10;
}
canvas {
position: absolute;
top: 60px;
left: 0;
right: 0;
bottom: 0px;
cursor: move;
}
#controls {
position: absolute;
width: 400px;
bottom: 5px;
left: 50%;
margin-left: -200px;
text-align: center;
}
input[type=range] {
width: 400px;
}
</style>
</head>
<body>
<%- partial("../../_menu") %>
<%- yield %>
<%- partial("../../_scripts") %>
<script type='text/javascript' src='/js/lib/moment.min.js'></script>
<script type='text/javascript' src='/examples/quake/quake.js'></script>
<%- partial("../../_ga") %>
</body>
</html>

View File

@ -0,0 +1,13 @@
<h1>Earthquakes: 2013</h1>
<ul id='magnitudes'></ul>
<canvas id='quakeCanvas'></canvas>
<div id='controls'>
<div>
<input id='slider' type='range' min='0' max='100' step='0.1' value='0'>
</div>
<div>
<span id='date'>Loading...</span>
</div>
</div>

View File

@ -0,0 +1,28 @@
#!/usr/bin/env node
var fs = require('fs');
var filename = process.argv[2];
if (!filename) {
console.log("Please specify a file to process");
process.exit(1);
}
if (!fs.existsSync(filename)) {
console.log("#{filename} not found.");
process.exit(2);
}
var data = fs.readFileSync(filename, 'utf8');
var json = JSON.parse(data);
var quakeData = json.features.map(function(feature) {
return {
time: feature.properties.time,
lat: feature.geometry.coordinates[1],
lng: feature.geometry.coordinates[0],
mag: feature.properties.mag
};
}).sort(function(a, b) { return a.time - b.time});
console.log(JSON.stringify(quakeData));

View File

@ -0,0 +1,229 @@
(function() {
var canvas = document.getElementById('quakeCanvas');
// Create our Planetary.js planet and set some initial values;
// we use several custom plugins, defined at the bottom of the file
var planet = planetaryjs.planet();
planet.loadPlugin(autocenter({extraHeight: -120}));
planet.loadPlugin(autoscale({extraHeight: -120}));
planet.loadPlugin(planetaryjs.plugins.earth({
topojson: { file: '/world-110m.json' },
oceans: { fill: '#001320' },
land: { fill: '#06304e' },
borders: { stroke: '#001320' }
}));
planet.loadPlugin(planetaryjs.plugins.pings());
planet.loadPlugin(planetaryjs.plugins.zoom({
scaleExtent: [50, 5000]
}));
planet.loadPlugin(planetaryjs.plugins.drag({
onDragStart: function() {
this.plugins.autorotate.pause();
},
onDragEnd: function() {
this.plugins.autorotate.resume();
}
}));
planet.loadPlugin(autorotate(5));
planet.projection.rotate([100, -10, 0]);
planet.draw(canvas);
// Create a color scale for the various earthquake magnitudes; the
// minimum magnitude in our data set is 2.5.
var colors = d3.scale.pow()
.exponent(3)
.domain([2, 4, 6, 8, 10])
.range(['white', 'yellow', 'orange', 'red', 'purple']);
// Also create a scale for mapping magnitudes to ping angle sizes
var angles = d3.scale.pow()
.exponent(3)
.domain([2.5, 10])
.range([0.5, 15]);
// And finally, a scale for mapping magnitudes to ping TTLs
var ttls = d3.scale.pow()
.exponent(3)
.domain([2.5, 10])
.range([2000, 5000]);
// Create a key to show the magnitudes and their colors
d3.select('#magnitudes').selectAll('li')
.data(colors.ticks(9))
.enter()
.append('li')
.style('color', colors)
.text(function(d) {
return "Magnitude " + d;
});
// Load our earthquake data and set up the controls.
// The data consists of an array of objects in the following format:
// {
// mag: magnitude_of_quake
// lng: longitude_coordinates
// lat: latitude_coordinates
// time: timestamp_of_quake
// }
// The data is ordered, with the earliest data being the first in the file.
d3.json('/examples/quake/year_quakes_small.json', function(err, data) {
if (err) {
alert("Problem loading the quake data.");
return;
}
var start = parseInt(data[0].time, 10);
var end = parseInt(data[data.length - 1].time, 10);
var currentTime = start;
var lastTick = new Date().getTime();
var updateDate = function() {
d3.select('#date').text(moment(currentTime).utc().format("MMM DD YYYY HH:mm UTC"));
};
// A scale that maps a percentage of playback to a time
// from the data; for example, `50` would map to the halfway
// mark between the first and last items in our data array.
var percentToDate = d3.scale.linear()
.domain([0, 100])
.range([start, end]);
// A scale that maps real time passage to data playback time.
// 12 minutes of real time maps to the entirety of the
// timespan covered by the data.
var realToData = d3.scale.linear()
.domain([0, 1000 * 60 * 12])
.range([0, end - start]);
var paused = false;
// Pause playback and update the time display
// while scrubbing using the range input.
d3.select('#slider')
.on('change', function(d) {
currentTime = percentToDate(d3.event.target.value);
updateDate();
})
.call(d3.behavior.drag()
.on('dragstart', function() {
paused = true;
})
.on('dragend', function() {
paused = false;
})
);
// The main playback loop; for each tick, we'll see how much
// time passed in our accelerated playback reel and find all
// the earthquakes that happened in that timespan, adding
// them to the globe with a color and angle relative to their magnitudes.
d3.timer(function() {
var now = new Date().getTime();
if (paused) {
lastTick = now;
return;
}
var realDelta = now - lastTick;
// Avoid switching back to the window only to see thousands of pings;
// if it's been more than 500 milliseconds since we've updated playback,
// we'll just set the value to 500 milliseconds.
if (realDelta > 500) realDelta = 500;
var dataDelta = realToData(realDelta);
var toPing = data.filter(function(d) {
return d.time > currentTime && d.time <= currentTime + dataDelta;
});
for (var i = 0; i < toPing.length; i++) {
var ping = toPing[i];
planet.plugins.pings.add(ping.lng, ping.lat, {
// Here we use the `angles` and `colors` scales we built earlier
// to convert magnitudes to appropriate angles and colors.
angle: angles(ping.mag),
color: colors(ping.mag),
ttl: ttls(ping.mag)
});
}
currentTime += dataDelta;
if (currentTime > end) currentTime = start;
updateDate();
d3.select('#slider').property('value', percentToDate.invert(currentTime));
lastTick = now;
});
});
// Plugin to resize the canvas to fill the window and to
// automatically center the planet when the window size changes
function autocenter(options) {
options = options || {};
var needsCentering = false;
var globe = null;
var resize = function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
globe.canvas.width = width;
globe.canvas.height = height;
globe.projection.translate([width / 2, height / 2]);
};
return function(planet) {
globe = planet;
planet.onInit(function() {
needsCentering = true;
d3.select(window).on('resize', function() {
needsCentering = true;
});
});
planet.onDraw(function() {
if (needsCentering) { resize(); needsCentering = false; }
});
};
};
// Plugin to automatically scale the planet's projection based
// on the window size when the planet is initialized
function autoscale(options) {
options = options || {};
return function(planet) {
planet.onInit(function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
planet.projection.scale(Math.min(width, height) / 2);
});
};
};
// Plugin to automatically rotate the globe around its vertical
// axis a configured number of degrees every second.
function autorotate(degPerSec) {
return function(planet) {
var lastTick = null;
var paused = false;
planet.plugins.autorotate = {
pause: function() { paused = true; },
resume: function() { paused = false; }
};
planet.onDraw(function() {
if (paused || !lastTick) {
lastTick = new Date();
} else {
var now = new Date();
var delta = now - lastTick;
var rotation = planet.projection.rotate();
rotation[0] += degPerSec * delta / 1000;
if (rotation[0] >= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
lastTick = now;
}
});
};
};
})();

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,145 @@
<div class="ui breadcrumb">
<a href='/examples/' class="section">Examples</a>
<i class="right arrow icon divider"></i>
<div class="active section">Rotating Globe with Pings</div>
</div>
<h1>Rotating Globe with Pings</h1>
<p>This code shows the example from the homepage, which rotates, shows randomly positioned, colored, and sized pings on the globe, and supports mouse-based dragging and zooming. It also shows the creation and use of a plugin, which powers the automatic rotation and exposes a public API.</p>
<p>We're using a specially-made TopoJSON file that includes lake data so that we can draw lakes on the globe with a custom plugin, which you can find at the bottom of the JavaScript. The custom TopoJSON was made using the <a href='https://github.com/mbostock/topojson/wiki/Command-Line-Reference'>TopoJSON command-line tool</a> and data from <a href='http://www.naturalearthdata.com/features/'>Natural Earth</a>; you can also <a href='/world-110m-withlakes.json'>download the JSON file</a> for your own use.</p>
<p>The demo also shows how you can keep your globe from looking pixelated on high density displays by changing the canvas' width and height but keeping its <em>displayed</em> width and height the same via CSS styling.</p>
<div style='text-align: center;'>
<canvas id='rotatingGlobe' width='400' height='400'
style="width: 400px; height: 400px; cursor: move;"></canvas>
</div>
<div class='ui raised segment'>
<div class='ui blue ribbon label'>HTML</div>
<pre class='line-numbers'><code class='language-html'>&lt;canvas id='rotatingGlobe' width='400' height='400'
style='width: 400px; height: 400px; cursor: move;'&gt;&lt;/canvas&gt;</code></pre>
<div class='ui red ribbon label'>JavaScript</div>
<pre class='line-numbers'><code class='language-javascript'>(function() {
var globe = planetaryjs.planet();
// Load our custom `autorotate` plugin; see below.
globe.loadPlugin(autorotate(10));
// The `earth` plugin draws the oceans and the land; it's actually
// a combination of several separate built-in plugins.
//
// Note that we're loading a special TopoJSON file
// (world-110m-withlakes.json) so we can render lakes.
globe.loadPlugin(planetaryjs.plugins.earth({
topojson: { file: '/world-110m-withlakes.json' },
oceans: { fill: '#000080' },
land: { fill: '#339966' },
borders: { stroke: '#008000' }
}));
// Load our custom `lakes` plugin to draw lakes; see below.
globe.loadPlugin(lakes({
fill: '#000080'
}));
// The `pings` plugin draws animated pings on the globe.
globe.loadPlugin(planetaryjs.plugins.pings());
// The `zoom` and `drag` plugins enable
// manipulating the globe with the mouse.
globe.loadPlugin(planetaryjs.plugins.zoom({
scaleExtent: [100, 300]
}));
globe.loadPlugin(planetaryjs.plugins.drag({
// Dragging the globe should pause the
// automatic rotation until we release the mouse.
onDragStart: function() {
this.plugins.autorotate.pause();
},
onDragEnd: function() {
this.plugins.autorotate.resume();
}
}));
// Set up the globe's initial scale, offset, and rotation.
globe.projection.scale(175).translate([175, 175]).rotate([0, -10, 0]);
// Every few hundred milliseconds, we'll draw another random ping.
var colors = ['red', 'yellow', 'white', 'orange', 'green', 'cyan', 'pink'];
setInterval(function() {
var lat = Math.random() * 170 - 85;
var lng = Math.random() * 360 - 180;
var color = colors[Math.floor(Math.random() * colors.length)];
globe.plugins.pings.add(lng, lat, { color: color, ttl: 2000, angle: Math.random() * 10 });
}, 150);
var canvas = document.getElementById('rotatingGlobe');
// Special code to handle high-density displays (e.g. retina, some phones)
// In the future, Planetary.js will handle this by itself (or via a plugin).
if (window.devicePixelRatio == 2) {
canvas.width = 800;
canvas.height = 800;
context = canvas.getContext('2d');
context.scale(2, 2);
}
// Draw that globe!
globe.draw(canvas);
// This plugin will automatically rotate the globe around its vertical
// axis a configured number of degrees every second.
function autorotate(degPerSec) {
// Planetary.js plugins are functions that take a `planet` instance
// as an argument...
return function(planet) {
var lastTick = null;
var paused = false;
planet.plugins.autorotate = {
pause: function() { paused = true; },
resume: function() { paused = false; }
};
// ...and configure hooks into certain pieces of its lifecycle.
planet.onDraw(function() {
if (paused || !lastTick) {
lastTick = new Date();
} else {
var now = new Date();
var delta = now - lastTick;
// This plugin uses the built-in projection (provided by D3)
// to rotate the globe each time we draw it.
var rotation = planet.projection.rotate();
rotation[0] += degPerSec * delta / 1000;
if (rotation[0] &gt;= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
lastTick = now;
}
});
};
};
// This plugin takes lake data from the special
// TopoJSON we're loading and draws them on the map.
function lakes(options) {
options = options || {};
var lakes = null;
return function(planet) {
planet.onInit(function() {
// We can access the data loaded from the TopoJSON plugin
// on its namespace on `planet.plugins`. We're loading a custom
// TopoJSON file with an object called &quot;ne_110m_lakes&quot;.
var world = planet.plugins.topojson.world;
lakes = topojson.feature(world, world.objects.ne_110m_lakes);
});
planet.onDraw(function() {
planet.withSavedContext(function(context) {
context.beginPath();
planet.path.context(context)(lakes);
context.fillStyle = options.fill || 'black';
context.fill();
});
});
};
};
})();</code></pre>
</div>
<%- partial('_scripts_rotating') %>

View File

@ -0,0 +1,117 @@
(function() {
var globe = planetaryjs.planet();
// Load our custom `autorotate` plugin; see below.
globe.loadPlugin(autorotate(10));
// The `earth` plugin draws the oceans and the land; it's actually
// a combination of several separate built-in plugins.
//
// Note that we're loading a special TopoJSON file
// (world-110m-withlakes.json) so we can render lakes.
globe.loadPlugin(planetaryjs.plugins.earth({
topojson: { file: '/world-110m-withlakes.json' },
oceans: { fill: '#000080' },
land: { fill: '#339966' },
borders: { stroke: '#008000' }
}));
// Load our custom `lakes` plugin to draw lakes; see below.
globe.loadPlugin(lakes({
fill: '#000080'
}));
// The `pings` plugin draws animated pings on the globe.
globe.loadPlugin(planetaryjs.plugins.pings());
// The `zoom` and `drag` plugins enable
// manipulating the globe with the mouse.
globe.loadPlugin(planetaryjs.plugins.zoom({
scaleExtent: [100, 300]
}));
globe.loadPlugin(planetaryjs.plugins.drag({
// Dragging the globe should pause the
// automatic rotation until we release the mouse.
onDragStart: function() {
this.plugins.autorotate.pause();
},
onDragEnd: function() {
this.plugins.autorotate.resume();
}
}));
// Set up the globe's initial scale, offset, and rotation.
globe.projection.scale(175).translate([175, 175]).rotate([0, -10, 0]);
// Every few hundred milliseconds, we'll draw another random ping.
var colors = ['red', 'yellow', 'white', 'orange', 'green', 'cyan', 'pink'];
setInterval(function() {
var lat = Math.random() * 170 - 85;
var lng = Math.random() * 360 - 180;
var color = colors[Math.floor(Math.random() * colors.length)];
globe.plugins.pings.add(lng, lat, { color: color, ttl: 2000, angle: Math.random() * 10 });
}, 150);
var canvas = document.getElementById('rotatingGlobe');
// Special code to handle high-density displays (e.g. retina, some phones)
// In the future, Planetary.js will handle this by itself (or via a plugin).
if (window.devicePixelRatio == 2) {
canvas.width = 800;
canvas.height = 800;
context = canvas.getContext('2d');
context.scale(2, 2);
}
// Draw that globe!
globe.draw(canvas);
// This plugin will automatically rotate the globe around its vertical
// axis a configured number of degrees every second.
function autorotate(degPerSec) {
// Planetary.js plugins are functions that take a `planet` instance
// as an argument...
return function(planet) {
var lastTick = null;
var paused = false;
planet.plugins.autorotate = {
pause: function() { paused = true; },
resume: function() { paused = false; }
};
// ...and configure hooks into certain pieces of its lifecycle.
planet.onDraw(function() {
if (paused || !lastTick) {
lastTick = new Date();
} else {
var now = new Date();
var delta = now - lastTick;
// This plugin uses the built-in projection (provided by D3)
// to rotate the globe each time we draw it.
var rotation = planet.projection.rotate();
rotation[0] += degPerSec * delta / 1000;
if (rotation[0] >= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
lastTick = now;
}
});
};
};
// This plugin takes lake data from the special
// TopoJSON we're loading and draws them on the map.
function lakes(options) {
options = options || {};
var lakes = null;
return function(planet) {
planet.onInit(function() {
// We can access the data loaded from the TopoJSON plugin
// on its namespace on `planet.plugins`. We're loading a custom
// TopoJSON file with an object called "ne_110m_lakes".
var world = planet.plugins.topojson.world;
lakes = topojson.feature(world, world.objects.ne_110m_lakes);
});
planet.onDraw(function() {
planet.withSavedContext(function(context) {
context.beginPath();
planet.path.context(context)(lakes);
context.fillStyle = options.fill || 'black';
context.fill();
});
});
};
};
})();

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

View File

@ -16,9 +16,13 @@
<i class='move icon'></i> <i class='move icon'></i>
<div class='content'>Mouse drag + zoom support</div> <div class='content'>Mouse drag + zoom support</div>
</div> </div>
<div class='item'> <!-- <div class='item'>
<i class='lightbulb icon'></i> <i class='lightbulb icon'></i>
<div class='content'><a href='angular.html'>AngularJS integration</a></div> <div class='content'><a href='angular.html'>AngularJS integration</a></div>
</div> -->
<div class='item'>
<i class='puzzle piece icon'></i>
<div class='content'>Extremely extensible via a plugin-based architecture</div>
</div> </div>
<div class='item'> <div class='item'>
<i class='fork code icon'></i> <i class='fork code icon'></i>
@ -27,19 +31,24 @@
</div> </div>
<div class='ui buttons'> <div class='ui buttons'>
<a class='ui green labeled icon button' href='https://github.com/BinaryMuse/planetary.js/releases'><i class='icon download'></i>Download</a> <a class='ui green labeled icon button' href='/download/'><i class='icon download'></i>Download</a>
<div class='or'></div> <div class='or'></div>
<a class='ui labeled button' href='https://github.com/BinaryMuse/planetary.js'>View Source</a> <a class='ui labeled button' href='https://github.com/BinaryMuse/planetary.js' onclick="_gaq.push(['_trackPageview', '/redirect-to-github-project-page']);">View Source</a>
</div>
<div style='padding-top: 10px;'>
Or install with <a href='http://bower.io/'>Bower</a>: <div class='ui small label bower'><i class='icon right arrow'></i> bower install planetary.js</div>
</div> </div>
</div> </div>
<div class='eight wide column left floated'> <div class='eight wide column left floated'>
<div class='ui panel homepage-globe-canvas'> <div class='ui panel homepage-globe-canvas'>
<canvas height='350' width='350' style="width: 350px; height: 350px;" id="homepage-globe-canvas"></canvas> <canvas height='350' width='350' style="width: 350px; height: 350px;" id="homepage-globe-canvas"></canvas>
<br>
<div style="width: 350px; text-align: center; display: inline-block;"> <div style="width: 350px; text-align: center; display: inline-block;">
<div class='ui pointing teal label'> <div class='ui pointing dark blue label'>
<a href='https://github.com/BinaryMuse/planetary.js/blob/master/site/public/js/homepage.js#files' <a href='/examples/rotating.html'
class='detail no-underline'><i class='icon code'></i> View this example's source!</a> class='detail no-underline'><i class='icon code'></i> See how to build this globe</a>
</div> </div>
</div> </div>
</div> </div>
@ -62,28 +71,28 @@
<div class='ui three column stackable divided grid center aligned'> <div class='ui three column stackable divided grid center aligned'>
<div class='column'> <div class='column'>
<a class='ui icon header' href='examples.html'> <a class='ui icon header' href='/examples/'>
<i class='ui huge icon laptop'></i> <i class='ui huge icon laptop'></i>
Examples Examples
</a> </a>
<p>Check out working examples and see what Planetary.js can do</p> <p class='section-description'>Check out working examples and see what Planetary.js can do</p>
<p><a class='ui teal button' href='examples.html'>Explore the Examples</a></p> <p><a class='ui teal button' href='/examples/'>Explore the Examples</a></p>
</div> </div>
<div class='column'> <div class='column'>
<a class='ui icon header' href='documentation.html'> <a class='ui icon header' href='/documentation/'>
<i class='ui huge icon book'></i> <i class='ui huge icon book'></i>
Documentation Documentation
</a> </a>
<p>Download and install Planetary.js and build something awesome</p> <p class='section-description'>See how to install Planetary.js and build something awesome</p>
<p><a class='ui orange button' href='documentation.html'>Peruse the Documentation</a></p> <p><a class='ui orange button' href='/documentation/'>Peruse the Documentation</a></p>
</div> </div>
<div class='column'> <div class='column'>
<a class='ui icon header' href='https://github.com/BinaryMuse/planetary.js'> <a class='ui icon header' href='https://github.com/BinaryMuse/planetary.js' onclick="_gaq.push(['_trackPageview', '/redirect-to-github-project-page']);">
<i class='ui huge icon github alternate'></i> <i class='ui huge icon github alternate'></i>
Source Code Source Code
</a> </a>
<p>Check out the source on GitHub and contribute to the project</p> <p class='section-description'>Take a look at the source on GitHub and contribute to the project</p>
<p><a class='ui purple button' href='https://github.com/BinaryMuse/planetary.js'>Examine the Source</a></p> <p><a class='ui purple button' href='https://github.com/BinaryMuse/planetary.js' onclick="_gaq.push(['_trackPageview', '/redirect-to-github-project-page']);">Examine the Source</a></p>
</div> </div>
</div> </div>

View File

@ -3,15 +3,33 @@
// The `earth` plugin draws the oceans and the land; it's actually // The `earth` plugin draws the oceans and the land; it's actually
// a combination of several separate built-in plugins. // a combination of several separate built-in plugins.
globe.loadPlugin(planetaryjs.plugins.earth({ globe.loadPlugin(planetaryjs.plugins.earth({
topojson: { file: 'world-110m.json' }, topojson: { file: 'world-110m-withlakes.json' },
oceans: { fill: '#000080' }, oceans: { fill: '#000080' },
land: { fill: '#339966' }, land: { fill: '#339966' },
borders: { stroke: '#008000' } borders: { stroke: '#008000' }
})); }));
globe.loadPlugin(lakes({
fill: '#000080'
}));
// The `pings` plugin draws animated pings on the globe. // The `pings` plugin draws animated pings on the globe.
globe.loadPlugin(planetaryjs.plugins.pings()); globe.loadPlugin(planetaryjs.plugins.pings());
// Load our custom `autorotate` plugin; see below. // Load our custom `autorotate` plugin; see below.
globe.loadPlugin(autorotate(10)); globe.loadPlugin(autorotate(10));
// The `zoom` and `drag` plugins enable
// manipulating the globe with the mouse.
globe.loadPlugin(planetaryjs.plugins.zoom({
scaleExtent: [100, 300]
}));
globe.loadPlugin(planetaryjs.plugins.drag({
// Dragging the globe should pause the
// automatic rotation until we release the mouse.
onDragStart: function(planet) {
this.plugins.autorotate.pause();
},
onDragEnd: function(planet) {
this.plugins.autorotate.resume();
}
}))
// Set up the globe's initial scale, offset, and rotation. // Set up the globe's initial scale, offset, and rotation.
globe.projection.scale(175).translate([175, 175]).rotate([0, -10, 0]); globe.projection.scale(175).translate([175, 175]).rotate([0, -10, 0]);
@ -21,8 +39,8 @@
var lat = Math.random() * 170 - 85; var lat = Math.random() * 170 - 85;
var lng = Math.random() * 360 - 180; var lng = Math.random() * 360 - 180;
var color = colors[Math.floor(Math.random() * colors.length)]; var color = colors[Math.floor(Math.random() * colors.length)];
globe.plugins.pings.add(lat, lng, { color: color, ttl: 2000, angle: Math.random() * 10 }); globe.plugins.pings.add(lng, lat, { color: color, ttl: 2000, angle: Math.random() * 10 });
}, 250); }, 150);
var canvas = document.getElementById('homepage-globe-canvas'); var canvas = document.getElementById('homepage-globe-canvas');
// Special code to handle high-density displays (e.g. retina, some phones) // Special code to handle high-density displays (e.g. retina, some phones)
@ -36,6 +54,27 @@
// Draw that globe! // Draw that globe!
globe.draw(canvas); globe.draw(canvas);
function lakes(config) {
config = config || {};
return function(planet) {
var lakes = null;
planet.onInit(function() {
var world = planet.plugins.topojson.world;
lakes = topojson.feature(world, world.objects.ne_110m_lakes);
});
planet.onDraw(function() {
planet.withSavedContext(function(context) {
context.beginPath();
planet.path.context(context)(lakes);
context.fillStyle = config.fill || 'black';
context.fill();
});
});
};
};
// This plugin will automatically rotate the globe around its vertical // This plugin will automatically rotate the globe around its vertical
// axis a configured number of degrees every second. // axis a configured number of degrees every second.
function autorotate(degPerSec) { function autorotate(degPerSec) {
@ -43,9 +82,14 @@
// as an argument... // as an argument...
return function(planet) { return function(planet) {
var lastTick = null; var lastTick = null;
var paused = false;
planet.plugins.autorotate = {
pause: function() { paused = true; },
resume: function() { paused = false; }
};
// ...and configure hooks into certain pieces of its lifecycle. // ...and configure hooks into certain pieces of its lifecycle.
planet.onDraw(function() { planet.onDraw(function() {
if (!lastTick) { if (paused || !lastTick) {
lastTick = new Date(); lastTick = new Date();
} else { } else {
var now = new Date(); var now = new Date();

6
site/public/js/lib/moment.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,2 +1,2 @@
/*! Planetary.js 0.0.0 | (c) 2013 Brandon Tilley | Released under MIT License */ /*! Planetary.js 1.1.2 | (c) 2013 Michelle Tilley | Released under MIT License */
!function(n,t){"function"==typeof define&&define.amd?define(["d3","topojson"],t):"object"==typeof exports?module.exports=t(require("d3"),require("topojson")):n.planetaryjs=t(n.d3,n.topojson,n)}(this,function(n,t,o){"use strict";var e=null;o&&(e=o.planetaryjs);var i=[],r=function(t,o,e){n.timer(function(){t.context.clearRect(0,0,o.width,o.height);for(var n=0;n<e.onDraw.length;n++)e.onDraw[n]()})},l=function(n,t){for(var o=0;o<i.length;o++)t.unshift(i[o]);0==t.length&&(s.plugins.earth&&n.loadPlugin(s.plugins.earth()),s.plugins.pings&&n.loadPlugin(s.plugins.pings()));for(var o=0;o<t.length;o++)t[o](n)},u=function(n,t,o){if(o.onInit.length){var e=0,i=function(n){var t=o.onInit[e];t.length?t(function(){e++,n()}):(t(),e++,setTimeout(n,0))},l=function(){e>=o.onInit.length?r(n,t,o):i(l)};i(l)}else r(n,t,o)},a=function(n,t,o,e){l(n,o),n.canvas=t,n.context=t.getContext("2d"),u(n,t,e)},s={plugins:{},noConflict:function(){return o.planetaryjs=e,s},loadPlugin:function(n){i.push(n)},planet:function(){var t=[],o={onInit:[],onDraw:[]},e={plugins:{},draw:function(n){a(e,n,t,o)},onInit:function(n){o.onInit.push(n)},onDraw:function(n){o.onDraw.push(n)},loadPlugin:function(n){t.push(n)},withSavedContext:function(n){if(!this.context)throw new Error("No canvas to fetch context for");this.context.save(),n(this.context),this.context.restore()}};return e.projection=n.geo.orthographic().clipAngle(90).precision(0),e.path=n.geo.path().projection(e.projection),e}};return s.plugins.topojson=function(t){return function(o){o.onInit(function(e){if(t.world)o.world=t.world,setTimeout(e,0);else{var i=t.file||"world-110m.json";n.json(i,function(n,t){if(n)throw new Error("Could not load JSON "+i);o.world=t,e()})}})}},s.plugins.oceans=function(n){return function(t){t.onDraw(function(){t.withSavedContext(function(o){o.beginPath(),t.path.context(o)({type:"Sphere"}),o.fillStyle=n.fill||"black",o.fill(),0!=n.stroke&&(o.strokeStyle=n.stroke,o.stroke())})})}},s.plugins.land=function(n){return function(o){var e=null;o.onInit(function(){e=t.feature(o.world,o.world.objects.land)}),o.onDraw(function(){o.withSavedContext(function(t){t.beginPath(),o.path.context(t)(e),0!=n.fill&&(t.fillStyle=n.fill||"white",t.fill()),n.stroke&&(t.strokeStyle=n.stroke,t.stroke())})})}},s.plugins.borders=function(n){return function(o){var e=null;o.onInit(function(){var n=o.world.objects.countries;e=t.mesh(o.world,n,function(n,t){return n.id!==t.id})}),o.onDraw(function(){o.withSavedContext(function(t){t.beginPath(),o.path.context(t)(e),t.strokeStyle=n.stroke||"gray",t.stroke()})})}},s.plugins.earth=function(n){var n=n||{},t=n.topojson||{},o=n.oceans||{},e=n.land||{},i=n.borders||{};return function(n){s.plugins.topojson(t)(n),s.plugins.oceans(o)(n),s.plugins.land(e)(n),s.plugins.borders(i)(n)}},s.plugins.pings=function(){var t=[],o=function(n,o,e){var e=e||{};e.color=e.color||"white",e.ttl=e.ttl||2e3,e.angle=e.angle||5,t.push({lat:n,lng:o,time:new Date,options:e})},e=function(n,o,e){for(var r=[],l=0;l<t.length;l++){var u=t[l],a=e-u.time;a<u.options.ttl&&(r.push(u),i(n,o,e,a,u))}t=r},i=function(t,o,e,i,r){var l=1-i/r.options.ttl,u=n.rgb(r.options.color);u="rgba("+u.r+","+u.g+","+u.b+","+l+")",o.strokeStyle=u;var a=n.geo.circle().origin([r.lng,r.lat]).angle(i/r.options.ttl*r.options.angle)();o.beginPath(),t.path.context(o)(a),o.stroke()};return function(n){n.plugins.pings={add:o},n.onDraw(function(){var t=new Date;n.withSavedContext(function(o){e(n,o,t)})})}},s}); !function(n,t){"function"==typeof define&&define.amd?define(["d3","topojson"],function(o,i){return n.planetaryjs=t(o,i,n)}):"object"==typeof exports?module.exports=t(require("d3"),require("topojson")):n.planetaryjs=t(n.d3,n.topojson,n)}(this,function(n,t,o){"use strict";var i=null;o&&(i=o.planetaryjs);var e=[],r=function(t,o,i){n.timer(function(){if(t.stopped)return!0;t.context.clearRect(0,0,o.width,o.height);for(var n=0;n<i.onDraw.length;n++)i.onDraw[n]()})},l=function(n,t){for(var o=e.length-1;o>=0;o--)t.unshift(e[o]);for(0===t.length&&(c.plugins.earth&&n.loadPlugin(c.plugins.earth()),c.plugins.pings&&n.loadPlugin(c.plugins.pings())),o=0;o<t.length;o++)t[o](n)},a=function(n,t,o){if(o.onInit.length){var i=0,e=function(n){var t=o.onInit[i];t.length?t(function(){i++,n()}):(t(),i++,setTimeout(n,0))},l=function(){i>=o.onInit.length?r(n,t,o):e(l)};e(l)}else r(n,t,o)},u=function(n,t,o,i){n.canvas=t,n.context=t.getContext("2d"),n.stopped!==!0&&l(n,o),n.stopped=!1,a(n,t,i)},c={plugins:{},noConflict:function(){return o.planetaryjs=i,c},loadPlugin:function(n){e.push(n)},planet:function(){var t=[],o={onInit:[],onDraw:[],onStop:[]},i={plugins:{},draw:function(n){u(i,n,t,o)},onInit:function(n){o.onInit.push(n)},onDraw:function(n){o.onDraw.push(n)},onStop:function(n){o.onStop.push(n)},loadPlugin:function(n){t.push(n)},stop:function(){i.stopped=!0;for(var n=0;n<o.onStop.length;n++)o.onStop[n](i)},withSavedContext:function(n){if(!this.context)throw new Error("No canvas to fetch context for");this.context.save(),n(this.context),this.context.restore()}};return i.projection=n.geo.orthographic().clipAngle(90),i.path=n.geo.path().projection(i.projection),i}};return c.plugins.topojson=function(t){return function(o){o.plugins.topojson={},o.onInit(function(i){if(t.world)o.plugins.topojson.world=t.world,setTimeout(i,0);else{var e=t.file||"world-110m.json";n.json(e,function(n,t){if(n)throw new Error("Could not load JSON "+e);o.plugins.topojson.world=t,i()})}})}},c.plugins.oceans=function(n){return function(t){t.onDraw(function(){t.withSavedContext(function(o){o.beginPath(),t.path.context(o)({type:"Sphere"}),o.fillStyle=n.fill||"black",o.fill()})})}},c.plugins.land=function(n){return function(o){var i=null;o.onInit(function(){var n=o.plugins.topojson.world;i=t.feature(n,n.objects.land)}),o.onDraw(function(){o.withSavedContext(function(t){t.beginPath(),o.path.context(t)(i),n.fill!==!1&&(t.fillStyle=n.fill||"white",t.fill()),n.stroke&&(n.lineWidth&&(t.lineWidth=n.lineWidth),t.strokeStyle=n.stroke,t.stroke())})})}},c.plugins.borders=function(n){return function(o){var i=null,e={internal:function(n,t){return n.id!==t.id},external:function(n,t){return n.id===t.id},both:function(){return!0}};o.onInit(function(){var r=o.plugins.topojson.world,l=r.objects.countries,a=n.type||"internal";i=t.mesh(r,l,e[a])}),o.onDraw(function(){o.withSavedContext(function(t){t.beginPath(),o.path.context(t)(i),t.strokeStyle=n.stroke||"gray",n.lineWidth&&(t.lineWidth=n.lineWidth),t.stroke()})})}},c.plugins.earth=function(n){n=n||{};var t=n.topojson||{},o=n.oceans||{},i=n.land||{},e=n.borders||{};return function(n){c.plugins.topojson(t)(n),c.plugins.oceans(o)(n),c.plugins.land(i)(n),c.plugins.borders(e)(n)}},c.plugins.pings=function(t){var o=[];t=t||{};var i=function(n,i,e){e=e||{},e.color=e.color||t.color||"white",e.angle=e.angle||t.angle||5,e.ttl=e.ttl||t.ttl||2e3;var r={time:new Date,options:e};t.latitudeFirst?(r.lat=n,r.lng=i):(r.lng=n,r.lat=i),o.push(r)},e=function(n,t,i){for(var e=[],l=0;l<o.length;l++){var a=o[l],u=i-a.time;u<a.options.ttl&&(e.push(a),r(n,t,i,u,a))}o=e},r=function(t,o,i,e,r){var l=1-e/r.options.ttl,a=n.rgb(r.options.color);a="rgba("+a.r+","+a.g+","+a.b+","+l+")",o.strokeStyle=a;var u=n.geo.circle().origin([r.lng,r.lat]).angle(e/r.options.ttl*r.options.angle)();o.beginPath(),t.path.context(o)(u),o.stroke()};return function(n){n.plugins.pings={add:i},n.onDraw(function(){var t=new Date;n.withSavedContext(function(o){e(n,o,t)})})}},c.plugins.zoom=function(t){t=t||{};var o=function(){},i=t.onZoomStart||o,e=t.onZoomEnd||o,r=t.onZoom||o,l=t.afterZoom||o,a=t.initialScale,u=t.scaleExtent||[50,2e3];return function(t){t.onInit(function(){var o=n.behavior.zoom().scaleExtent(u);o.scale(null!==a&&void 0!==a?a:t.projection.scale()),o.on("zoomstart",i.bind(t)).on("zoomend",e.bind(t)).on("zoom",function(){r.call(t),t.projection.scale(n.event.scale),l.call(t)}),n.select(t.canvas).call(o)})}},c.plugins.drag=function(t){t=t||{};var o=function(){},i=t.onDragStart||o,e=t.onDragEnd||o,r=t.onDrag||o,l=t.afterDrag||o;return function(t){t.onInit(function(){var o=n.behavior.drag().on("dragstart",i.bind(t)).on("dragend",e.bind(t)).on("drag",function(){r.call(t);var o=n.event.dx,i=n.event.dy,e=t.projection.rotate(),a=t.projection.scale(),u=n.scale.linear().domain([-1*a,a]).range([-90,90]),c=u(o),s=u(i);e[0]+=c,e[1]-=s,e[1]>90&&(e[1]=90),e[1]<-90&&(e[1]=-90),e[0]>=180&&(e[0]-=360),t.projection.rotate(e),l.call(t)});n.select(t.canvas).call(o)})}},c});

12
site/public/js/prism.js Normal file
View File

@ -0,0 +1,12 @@
/**
* Prism: Lightweight, robust, elegant syntax highlighting
* MIT license http://www.opensource.org/licenses/mit-license.php/
* @author Lea Verou http://lea.verou.me
*/(function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},clone:function(e){var n=t.util.type(e);switch(n){case"Object":var r={};for(var i in e)e.hasOwnProperty(i)&&(r[i]=t.util.clone(e[i]));return r;case"Array":return e.slice()}return e}},languages:{extend:function(e,n){var r=t.util.clone(t.languages[e]);for(var i in n)r[i]=n[i];return r},insertBefore:function(e,n,r,i){i=i||t.languages;var s=i[e],o={};for(var u in s)if(s.hasOwnProperty(u)){if(u==n)for(var a in r)r.hasOwnProperty(a)&&(o[a]=r[a]);o[u]=s[u]}return i[e]=o},DFS:function(e,n){for(var r in e){n.call(e,r,e[r]);t.util.type(e)==="Object"&&t.languages.DFS(e[r],n)}}},highlightAll:function(e,n){var r=document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');for(var i=0,s;s=r[i++];)t.highlightElement(s,e===!0,n)},highlightElement:function(r,i,s){var o,u,a=r;while(a&&!e.test(a.className))a=a.parentNode;if(a){o=(a.className.match(e)||[,""])[1];u=t.languages[o]}if(!u)return;r.className=r.className.replace(e,"").replace(/\s+/g," ")+" language-"+o;a=r.parentNode;/pre/i.test(a.nodeName)&&(a.className=a.className.replace(e,"").replace(/\s+/g," ")+" language-"+o);var f=r.textContent;if(!f)return;f=f.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/\u00a0/g," ");var l={element:r,language:o,grammar:u,code:f};t.hooks.run("before-highlight",l);if(i&&self.Worker){var c=new Worker(t.filename);c.onmessage=function(e){l.highlightedCode=n.stringify(JSON.parse(e.data),o);t.hooks.run("before-insert",l);l.element.innerHTML=l.highlightedCode;s&&s.call(l.element);t.hooks.run("after-highlight",l)};c.postMessage(JSON.stringify({language:l.language,code:l.code}))}else{l.highlightedCode=t.highlight(l.code,l.grammar,l.language);t.hooks.run("before-insert",l);l.element.innerHTML=l.highlightedCode;s&&s.call(r);t.hooks.run("after-highlight",l)}},highlight:function(e,r,i){return n.stringify(t.tokenize(e,r),i)},tokenize:function(e,n,r){var i=t.Token,s=[e],o=n.rest;if(o){for(var u in o)n[u]=o[u];delete n.rest}e:for(var u in n){if(!n.hasOwnProperty(u)||!n[u])continue;var a=n[u],f=a.inside,l=!!a.lookbehind,c=0;a=a.pattern||a;for(var h=0;h<s.length;h++){var p=s[h];if(s.length>e.length)break e;if(p instanceof i)continue;a.lastIndex=0;var d=a.exec(p);if(d){l&&(c=d[1].length);var v=d.index-1+c,d=d[0].slice(c),m=d.length,g=v+m,y=p.slice(0,v+1),b=p.slice(g+1),w=[h,1];y&&w.push(y);var E=new i(u,f?t.tokenize(d,f):d);w.push(E);b&&w.push(b);Array.prototype.splice.apply(s,w)}}}return s},hooks:{all:{},add:function(e,n){var r=t.hooks.all;r[e]=r[e]||[];r[e].push(n)},run:function(e,n){var r=t.hooks.all[e];if(!r||!r.length)return;for(var i=0,s;s=r[i++];)s(n)}}},n=t.Token=function(e,t){this.type=e;this.content=t};n.stringify=function(e,r,i){if(typeof e=="string")return e;if(Object.prototype.toString.call(e)=="[object Array]")return e.map(function(t){return n.stringify(t,r,e)}).join("");var s={type:e.type,content:n.stringify(e.content,r,i),tag:"span",classes:["token",e.type],attributes:{},language:r,parent:i};s.type=="comment"&&(s.attributes.spellcheck="true");t.hooks.run("wrap",s);var o="";for(var u in s.attributes)o+=u+'="'+(s.attributes[u]||"")+'"';return"<"+s.tag+' class="'+s.classes.join(" ")+'" '+o+">"+s.content+"</"+s.tag+">"};if(!self.document){self.addEventListener("message",function(e){var n=JSON.parse(e.data),r=n.language,i=n.code;self.postMessage(JSON.stringify(t.tokenize(i,t.languages[r])));self.close()},!1);return}var r=document.getElementsByTagName("script");r=r[r.length-1];if(r){t.filename=r.src;document.addEventListener&&!r.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)}})();;
Prism.languages.html={comment:/&lt;!--[\w\W]*?-->/g,prolog:/&lt;\?.+?\?>/,doctype:/&lt;!DOCTYPE.+?>/,cdata:/&lt;!\[CDATA\[[\w\W]*?]]>/i,tag:{pattern:/&lt;\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|\w+))?\s*)*\/?>/gi,inside:{tag:{pattern:/^&lt;\/?[\w:-]+/i,inside:{punctuation:/^&lt;\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,inside:{punctuation:/=|>|"/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/&amp;#?[\da-z]{1,8};/gi};Prism.hooks.add("wrap",function(e){e.type==="entity"&&(e.attributes.title=e.content.replace(/&amp;/,"&"))});;
Prism.languages.clike={comment:{pattern:/(^|[^\\])(\/\*[\w\W]*?\*\/|(^|[^:])\/\/.*?(\r?\n|$))/g,lookbehind:!0},string:/("|')(\\?.)*?\1/g,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/ig,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,"function":{pattern:/[a-z0-9_]+\(/ig,inside:{punctuation:/\(/}}, number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,operator:/[-+]{1,2}|!|&lt;=?|>=?|={1,3}|(&amp;){1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};
;
Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(var|let|if|else|while|do|for|return|in|instanceof|function|new|with|typeof|try|throw|catch|finally|null|break|continue)\b/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?|NaN|-?Infinity)\b/g});Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:!0}});Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/(&lt;|<)script[\w\W]*?(>|&gt;)[\w\W]*?(&lt;|<)\/script(>|&gt;)/ig,inside:{tag:{pattern:/(&lt;|<)script[\w\W]*?(>|&gt;)|(&lt;|<)\/script(>|&gt;)/ig,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript}}});
;
Prism.hooks.add("after-highlight",function(e){var t=e.element.parentNode;if(!t||!/pre/i.test(t.nodeName)||t.className.indexOf("line-numbers")===-1){return}var n=1+e.code.split("\n").length;var r;lines=new Array(n);lines=lines.join("<span></span>");r=document.createElement("span");r.className="line-numbers-rows";r.innerHTML=lines;if(t.hasAttribute("data-start")){t.style.counterReset="linenumber "+(parseInt(t.getAttribute("data-start"),10)-1)}e.element.appendChild(r)})
;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,8 @@
(function (root, factory) { (function (root, factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
define(['d3', 'topojson'], factory); define(['d3', 'topojson'], function(d3, topojson) {
return (root.planetaryjs = factory(d3, topojson, root));
});
} else if (typeof exports === 'object') { } else if (typeof exports === 'object') {
module.exports = factory(require('d3'), require('topojson')); module.exports = factory(require('d3'), require('topojson'));
} else { } else {

View File

@ -4,7 +4,11 @@
var doDrawLoop = function(planet, canvas, hooks) { var doDrawLoop = function(planet, canvas, hooks) {
d3.timer(function() { d3.timer(function() {
planet.context.clearRect(0, 0, canvas.width, canvas.height) if (planet.stopped) {
return true;
}
planet.context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < hooks.onDraw.length; i++) { for (var i = 0; i < hooks.onDraw.length; i++) {
hooks.onDraw[i](); hooks.onDraw[i]();
} }
@ -13,19 +17,19 @@
var initPlugins = function(planet, localPlugins) { var initPlugins = function(planet, localPlugins) {
// Add the global plugins to the beginning of the local ones // Add the global plugins to the beginning of the local ones
for (var i = 0; i < plugins.length; i++) { for (var i = plugins.length - 1; i >= 0; i--) {
localPlugins.unshift(plugins[i]); localPlugins.unshift(plugins[i]);
} }
// Load the default plugins if none have been loaded so far // Load the default plugins if none have been loaded so far
if (localPlugins.length == 0) { if (localPlugins.length === 0) {
if (planetaryjs.plugins.earth) if (planetaryjs.plugins.earth)
planet.loadPlugin(planetaryjs.plugins.earth()); planet.loadPlugin(planetaryjs.plugins.earth());
if (planetaryjs.plugins.pings) if (planetaryjs.plugins.pings)
planet.loadPlugin(planetaryjs.plugins.pings()); planet.loadPlugin(planetaryjs.plugins.pings());
} }
for (var i = 0; i < localPlugins.length; i++) { for (i = 0; i < localPlugins.length; i++) {
localPlugins[i](planet); localPlugins[i](planet);
} }
}; };
@ -51,7 +55,7 @@
var check = function() { var check = function() {
if (completed >= hooks.onInit.length) doDrawLoop(planet, canvas, hooks); if (completed >= hooks.onInit.length) doDrawLoop(planet, canvas, hooks);
else doNext(check); else doNext(check);
} };
doNext(check); doNext(check);
} else { } else {
doDrawLoop(planet, canvas, hooks); doDrawLoop(planet, canvas, hooks);
@ -59,11 +63,14 @@
}; };
var startDraw = function(planet, canvas, localPlugins, hooks) { var startDraw = function(planet, canvas, localPlugins, hooks) {
initPlugins(planet, localPlugins);
planet.canvas = canvas; planet.canvas = canvas;
planet.context = canvas.getContext('2d'); planet.context = canvas.getContext('2d');
if (planet.stopped !== true) {
initPlugins(planet, localPlugins);
}
planet.stopped = false;
runOnInitHooks(planet, canvas, hooks); runOnInitHooks(planet, canvas, hooks);
}; };
@ -83,7 +90,8 @@
var localPlugins = []; var localPlugins = [];
var hooks = { var hooks = {
onInit: [], onInit: [],
onDraw: [] onDraw: [],
onStop: []
}; };
var planet = { var planet = {
@ -101,13 +109,24 @@
hooks.onDraw.push(fn); hooks.onDraw.push(fn);
}, },
onStop: function(fn) {
hooks.onStop.push(fn);
},
loadPlugin: function(plugin) { loadPlugin: function(plugin) {
localPlugins.push(plugin); localPlugins.push(plugin);
}, },
stop: function() {
planet.stopped = true;
for (var i = 0; i < hooks.onStop.length; i++) {
hooks.onStop[i](planet);
}
},
withSavedContext: function(fn) { withSavedContext: function(fn) {
if (!this.context) { if (!this.context) {
throw new Error("No canvas to fetch context for") throw new Error("No canvas to fetch context for");
} }
this.context.save(); this.context.save();
@ -117,8 +136,7 @@
}; };
planet.projection = d3.geo.orthographic() planet.projection = d3.geo.orthographic()
.clipAngle(90) .clipAngle(90);
.precision(0);
planet.path = d3.geo.path().projection(planet.projection); planet.path = d3.geo.path().projection(planet.projection);
return planet; return planet;

View File

@ -1,16 +1,18 @@
planetaryjs.plugins.topojson = function(config) { planetaryjs.plugins.topojson = function(config) {
return function(planet) { return function(planet) {
planet.plugins.topojson = {};
planet.onInit(function(done) { planet.onInit(function(done) {
if (config.world) { if (config.world) {
planet.world = config.world; planet.plugins.topojson.world = config.world;
setTimeout(done, 0); setTimeout(done, 0);
} else { } else {
var file = config.file || 'world-110m.json' var file = config.file || 'world-110m.json';
d3.json(file, function(err, world) { d3.json(file, function(err, world) {
if (err) { if (err) {
throw new Error("Could not load JSON " + file); throw new Error("Could not load JSON " + file);
} }
planet.world = world; planet.plugins.topojson.world = world;
done(); done();
}); });
} }
@ -27,11 +29,6 @@
context.fillStyle = config.fill || 'black'; context.fillStyle = config.fill || 'black';
context.fill(); context.fill();
if (config.stroke != false) {
context.strokeStyle = config.stroke;
context.stroke();
}
}); });
}); });
}; };
@ -42,20 +39,22 @@
var land = null; var land = null;
planet.onInit(function() { planet.onInit(function() {
land = topojson.feature(planet.world, planet.world.objects.land); var world = planet.plugins.topojson.world;
}) land = topojson.feature(world, world.objects.land);
});
planet.onDraw(function() { planet.onDraw(function() {
planet.withSavedContext(function(context) { planet.withSavedContext(function(context) {
context.beginPath(); context.beginPath();
planet.path.context(context)(land); planet.path.context(context)(land);
if (config.fill != false) { if (config.fill !== false) {
context.fillStyle = config.fill || 'white'; context.fillStyle = config.fill || 'white';
context.fill(); context.fill();
} }
if (config.stroke) { if (config.stroke) {
if (config.lineWidth) context.lineWidth = config.lineWidth;
context.strokeStyle = config.stroke; context.strokeStyle = config.stroke;
context.stroke(); context.stroke();
} }
@ -67,11 +66,23 @@
planetaryjs.plugins.borders = function(config) { planetaryjs.plugins.borders = function(config) {
return function(planet) { return function(planet) {
var borders = null; var borders = null;
planet.onInit(function() { var borderFns = {
var countries = planet.world.objects.countries; internal: function(a, b) {
borders = topojson.mesh(planet.world, countries, function(a, b) {
return a.id !== b.id; return a.id !== b.id;
}); },
external: function(a, b) {
return a.id === b.id;
},
both: function(a, b) {
return true;
}
};
planet.onInit(function() {
var world = planet.plugins.topojson.world;
var countries = world.objects.countries;
var type = config.type || 'internal';
borders = topojson.mesh(world, countries, borderFns[type]);
}); });
planet.onDraw(function() { planet.onDraw(function() {
@ -79,6 +90,7 @@
context.beginPath(); context.beginPath();
planet.path.context(context)(borders); planet.path.context(context)(borders);
context.strokeStyle = config.stroke || 'gray'; context.strokeStyle = config.stroke || 'gray';
if (config.lineWidth) context.lineWidth = config.lineWidth;
context.stroke(); context.stroke();
}); });
}); });
@ -86,7 +98,7 @@
}; };
planetaryjs.plugins.earth = function(config) { planetaryjs.plugins.earth = function(config) {
var config = config || {}; config = config || {};
var topojsonOptions = config.topojson || {}; var topojsonOptions = config.topojson || {};
var oceanOptions = config.oceans || {}; var oceanOptions = config.oceans || {};
var landOptions = config.land || {}; var landOptions = config.land || {};
@ -102,13 +114,22 @@
planetaryjs.plugins.pings = function(config) { planetaryjs.plugins.pings = function(config) {
var pings = []; var pings = [];
config = config || {};
var addPing = function(lat, lng, options) { var addPing = function(lng, lat, options) {
var options = options || {}; options = options || {};
options.color = options.color || 'white'; options.color = options.color || config.color || 'white';
options.ttl = options.ttl || 2000; options.angle = options.angle || config.angle || 5;
options.angle = options.angle || 5; options.ttl = options.ttl || config.ttl || 2000;
pings.push({ lat: lat, lng: lng, time: new Date(), options: options }); var ping = { time: new Date(), options: options };
if (config.latitudeFirst) {
ping.lat = lng;
ping.lng = lat;
} else {
ping.lng = lng;
ping.lat = lat;
}
pings.push(ping);
}; };
var drawPings = function(planet, context, now) { var drawPings = function(planet, context, now) {
@ -149,3 +170,74 @@
}); });
}; };
}; };
planetaryjs.plugins.zoom = function (options) {
options = options || {};
var noop = function() {};
var onZoomStart = options.onZoomStart || noop;
var onZoomEnd = options.onZoomEnd || noop;
var onZoom = options.onZoom || noop;
var afterZoom = options.afterZoom || noop;
var startScale = options.initialScale;
var scaleExtent = options.scaleExtent || [50, 2000];
return function(planet) {
planet.onInit(function() {
var zoom = d3.behavior.zoom()
.scaleExtent(scaleExtent);
if (startScale !== null && startScale !== undefined) {
zoom.scale(startScale);
} else {
zoom.scale(planet.projection.scale());
}
zoom
.on('zoomstart', onZoomStart.bind(planet))
.on('zoomend', onZoomEnd.bind(planet))
.on('zoom', function() {
onZoom.call(planet);
planet.projection.scale(d3.event.scale);
afterZoom.call(planet);
});
d3.select(planet.canvas).call(zoom);
});
};
};
planetaryjs.plugins.drag = function(options) {
options = options || {};
var noop = function() {};
var onDragStart = options.onDragStart || noop;
var onDragEnd = options.onDragEnd || noop;
var onDrag = options.onDrag || noop;
var afterDrag = options.afterDrag || noop;
return function(planet) {
planet.onInit(function() {
var drag = d3.behavior.drag()
.on('dragstart', onDragStart.bind(planet))
.on('dragend', onDragEnd.bind(planet))
.on('drag', function() {
onDrag.call(planet);
var dx = d3.event.dx;
var dy = d3.event.dy;
var rotation = planet.projection.rotate();
var radius = planet.projection.scale();
var scale = d3.scale.linear()
.domain([-1 * radius, radius])
.range([-90, 90]);
var degX = scale(dx);
var degY = scale(dy);
rotation[0] += degX;
rotation[1] -= degY;
if (rotation[1] > 90) rotation[1] = 90;
if (rotation[1] < -90) rotation[1] = -90;
if (rotation[0] >= 180) rotation[0] -= 360;
planet.projection.rotate(rotation);
afterDrag.call(planet);
});
d3.select(planet.canvas).call(drag);
});
};
};

File diff suppressed because one or more lines are too long