Skip to content
Browse files

version 1.0

- completed README documentation
- first version of red-dwarf.js
  • Loading branch information...
1 parent bfa1c07 commit 2315080b0b756888587f95b39744676ab9042df7 @rviscomi committed Sep 30, 2012
Showing with 412 additions and 2 deletions.
  1. +82 −2 README.md
  2. +330 −0 red-dwarf.js
View
84 README.md
@@ -1,4 +1,84 @@
-red-dwarf
+Red Dwarf
=========
-Google Maps heatmap of GitHub repository stargazers
+![trunk8 heatmap](http://jrvis.com/red-dwarf/img/trunk8-heatmap.jpg)
+
+About
+-----
+**Red Dwarf** is a heatmap visualization of GitHub repository stargazers.
+
+Play with the [live demo](http://jrvis.com/red-dwarf/?rel=github).
+
+How it Works
+------------
+Red Dwarf uses the GitHub API to determine the locations of people who have starred a given repository. Then, using the Google Maps API, these locations are translated into geocoordinates and fed into a heatmap visualization. The result is a beautiful and detailed visualization of global positions of a repository's stargazers.
+
+Getting Started
+---------------
+Red Dwarf depends on Google Maps for geocoding and mapping. You must get a [Google Maps API key](https://developers.google.com/maps/documentation/javascript/tutorial#api_key) to access these services.
+
+Usage
+-----
+Instantiate a new RedDwarf object, the constructor of which accepts a configuration object (see [Settings](#Settings)).
+
+```js
+var stars = new RedDwarf({
+ user: config.user,
+ repository: config.repository,
+ map_id: config.map_id
+});
+```
+
+Settings
+--------
+* **user** (required)
+ The GitHub user login of the repository owner.
+* **repository** (required)
+ The GitHub repository name.
+* **map_id** (required)
+ The ID of the HTML element in which to draw the map.
+* **cache_location** (optional)
+ The path (relative or absolute) of a JSON file containing precomputed geolocation data. If omitted, Red Dwarf will compute all data from scratch (see [Performance](#Performance)). *Note: this file's contents are equivalent to the output of the [toJSON](#Methods) method.*
+* **map_zoom** The initial zoom level of the heatmap. *Default: 2.* ([more info](https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions))
+* **map_lat** The initial latitude position on which the heatmap is centered. *Default: 20.* ([more info](https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions))
+* **map_lng** The initial longitude position on which the heatmap is centered. *Default: 0.* ([more info](https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions))
+* **map_type** The initial type of the heatmap: road, satellite, hybrid, or terrain. *Default: road.* ([more info](https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions))
+
+Methods
+-------
+* **toJSON** Returns a JSON representation of a mapping of string locations to geocodes, the number of repository stars, and a mapping of stargazers' user logins to their resppective user objects.
+
+Events
+------
+Red Dwarf will trigger each of the following events during processing. Arguments passed to the event handlers are listed below the event name (where applicable).
+
+Event handlers are defined by including functions keyed by the respective event name in the settings object.
+
+* **onRepositoryLoaded** Fired after successfully loading repository info from the GitHub API.
+ * **data** The data object returned by GitHub.
+* **onCacheLoaded** Fired after successfully loading the JSON cache file.
+* **onStargazersUpdated** Fired after processing a chunk of at most 100 repository stargazers.
+ * **num_stargazers** The number of stargazers processed so far.
+* **onStargazersLoaded** Fired after successfully loading all stargazers.
+* **onLocationUpdated** Fired after successfully loading a single stargazer's profile.
+ * **num_resolved_stargazers** The number of stargazers whose profiles have been loaded so far.
+ * **num_stargazers** The total number of profiles to load.
+* **onLocationLoaded** Fired after successfully loading all stargazers' profiles.
+* **onPointsUpdated** Fired after geocoding a chunk of at most 10 stargazer locations.
+ * **num_resolved_points** The number of locations geocoded so far.
+ * **num_stargazers** The total number of locations to geocode.
+* **onPointsLoaded** Fired after successfully geocoding all locations and drawing the heatmap.
+
+Performance
+-----------
+It's important to precache the geolocation data because the Google Maps geocoding API places strict limits on the frequency of requests. Trial and error indicates that this limit is in the neighborhood of 40 requests per minute. This means repository with 200 stars would take 5 minutes to get all geocoordinates. By default, Red Dwarf rate limits requests to this API using a technique based on work by [Nicholas Zakas](http://www.nczonline.net/blog/2009/08/11/timed-array-processing-in-javascript/).
+
+MIT License
+-----------
+Copyright (c) 2012 Rick Viscomi (rviscomi@gmail.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
View
330 red-dwarf.js
@@ -0,0 +1,330 @@
+/**!
+ * red dwarf v1.0
+ * https://github.com/rviscomi/red-dwarf
+ *
+ * Copyright 2012 Rick Viscomi
+ * Released under the MIT License.
+ *
+ * Date: September 30, 2012
+ */
+
+(function () {
+ 'use strict';
+
+ function RedDwarf(options) {
+ /* Validate options. */
+ if (!options.user ||
+ !options.repository ||
+ !options.map_id) {
+ throw 'RedDwarf requires an object with properties "user", "repository", and "map_id".';
+ }
+
+ /* Require jQuery. */
+ if (!jQuery) {
+ throw 'RedDwarf requires jQuery.';
+ }
+
+ /* Require JSON. */
+ if (!JSON) {
+ throw 'RedDwarf requires JSON. Check your browser support.';
+ }
+
+ this.user = options.user;
+ this.repository = options.repository;
+ this.map_id = options.map_id;
+ this.cache_location = options.cache_location || '';
+ this.num_stargazers = 0;
+ this.stargazers = {};
+ this.points = [];
+ this.geocodes = {};
+
+ /* Require Google Maps API. */
+ if (this.hasMapsAPI()) {
+ this.drawMap(options.map_zoom, options.map_lat, options.map_lng, options.map_type);
+ }
+ else {
+ throw 'RedDwarf requires the Google Maps JavaScript API.';
+ }
+
+ /* Event hooks. */
+ this.onRepositoryLoaded = options.onRepositoryLoaded || function () {};
+ this.onCacheLoaded = options.onCacheLoaded || function () {};
+ this.onStargazersUpdated = options.onStargazersUpdated || function () {};
+ this.onStargazersLoaded = options.onStargazersLoaded || function () {};
+ this.onLocationUpdated = options.onLocationUpdated || function () {};
+ this.onLocationLoaded = options.onLocationLoaded || function () {};
+ this.onPointsUpdated = options.onPointsUpdated || function () {};
+ this.onPointsLoaded = options.onPointsLoaded || function () {};
+
+ this.start();
+ }
+
+ RedDwarf.prototype.start = function () {
+ var cache_loaded = false,
+ repo_loaded = false,
+ that = this;
+
+ /* Load the JSON cache file. */
+ if (this.cache_location) {
+ this.loadCache(function () {
+ /* After cache load and repo load are completed. */
+ if (repo_loaded) {
+ that.onInitialized();
+ }
+
+ cache_loaded = true;
+ });
+ }
+ else {
+ cache_loaded = true;
+ }
+
+ /* Load the repository info.*/
+ this.loadRepository(function () {
+ /* After cache load and repo load are completed. */
+ if (cache_loaded) {
+ that.onInitialized();
+ }
+
+ repo_loaded = true;
+ });
+ };
+
+ RedDwarf.prototype.loadCache = function (onComplete) {
+ var that = this;
+
+ $.ajax({
+ url: this.cache_location,
+ dataType: 'json',
+ success: function (data) {
+ var location = null,
+ geocode;
+
+ if (data) {
+ that.num_cached_stargazers = data.num_stargazers || 0;
+ that.stargazers = data.stargazers || {};
+
+ /* Convert geocodes to pairs of locations to LatLngs. */
+ for (location in data.geocodes) {
+ if (data.geocodes.hasOwnProperty(location)) {
+ geocode = data.geocodes[location];
+ that.geocodes[location] = geocode;
+ that.points.push(new google.maps.LatLng(geocode.Xa, geocode.Ya));
+ }
+ }
+ }
+
+ that.onCacheLoaded();
+ },
+ complete: onComplete
+ });
+ };
+
+ RedDwarf.prototype.loadRepository = function (onComplete) {
+ var that = this;
+
+ $.ajax({
+ url: 'https://api.github.com/repos/' + this.user + '/' +
+ this.repository,
+ dataType: 'json',
+ success: function (data) {
+ that.num_stargazers = data.watchers; // TODO data.stargazers?
+
+ that.onRepositoryLoaded(data);
+ },
+ complete: onComplete
+ });
+ };
+
+ RedDwarf.prototype.onInitialized = function () {
+ if (this.num_stargazers <= this.num_cached_stargazers) {
+ this.drawHeatmap();
+ }
+ else {
+ this.appendStargazers();
+ }
+ };
+
+ RedDwarf.prototype.appendStargazers = function () {
+ var that = this,
+ page = 1,
+ num_stargazers = 0,
+ stargazers = [];
+
+ function loadStargazers() {
+ $.ajax({
+ url: 'https://api.github.com/repos/' + that.user + '/' +
+ that.repository + '/stargazers',
+ data: {
+ page: page,
+ per_page: 100
+ },
+ dataType: 'jsonp',
+ success: function (data, textStatus, xhr) {
+ var i, n, stargazer;
+
+ if (textStatus === 'success' && data.meta.status === 200) {
+ n = data.data.length;
+
+ /* Add new stargazers to instance property. */
+ for (i = 0; i < n; i++) {
+ stargazer = data.data[i];
+
+ /* If this stargazer is not in cache, do lookup. */
+ if (!that.stargazers[stargazer.login]) {
+ that.stargazers[stargazer.login] = stargazer;
+
+ stargazers.push(stargazer);
+ }
+ }
+
+ num_stargazers += n;
+ that.onStargazersUpdated(num_stargazers);
+ }
+
+ if (num_stargazers < that.num_stargazers) {
+ page++;
+ loadStargazers();
+ }
+ else {
+ that.onStargazersLoaded();
+
+ that.getStargazersLocation(stargazers);
+ }
+ }
+ });
+ }
+
+ loadStargazers();
+ };
+
+ RedDwarf.prototype.getStargazersLocation = function (stargazers) {
+ var that = this,
+ n = stargazers.length,
+ num_resolved_stargazers = 0,
+ locations = [],
+ i, stargazer;
+
+ for (i = 0; i < n; i++) {
+ stargazer = stargazers[i];
+
+ $.ajax({
+ url: stargazer.url,
+ dataType: 'jsonp',
+ success: function (data, textStatus, xhr) {
+ var location = '';
+
+ num_resolved_stargazers++;
+
+ if (textStatus === 'success' && data.meta.status === 200) {
+ location = data.data.location;
+ }
+
+ if (location && !that.points[location]) {
+ locations.push(location);
+ }
+
+ that.onLocationUpdated(num_resolved_stargazers, n);
+
+ if (num_resolved_stargazers === n) {
+ that.onLocationLoaded();
+
+ that.getGeoCoordinates(locations);
+ }
+ }
+ });
+ }
+ };
+
+ RedDwarf.prototype.getGeoCoordinates = function (locations) {
+ var that = this,
+ geo = new google.maps.Geocoder(),
+ OK = google.maps.GeocoderStatus.OK;
+
+ /* Delay to avoid maxing out Google API. */
+ timedChunk(locations, function (location) {
+ geo.geocode({address: location}, function (results, status) {
+ if (status === OK) {
+ that.points.push(results[0].geometry.location);
+ that.geocodes[location] = results[0].geometry.location;
+ }
+ });
+
+ that.onPointsUpdated(that.points.length, that.num_stargazers);
+ }, this, this.drawHeatmap, 15e3, 10);
+ };
+
+ RedDwarf.prototype.drawMap = function (zoom, lat, lng, type) {
+ zoom = zoom || 2;
+ lat = lat || 20;
+ lng = lng || 0;
+ type = type || google.maps.MapTypeId.ROADMAP;
+
+ this.map = new google.maps.Map(document.getElementById(this.map_id), {
+ zoom: zoom,
+ center: new google.maps.LatLng(lat, lng),
+ mapTypeId: type
+ });
+ };
+
+ RedDwarf.prototype.drawHeatmap = function () {
+ new google.maps.visualization.HeatmapLayer({
+ data: this.points,
+ map: this.map,
+ radius: 25
+ });
+
+ this.onPointsLoaded();
+ };
+
+ RedDwarf.prototype.hasMapsAPI = function () {
+ /* Check all Google API dependencies. */
+ return (google &&
+ google.maps &&
+ google.maps.Map &&
+ google.maps.MapTypeId &&
+ google.maps.MapTypeId.ROADMAP &&
+ google.maps.Geocoder &&
+ google.maps.GeocoderStatus &&
+ google.maps.GeocoderStatus.OK &&
+ google.maps.LatLng &&
+ google.maps.visualization &&
+ google.maps.visualization.HeatmapLayer);
+ };
+
+ RedDwarf.prototype.toJSON = function () {
+ return JSON.stringify({
+ num_stargazers: this.num_stargazers,
+ stargazers: this.stargazers,
+ geocodes: this.geocodes
+ });
+ };
+
+ /*! Copyright 2009 Nicholas C. Zakas. All rights reserved. MIT Licensed */
+ function timedChunk(items, process, context, callback, delay, maxItems) {
+ var n = items.length,
+ delay = delay || 25,
+ maxItems = maxItems || n,
+ i = 0;
+
+ setTimeout(function chunkTimer(){
+ var start = +new Date(),
+ j = i;
+
+ while (i < n && (i - j) < maxItems && (new Date() - start < 50)) {
+ process.call(context, items[i]);
+ i += 1;
+ }
+
+ if (i < n) {
+ setTimeout(chunkTimer, delay);
+ }
+ else {
+ callback.call(context, items);
+ }
+ }, 25);
+ }
+
+ /* Expose as a global object. */
+ window.RedDwarf = RedDwarf;
+})();

0 comments on commit 2315080

Please sign in to comment.
Something went wrong with that request. Please try again.