nv.d3.datamaps.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. (function() {
  17. var svg;
  18. //save off default references
  19. var d3 = window.d3, topojson = window.topojson;
  20. var defaultOptions = {
  21. scope: 'world',
  22. setProjection: setProjection,
  23. projection: 'equirectangular',
  24. dataType: 'json',
  25. onClick: function() {},
  26. done: function() {},
  27. fills: {
  28. defaultFill: '#ABDDA4'
  29. },
  30. geographyConfig: {
  31. dataUrl: null,
  32. hideAntarctica: true,
  33. borderWidth: 1,
  34. borderColor: '#FDFDFD',
  35. popupTemplate: function(geography, data) {
  36. return '<div class="hoverinfo"><strong>' + geography.properties.name + '</strong></div>';
  37. },
  38. popupOnHover: true,
  39. highlightOnHover: true,
  40. highlightFillColor: '#FC8D59',
  41. highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
  42. highlightBorderWidth: 2
  43. },
  44. bubblesConfig: {
  45. borderWidth: 2,
  46. borderColor: '#FFFFFF',
  47. popupOnHover: true,
  48. popupTemplate: function(geography, data) {
  49. return '<div class="hoverinfo"><strong>' + data.name + '</strong></div>';
  50. },
  51. fillOpacity: 0.75,
  52. animate: true,
  53. highlightOnHover: true,
  54. highlightFillColor: '#FC8D59',
  55. highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
  56. highlightBorderWidth: 2,
  57. highlightFillOpacity: 0.85,
  58. exitDelay: 100
  59. },
  60. arcConfig: {
  61. strokeColor: '#DD1C77',
  62. strokeWidth: 1,
  63. arcSharpness: 1,
  64. animationSpeed: 600
  65. }
  66. };
  67. function addContainer( element ) {
  68. this.svg = d3.select( element ).append('svg')
  69. .attr('width', element.offsetWidth)
  70. .attr('class', 'datamap')
  71. .attr('height', element.offsetHeight);
  72. return this.svg;
  73. }
  74. // setProjection takes the svg element and options
  75. function setProjection( element, options ) {
  76. var projection, path;
  77. if ( options && typeof options.scope === 'undefined') {
  78. options.scope = 'world';
  79. }
  80. if ( options.scope === 'usa' ) {
  81. projection = d3.geo.albersUsa()
  82. .scale(element.offsetWidth)
  83. .translate([element.offsetWidth / 2, element.offsetHeight / 2]);
  84. }
  85. else if ( options.scope === 'world' ) {
  86. projection = d3.geo[options.projection]()
  87. .scale((element.offsetWidth + 1) / 2 / Math.PI)
  88. .translate([element.offsetWidth / 2, element.offsetHeight / (options.projection === "mercator" ? 1.45 : 1.8)]);
  89. }
  90. path = d3.geo.path()
  91. .projection( projection );
  92. return {path: path, projection: projection};
  93. }
  94. function addStyleBlock() {
  95. if ( d3.select('.datamaps-style-block').empty() ) {
  96. d3.select('head').attr('class', 'datamaps-style-block').append('style')
  97. .html('.datamap path {stroke: #FFFFFF; stroke-width: 1px;} .datamaps-legend dt, .datamaps-legend dd { float: left; margin: 0 3px 0 0;} .datamaps-legend dd {width: 20px; margin-right: 6px; border-radius: 3px;} .datamaps-legend {padding-bottom: 20px; z-index: 1001; position: absolute; left: 4px; font-size: 12px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;} .datamaps-hoverover {display: none; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .hoverinfo {padding: 4px; border-radius: 1px; background-color: #FFF; box-shadow: 1px 1px 5px #CCC; font-size: 12px; border: 1px solid #CCC; } .hoverinfo hr {border:1px dotted #CCC; }');
  98. }
  99. }
  100. function drawSubunits( data ) {
  101. var fillData = this.options.fills,
  102. colorCodeData = this.options.data || {},
  103. geoConfig = this.options.geographyConfig,
  104. onClick = this.options.onClick;
  105. var subunits = this.svg.select('g.datamaps-subunits');
  106. if ( subunits.empty() ) {
  107. subunits = this.addLayer('datamaps-subunits', null, true);
  108. }
  109. var geoData = topojson.feature( data, data.objects[ this.options.scope ] ).features;
  110. if ( geoConfig.hideAntarctica ) {
  111. geoData = geoData.filter(function(feature) {
  112. return feature.id !== "ATA";
  113. });
  114. }
  115. var geo = subunits.selectAll('path.datamaps-subunit').data( geoData );
  116. geo.enter()
  117. .append('path')
  118. .attr('d', this.path)
  119. .attr('class', function(d) {
  120. return 'datamaps-subunit ' + d.id;
  121. })
  122. .attr('data-info', function(d) {
  123. return JSON.stringify( colorCodeData[d.id]);
  124. })
  125. .style('fill', function(d) {
  126. var fillColor;
  127. if ( colorCodeData[d.id] ) {
  128. fillColor = fillData[ colorCodeData[d.id].fillKey ];
  129. }
  130. return fillColor || fillData.defaultFill;
  131. })
  132. .on('click', function(d) {
  133. if ( colorCodeData[d.id] && typeof onClick != "undefined") {
  134. onClick(colorCodeData[d.id]);
  135. }
  136. })
  137. .style('stroke-width', geoConfig.borderWidth)
  138. .style('stroke', geoConfig.borderColor);
  139. }
  140. function handleGeographyConfig () {
  141. var hoverover;
  142. var svg = this.svg;
  143. var self = this;
  144. var options = this.options.geographyConfig;
  145. if ( options.highlightOnHover || options.popupOnHover ) {
  146. svg.selectAll('.datamaps-subunit')
  147. .on('mouseover', function(d) {
  148. var $this = d3.select(this);
  149. if ( options.highlightOnHover ) {
  150. var previousAttributes = {
  151. 'fill': $this.style('fill'),
  152. 'stroke': $this.style('stroke'),
  153. 'stroke-width': $this.style('stroke-width'),
  154. 'fill-opacity': $this.style('fill-opacity')
  155. };
  156. $this
  157. .style('fill', options.highlightFillColor)
  158. .style('stroke', options.highlightBorderColor)
  159. .style('stroke-width', options.highlightBorderWidth)
  160. .style('fill-opacity', options.highlightFillOpacity)
  161. .attr('data-previousAttributes', JSON.stringify(previousAttributes));
  162. //as per discussion on https://github.com/markmarkoh/datamaps/issues/19
  163. if ( ! /MSIE/.test(navigator.userAgent) ) {
  164. moveToFront.call(this);
  165. }
  166. }
  167. if ( options.popupOnHover ) {
  168. self.updatePopup($this, d, options, svg);
  169. }
  170. })
  171. .on('mouseout', function() {
  172. var $this = d3.select(this);
  173. if (options.highlightOnHover) {
  174. //reapply previous attributes
  175. var previousAttributes = JSON.parse( $this.attr('data-previousAttributes') );
  176. for ( var attr in previousAttributes ) {
  177. $this.style(attr, previousAttributes[attr]);
  178. }
  179. }
  180. $this.on('mousemove', null);
  181. d3.selectAll('.datamaps-hoverover').style('display', 'none');
  182. });
  183. }
  184. function moveToFront() {
  185. this.parentNode.appendChild(this);
  186. }
  187. }
  188. //plugin to add a simple map legend
  189. function addLegend(layer, data, options) {
  190. data = data || {};
  191. if ( !this.options.fills ) {
  192. return;
  193. }
  194. var html = '<dl>';
  195. var label = '';
  196. if ( data.legendTitle ) {
  197. html = '<h2>' + data.legendTitle + '</h2>' + html;
  198. }
  199. for ( var fillKey in this.options.fills ) {
  200. if ( fillKey === 'defaultFill') {
  201. if (! data.defaultFillName ) {
  202. continue;
  203. }
  204. label = data.defaultFillName;
  205. } else {
  206. if (data.labels && data.labels[fillKey]) {
  207. label = data.labels[fillKey];
  208. } else {
  209. label= fillKey + ': ';
  210. }
  211. }
  212. html += '<dt>' + label + '</dt>';
  213. html += '<dd style="background-color:' + this.options.fills[fillKey] + '">&nbsp;</dd>';
  214. }
  215. html += '</dl>';
  216. var hoverover = d3.select( this.options.element ).append('div')
  217. .attr('class', 'datamaps-legend')
  218. .html(html);
  219. }
  220. function handleArcs (layer, data, options) {
  221. var self = this,
  222. svg = this.svg;
  223. if ( !data || (data && !data.slice) ) {
  224. throw "Datamaps Error - arcs must be an array";
  225. }
  226. if ( typeof options === "undefined" ) {
  227. options = defaultOptions.arcConfig;
  228. }
  229. var arcs = layer.selectAll('path.datamaps-arc').data( data, JSON.stringify );
  230. arcs
  231. .enter()
  232. .append('svg:path')
  233. .attr('class', 'datamaps-arc')
  234. .style('stroke-linecap', 'round')
  235. .style('stroke', function(datum) {
  236. if ( datum.options && datum.options.strokeColor) {
  237. return datum.options.strokeColor;
  238. }
  239. return options.strokeColor
  240. })
  241. .style('fill', 'none')
  242. .style('stroke-width', function(datum) {
  243. if ( datum.options && datum.options.strokeWidth) {
  244. return datum.options.strokeWidth;
  245. }
  246. return options.strokeWidth;
  247. })
  248. .attr('d', function(datum) {
  249. var originXY = self.latLngToXY(datum.origin.latitude, datum.origin.longitude);
  250. var destXY = self.latLngToXY(datum.destination.latitude, datum.destination.longitude);
  251. var midXY = [ (originXY[0] + destXY[0]) / 2, (originXY[1] + destXY[1]) / 2];
  252. return "M" + originXY[0] + ',' + originXY[1] + "S" + (midXY[0] + (50 * options.arcSharpness)) + "," + (midXY[1] - (75 * options.arcSharpness)) + "," + destXY[0] + "," + destXY[1];
  253. })
  254. .transition()
  255. .delay(100)
  256. .style('fill', function() {
  257. /*
  258. Thank you Jake Archibald, this is awesome.
  259. Source: http://jakearchibald.com/2013/animated-line-drawing-svg/
  260. */
  261. var length = this.getTotalLength();
  262. this.style.transition = this.style.WebkitTransition = 'none';
  263. this.style.strokeDasharray = length + ' ' + length;
  264. this.style.strokeDashoffset = length;
  265. this.getBoundingClientRect();
  266. this.style.transition = this.style.WebkitTransition = 'stroke-dashoffset ' + options.animationSpeed + 'ms ease-out';
  267. this.style.strokeDashoffset = '0';
  268. return 'none';
  269. })
  270. arcs.exit()
  271. .transition()
  272. .style('opacity', 0)
  273. .remove();
  274. }
  275. function handleLabels ( layer, options ) {
  276. var self = this;
  277. options = options || {};
  278. var labelStartCoodinates = this.projection([-67.707617, 42.722131]);
  279. this.svg.selectAll(".datamaps-subunit")
  280. .attr("data-foo", function(d) {
  281. var center = self.path.centroid(d);
  282. var xOffset = 7.5, yOffset = 5;
  283. if ( ["FL", "KY", "MI"].indexOf(d.id) > -1 ) xOffset = -2.5;
  284. if ( d.id === "NY" ) xOffset = -1;
  285. if ( d.id === "MI" ) yOffset = 18;
  286. if ( d.id === "LA" ) xOffset = 13;
  287. var x,y;
  288. x = center[0] - xOffset;
  289. y = center[1] + yOffset;
  290. var smallStateIndex = ["VT", "NH", "MA", "RI", "CT", "NJ", "DE", "MD", "DC"].indexOf(d.id);
  291. if ( smallStateIndex > -1) {
  292. var yStart = labelStartCoodinates[1];
  293. x = labelStartCoodinates[0];
  294. y = yStart + (smallStateIndex * (2+ (options.fontSize || 12)));
  295. layer.append("line")
  296. .attr("x1", x - 3)
  297. .attr("y1", y - 5)
  298. .attr("x2", center[0])
  299. .attr("y2", center[1])
  300. .style("stroke", options.labelColor || "#000")
  301. .style("stroke-width", options.lineWidth || 1)
  302. }
  303. layer.append("text")
  304. .attr("x", x)
  305. .attr("y", y)
  306. .style("font-size", (options.fontSize || 10) + 'px')
  307. .style("font-family", options.fontFamily || "Verdana")
  308. .style("fill", options.labelColor || "#000")
  309. .text( d.id );
  310. return "bar";
  311. });
  312. }
  313. function handleBubbles (layer, data, options ) {
  314. var self = this,
  315. fillData = this.options.fills,
  316. svg = this.svg;
  317. if ( !data || (data && !data.slice) ) {
  318. throw "Datamaps Error - bubbles must be an array";
  319. }
  320. var bubbles = layer.selectAll('circle.datamaps-bubble').data( data, JSON.stringify );
  321. bubbles
  322. .enter()
  323. .append('svg:circle')
  324. .attr('class', 'datamaps-bubble')
  325. .attr('cx', function ( datum ) {
  326. var latLng;
  327. if ( datumHasCoords(datum) ) {
  328. latLng = self.latLngToXY(datum.latitude, datum.longitude);
  329. }
  330. else if ( datum.centered ) {
  331. latLng = self.path.centroid(svg.select('path.' + datum.centered).data()[0]);
  332. }
  333. if ( latLng ) return latLng[0];
  334. })
  335. .attr('cy', function ( datum ) {
  336. var latLng;
  337. if ( datumHasCoords(datum) ) {
  338. latLng = self.latLngToXY(datum.latitude, datum.longitude);
  339. }
  340. else if ( datum.centered ) {
  341. latLng = self.path.centroid(svg.select('path.' + datum.centered).data()[0]);
  342. }
  343. if ( latLng ) return latLng[1];;
  344. })
  345. .attr('r', 0) //for animation purposes
  346. .attr('data-info', function(d) {
  347. return JSON.stringify(d);
  348. })
  349. .style('stroke', options.borderColor)
  350. .style('stroke-width', options.borderWidth)
  351. .style('fill-opacity', options.fillOpacity)
  352. .style('fill', function ( datum ) {
  353. var fillColor = fillData[ datum.fillKey ];
  354. return fillColor || fillData.defaultFill;
  355. })
  356. .on('mouseover', function ( datum ) {
  357. var $this = d3.select(this);
  358. if (options.highlightOnHover) {
  359. //save all previous attributes for mouseout
  360. var previousAttributes = {
  361. 'fill': $this.style('fill'),
  362. 'stroke': $this.style('stroke'),
  363. 'stroke-width': $this.style('stroke-width'),
  364. 'fill-opacity': $this.style('fill-opacity')
  365. };
  366. $this
  367. .style('fill', options.highlightFillColor)
  368. .style('stroke', options.highlightBorderColor)
  369. .style('stroke-width', options.highlightBorderWidth)
  370. .style('fill-opacity', options.highlightFillOpacity)
  371. .attr('data-previousAttributes', JSON.stringify(previousAttributes));
  372. }
  373. if (options.popupOnHover) {
  374. self.updatePopup($this, datum, options, svg);
  375. }
  376. })
  377. .on('mouseout', function ( datum ) {
  378. var $this = d3.select(this);
  379. if (options.highlightOnHover) {
  380. //reapply previous attributes
  381. var previousAttributes = JSON.parse( $this.attr('data-previousAttributes') );
  382. for ( var attr in previousAttributes ) {
  383. $this.style(attr, previousAttributes[attr]);
  384. }
  385. }
  386. d3.selectAll('.datamaps-hoverover').style('display', 'none');
  387. })
  388. .transition().duration(400)
  389. .attr('r', function ( datum ) {
  390. return datum.radius;
  391. });
  392. bubbles.exit()
  393. .transition()
  394. .delay(options.exitDelay)
  395. .attr("r", 0)
  396. .remove();
  397. function datumHasCoords (datum) {
  398. return typeof datum !== 'undefined' && typeof datum.latitude !== 'undefined' && typeof datum.longitude !== 'undefined';
  399. }
  400. }
  401. //stolen from underscore.js
  402. function defaults(obj) {
  403. Array.prototype.slice.call(arguments, 1).forEach(function(source) {
  404. if (source) {
  405. for (var prop in source) {
  406. if (obj[prop] == null) obj[prop] = source[prop];
  407. }
  408. }
  409. });
  410. return obj;
  411. }
  412. /**************************************
  413. Public Functions
  414. ***************************************/
  415. function Datamap( options ) {
  416. if ( typeof d3 === 'undefined' || typeof topojson === 'undefined' ) {
  417. throw new Error('Include d3.js (v3.0.3 or greater) and topojson on this page before creating a new map');
  418. }
  419. //set options for global use
  420. this.options = defaults(options, defaultOptions);
  421. this.options.geographyConfig = defaults(options.geographyConfig, defaultOptions.geographyConfig);
  422. this.options.bubblesConfig = defaults(options.bubblesConfig, defaultOptions.bubblesConfig);
  423. this.options.arcConfig = defaults(options.arcConfig, defaultOptions.arcConfig);
  424. //add the SVG container
  425. if ( d3.select( this.options.element ).select('svg').length > 0 ) {
  426. addContainer.call(this, this.options.element );
  427. }
  428. /* Add core plugins to this instance */
  429. this.addPlugin('bubbles', handleBubbles);
  430. this.addPlugin('legend', addLegend);
  431. this.addPlugin('arc', handleArcs);
  432. this.addPlugin('labels', handleLabels);
  433. //append style block with basic hoverover styles
  434. if ( ! this.options.disableDefaultStyles ) {
  435. addStyleBlock();
  436. }
  437. return this.draw();
  438. }
  439. // actually draw the features(states & countries)
  440. Datamap.prototype.draw = function() {
  441. //save off in a closure
  442. var self = this;
  443. var options = self.options;
  444. //set projections and paths based on scope
  445. var pathAndProjection = options.setProjection.apply(self, [options.element, options] );
  446. this.path = pathAndProjection.path;
  447. this.projection = pathAndProjection.projection;
  448. //if custom URL for topojson data, retrieve it and render
  449. if ( options.geographyConfig.dataUrl ) {
  450. d3.json( options.geographyConfig.dataUrl, function(error, results) {
  451. if ( error ) throw new Error(error);
  452. self.customTopo = results;
  453. draw( results );
  454. });
  455. }
  456. else {
  457. draw( this[options.scope + 'Topo'] );
  458. }
  459. return this;
  460. function draw (data) {
  461. // if fetching remote data, draw the map first then call `updateChoropleth`
  462. if ( self.options.dataUrl ) {
  463. //allow for csv or json data types
  464. d3[self.options.dataType](self.options.dataUrl, function(data) {
  465. //in the case of csv, transform data to object
  466. if ( self.options.dataType === 'csv' && (data && data.slice) ) {
  467. var tmpData = {};
  468. for(var i = 0; i < data.length; i++) {
  469. tmpData[data[i].id] = data[i];
  470. }
  471. data = tmpData;
  472. }
  473. Datamaps.prototype.updateChoropleth.call(self, data);
  474. });
  475. }
  476. drawSubunits.call(self, data);
  477. handleGeographyConfig.call(self);
  478. if ( self.options.geographyConfig.popupOnHover || self.options.bubblesConfig.popupOnHover) {
  479. hoverover = d3.select( self.options.element ).append('div')
  480. .attr('class', 'datamaps-hoverover')
  481. .style('z-index', 10001)
  482. .style('position', 'absolute');
  483. }
  484. //fire off finished callback
  485. self.options.done(self);
  486. }
  487. };
  488. /**************************************
  489. TopoJSON
  490. ***************************************/
  491. Datamap.prototype.worldTopo = WORLD_TOPO;
  492. Datamap.prototype.usaTopo = USA_TOPO;
  493. /**************************************
  494. Utilities
  495. ***************************************/
  496. //convert lat/lng coords to X / Y coords
  497. Datamap.prototype.latLngToXY = function(lat, lng) {
  498. return this.projection([lng, lat]);
  499. };
  500. //add <g> layer to root SVG
  501. Datamap.prototype.addLayer = function( className, id, first ) {
  502. var layer;
  503. if ( first ) {
  504. layer = this.svg.insert('g', ':first-child')
  505. }
  506. else {
  507. layer = this.svg.append('g')
  508. }
  509. return layer.attr('id', id || '')
  510. .attr('class', className || '');
  511. };
  512. Datamap.prototype.updateChoropleth = function(data) {
  513. var svg = this.svg;
  514. for ( var subunit in data ) {
  515. if ( data.hasOwnProperty(subunit) ) {
  516. console.log(data);
  517. var color;
  518. var subunitData = data[subunit]
  519. if ( ! subunit ) {
  520. continue;
  521. }
  522. else if ( typeof subunitData === "string" ) {
  523. color = subunitData;
  524. }
  525. else if ( typeof subunitData.color === "string" ) {
  526. color = subunitData.color;
  527. }
  528. else {
  529. color = this.options.fills[ subunitData.fillKey ];
  530. }
  531. //if it's an object, overriding the previous data
  532. if ( subunitData === Object(subunitData) ) {
  533. this.options.data[subunit] = defaults(subunitData, this.options.data[subunit] || {});
  534. var geo = this.svg.select('.' + subunit).attr('data-info', JSON.stringify(this.options.data[subunit]));
  535. }
  536. svg
  537. .selectAll('.' + subunit)
  538. .transition()
  539. .style('fill', color);
  540. }
  541. }
  542. };
  543. Datamap.prototype.updatePopup = function (element, d, options) {
  544. var self = this;
  545. element.on('mousemove', null);
  546. element.on('mousemove', function() {
  547. var position = d3.mouse(this);
  548. d3.select(self.svg[0][0].parentNode).select('.datamaps-hoverover')
  549. .style('top', ( (position[1] + 30)) + "px")
  550. .html(function() {
  551. var data = JSON.parse(element.attr('data-info'));
  552. //if ( !data ) return '';
  553. return options.popupTemplate(d, data);
  554. })
  555. .style('left', ( position[0]) + "px");
  556. });
  557. d3.select(self.svg[0][0].parentNode).select('.datamaps-hoverover').style('display', 'block');
  558. };
  559. Datamap.prototype.addPlugin = function( name, pluginFn ) {
  560. var self = this;
  561. if ( typeof Datamap.prototype[name] === "undefined" ) {
  562. Datamap.prototype[name] = function(data, options, callback, createNewLayer) {
  563. var layer;
  564. if ( typeof createNewLayer === "undefined" ) {
  565. createNewLayer = false;
  566. }
  567. if ( typeof options === 'function' ) {
  568. callback = options;
  569. options = undefined;
  570. }
  571. options = defaults(options || {}, defaultOptions[name + 'Config']);
  572. //add a single layer, reuse the old layer
  573. if ( !createNewLayer && this.options[name + 'Layer'] ) {
  574. layer = this.options[name + 'Layer'];
  575. options = options || this.options[name + 'Options'];
  576. }
  577. else {
  578. layer = this.addLayer(name);
  579. this.options[name + 'Layer'] = layer;
  580. this.options[name + 'Options'] = options;
  581. }
  582. pluginFn.apply(this, [layer, data, options]);
  583. if ( callback ) {
  584. callback(layer);
  585. }
  586. };
  587. }
  588. };
  589. // expose library
  590. if ( typeof define === "function" && define.amd ) {
  591. define( "datamaps", function(require) { d3 = require('d3'); topojson = require('topojson'); return Datamap; } );
  592. }
  593. else {
  594. window.Datamap = window.Datamaps = Datamap;
  595. }
  596. if ( window.jQuery ) {
  597. window.jQuery.fn.datamaps = function(options, callback) {
  598. options = options || {};
  599. options.element = this[0];
  600. var datamap = new Datamap(options);
  601. if ( typeof callback === "function" ) {
  602. callback(datamap, options);
  603. }
  604. return this;
  605. };
  606. }
  607. })();