jquery.vmap.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. /*!
  2. * jQVMap Version 1.0
  3. *
  4. * http://jqvmap.com
  5. *
  6. * Copyright 2012, Peter Schmalfeldt <manifestinteractive@gmail.com>
  7. * Copyright 2011-2012, Kirill Lebedev
  8. * Licensed under the MIT license.
  9. *
  10. * Fork Me @ https://github.com/manifestinteractive/jqvmap
  11. */
  12. (function ($) {
  13. var apiParams = {
  14. colors: 1,
  15. values: 1,
  16. backgroundColor: 1,
  17. scaleColors: 1,
  18. normalizeFunction: 1,
  19. enableZoom: 1,
  20. showTooltip: 1,
  21. borderColor: 1,
  22. borderWidth: 1,
  23. borderOpacity: 1,
  24. selectedRegions: 1,
  25. multiSelectRegion: 1
  26. };
  27. var apiEvents = {
  28. onLabelShow: 'labelShow',
  29. onRegionOver: 'regionMouseOver',
  30. onRegionOut: 'regionMouseOut',
  31. onRegionClick: 'regionClick',
  32. onRegionSelect: 'regionSelect',
  33. onRegionDeselect: 'regionDeselect'
  34. };
  35. $.fn.vectorMap = function (options) {
  36. var defaultParams = {
  37. map: 'world_en',
  38. backgroundColor: '#a5bfdd',
  39. color: '#f4f3f0',
  40. hoverColor: '#c9dfaf',
  41. selectedColor: '#c9dfaf',
  42. scaleColors: ['#b6d6ff', '#005ace'],
  43. normalizeFunction: 'linear',
  44. enableZoom: true,
  45. showTooltip: true,
  46. borderColor: '#818181',
  47. borderWidth: 1,
  48. borderOpacity: 0.25,
  49. selectedRegions: null,
  50. multiSelectRegion: false
  51. }, map = this.data('mapObject');
  52. if (options === 'addMap') {
  53. WorldMap.maps[arguments[1]] = arguments[2];
  54. } else if (options === 'set' && apiParams[arguments[1]]) {
  55. map['set' + arguments[1].charAt(0).toUpperCase() + arguments[1].substr(1)].apply(map, Array.prototype.slice.call(arguments, 2));
  56. } else if (typeof options === 'string' &&
  57. typeof map[options] === 'function') {
  58. return map[options].apply(map, Array.prototype.slice.call(arguments, 1));
  59. } else {
  60. $.extend(defaultParams, options);
  61. defaultParams.container = this;
  62. this.css({ position: 'relative', overflow: 'hidden' });
  63. map = new WorldMap(defaultParams);
  64. this.data('mapObject', map);
  65. for (var e in apiEvents) {
  66. if (defaultParams[e]) {
  67. this.bind(apiEvents[e] + '.jqvmap', defaultParams[e]);
  68. }
  69. }
  70. }
  71. };
  72. var VectorCanvas = function (width, height, params) {
  73. this.mode = window.SVGAngle ? 'svg' : 'vml';
  74. this.params = params;
  75. if (this.mode == 'svg') {
  76. this.createSvgNode = function (nodeName) {
  77. return document.createElementNS(this.svgns, nodeName);
  78. };
  79. } else {
  80. try {
  81. if (!document.namespaces.rvml) {
  82. document.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
  83. }
  84. this.createVmlNode = function (tagName) {
  85. return document.createElement('<rvml:' + tagName + ' class="rvml">');
  86. };
  87. } catch (e) {
  88. this.createVmlNode = function (tagName) {
  89. return document.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
  90. };
  91. }
  92. document.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
  93. }
  94. if (this.mode == 'svg') {
  95. this.canvas = this.createSvgNode('svg');
  96. } else {
  97. this.canvas = this.createVmlNode('group');
  98. this.canvas.style.position = 'absolute';
  99. }
  100. this.setSize(width, height);
  101. };
  102. VectorCanvas.prototype = {
  103. svgns: "http://www.w3.org/2000/svg",
  104. mode: 'svg',
  105. width: 0,
  106. height: 0,
  107. canvas: null,
  108. setSize: function (width, height) {
  109. if (this.mode == 'svg') {
  110. this.canvas.setAttribute('width', width);
  111. this.canvas.setAttribute('height', height);
  112. } else {
  113. this.canvas.style.width = width + "px";
  114. this.canvas.style.height = height + "px";
  115. this.canvas.coordsize = width + ' ' + height;
  116. this.canvas.coordorigin = "0 0";
  117. if (this.rootGroup) {
  118. var pathes = this.rootGroup.getElementsByTagName('shape');
  119. for (var i = 0, l = pathes.length; i < l; i++) {
  120. pathes[i].coordsize = width + ' ' + height;
  121. pathes[i].style.width = width + 'px';
  122. pathes[i].style.height = height + 'px';
  123. }
  124. this.rootGroup.coordsize = width + ' ' + height;
  125. this.rootGroup.style.width = width + 'px';
  126. this.rootGroup.style.height = height + 'px';
  127. }
  128. }
  129. this.width = width;
  130. this.height = height;
  131. },
  132. createPath: function (config) {
  133. var node;
  134. if (this.mode == 'svg') {
  135. node = this.createSvgNode('path');
  136. node.setAttribute('d', config.path);
  137. if (this.params.borderColor !== null) {
  138. node.setAttribute('stroke', this.params.borderColor);
  139. }
  140. if (this.params.borderWidth > 0) {
  141. node.setAttribute('stroke-width', this.params.borderWidth);
  142. node.setAttribute('stroke-linecap', 'round');
  143. node.setAttribute('stroke-linejoin', 'round');
  144. }
  145. if (this.params.borderOpacity > 0) {
  146. node.setAttribute('stroke-opacity', this.params.borderOpacity);
  147. }
  148. node.setFill = function (color) {
  149. this.setAttribute("fill", color);
  150. if (this.getAttribute("original") === null) {
  151. this.setAttribute("original", color);
  152. }
  153. };
  154. node.getFill = function (color) {
  155. return this.getAttribute("fill");
  156. };
  157. node.getOriginalFill = function () {
  158. return this.getAttribute("original");
  159. };
  160. node.setOpacity = function (opacity) {
  161. this.setAttribute('fill-opacity', opacity);
  162. };
  163. } else {
  164. node = this.createVmlNode('shape');
  165. node.coordorigin = "0 0";
  166. node.coordsize = this.width + ' ' + this.height;
  167. node.style.width = this.width + 'px';
  168. node.style.height = this.height + 'px';
  169. node.fillcolor = WorldMap.defaultFillColor;
  170. node.stroked = false;
  171. node.path = VectorCanvas.pathSvgToVml(config.path);
  172. var scale = this.createVmlNode('skew');
  173. scale.on = true;
  174. scale.matrix = '0.01,0,0,0.01,0,0';
  175. scale.offset = '0,0';
  176. node.appendChild(scale);
  177. var fill = this.createVmlNode('fill');
  178. node.appendChild(fill);
  179. node.setFill = function (color) {
  180. this.getElementsByTagName('fill')[0].color = color;
  181. if (this.getAttribute("original") === null) {
  182. this.setAttribute("original", color);
  183. }
  184. };
  185. node.getFill = function (color) {
  186. return this.getElementsByTagName('fill')[0].color;
  187. };
  188. node.getOriginalFill = function () {
  189. return this.getAttribute("original");
  190. };
  191. node.setOpacity = function (opacity) {
  192. this.getElementsByTagName('fill')[0].opacity = parseInt(opacity * 100, 10) + '%';
  193. };
  194. }
  195. return node;
  196. },
  197. createGroup: function (isRoot) {
  198. var node;
  199. if (this.mode == 'svg') {
  200. node = this.createSvgNode('g');
  201. } else {
  202. node = this.createVmlNode('group');
  203. node.style.width = this.width + 'px';
  204. node.style.height = this.height + 'px';
  205. node.style.left = '0px';
  206. node.style.top = '0px';
  207. node.coordorigin = "0 0";
  208. node.coordsize = this.width + ' ' + this.height;
  209. }
  210. if (isRoot) {
  211. this.rootGroup = node;
  212. }
  213. return node;
  214. },
  215. applyTransformParams: function (scale, transX, transY) {
  216. if (this.mode == 'svg') {
  217. this.rootGroup.setAttribute('transform', 'scale(' + scale + ') translate(' + transX + ', ' + transY + ')');
  218. } else {
  219. this.rootGroup.coordorigin = (this.width - transX) + ',' + (this.height - transY);
  220. this.rootGroup.coordsize = this.width / scale + ',' + this.height / scale;
  221. }
  222. }
  223. };
  224. VectorCanvas.pathSvgToVml = function (path) {
  225. var result = '';
  226. var cx = 0, cy = 0, ctrlx, ctrly;
  227. return path.replace(/([MmLlHhVvCcSs])((?:-?(?:\d+)?(?:\.\d+)?,?\s?)+)/g, function (segment, letter, coords, index) {
  228. coords = coords.replace(/(\d)-/g, '$1,-').replace(/\s+/g, ',').split(',');
  229. if (!coords[0]) {
  230. coords.shift();
  231. }
  232. for (var i = 0, l = coords.length; i < l; i++) {
  233. coords[i] = Math.round(100 * coords[i]);
  234. }
  235. switch (letter) {
  236. case 'm':
  237. cx += coords[0];
  238. cy += coords[1];
  239. return 't' + coords.join(',');
  240. break;
  241. case 'M':
  242. cx = coords[0];
  243. cy = coords[1];
  244. return 'm' + coords.join(',');
  245. break;
  246. case 'l':
  247. cx += coords[0];
  248. cy += coords[1];
  249. return 'r' + coords.join(',');
  250. break;
  251. case 'L':
  252. cx = coords[0];
  253. cy = coords[1];
  254. return 'l' + coords.join(',');
  255. break;
  256. case 'h':
  257. cx += coords[0];
  258. return 'r' + coords[0] + ',0';
  259. break;
  260. case 'H':
  261. cx = coords[0];
  262. return 'l' + cx + ',' + cy;
  263. break;
  264. case 'v':
  265. cy += coords[0];
  266. return 'r0,' + coords[0];
  267. break;
  268. case 'V':
  269. cy = coords[0];
  270. return 'l' + cx + ',' + cy;
  271. break;
  272. case 'c':
  273. ctrlx = cx + coords[coords.length - 4];
  274. ctrly = cy + coords[coords.length - 3];
  275. cx += coords[coords.length - 2];
  276. cy += coords[coords.length - 1];
  277. return 'v' + coords.join(',');
  278. break;
  279. case 'C':
  280. ctrlx = coords[coords.length - 4];
  281. ctrly = coords[coords.length - 3];
  282. cx = coords[coords.length - 2];
  283. cy = coords[coords.length - 1];
  284. return 'c' + coords.join(',');
  285. break;
  286. case 's':
  287. coords.unshift(cy - ctrly);
  288. coords.unshift(cx - ctrlx);
  289. ctrlx = cx + coords[coords.length - 4];
  290. ctrly = cy + coords[coords.length - 3];
  291. cx += coords[coords.length - 2];
  292. cy += coords[coords.length - 1];
  293. return 'v' + coords.join(',');
  294. break;
  295. case 'S':
  296. coords.unshift(cy + cy - ctrly);
  297. coords.unshift(cx + cx - ctrlx);
  298. ctrlx = coords[coords.length - 4];
  299. ctrly = coords[coords.length - 3];
  300. cx = coords[coords.length - 2];
  301. cy = coords[coords.length - 1];
  302. return 'c' + coords.join(',');
  303. break;
  304. default:
  305. return false;
  306. break;
  307. }
  308. return '';
  309. }).replace(/z/g, '');
  310. };
  311. var WorldMap = function (params) {
  312. params = params || {};
  313. var map = this;
  314. var mapData = WorldMap.maps[params.map];
  315. this.selectedRegions = [];
  316. this.multiSelectRegion = params.multiSelectRegion;
  317. this.container = params.container;
  318. this.defaultWidth = mapData.width;
  319. this.defaultHeight = mapData.height;
  320. this.color = params.color;
  321. this.selectedColor = params.selectedColor;
  322. this.hoverColor = params.hoverColor;
  323. this.hoverOpacity = params.hoverOpacity;
  324. this.setBackgroundColor(params.backgroundColor);
  325. this.width = params.container.width();
  326. this.height = params.container.height();
  327. this.resize();
  328. jQuery(window).resize(function () {
  329. map.width = params.container.width();
  330. map.height = params.container.height();
  331. map.resize();
  332. map.canvas.setSize(map.width, map.height);
  333. map.applyTransform();
  334. });
  335. this.canvas = new VectorCanvas(this.width, this.height, params);
  336. params.container.append(this.canvas.canvas);
  337. this.makeDraggable();
  338. this.rootGroup = this.canvas.createGroup(true);
  339. this.index = WorldMap.mapIndex;
  340. this.label = jQuery('<div/>').addClass('jqvmap-label').appendTo(jQuery('body')).hide();
  341. if (params.enableZoom) {
  342. jQuery('<div/>').addClass('jqvmap-zoomin').text('+').appendTo(params.container);
  343. jQuery('<div/>').addClass('jqvmap-zoomout').html('&#x2212;').appendTo(params.container);
  344. }
  345. map.countries = [];
  346. for (var key in mapData.pathes) {
  347. var path = this.canvas.createPath({
  348. path: mapData.pathes[key].path
  349. });
  350. path.setFill(this.color);
  351. path.id = map.getCountryId(key);
  352. map.countries[key] = path;
  353. if (this.canvas.mode == 'svg') {
  354. path.setAttribute('class', 'jvectormap-region');
  355. } else {
  356. jQuery(path).addClass('jvectormap-region');
  357. }
  358. jQuery(this.rootGroup).append(path);
  359. }
  360. jQuery(params.container).delegate(this.canvas.mode == 'svg' ? 'path' : 'shape', 'mouseover mouseout', function (e) {
  361. var path = e.target,
  362. code = e.target.id.split('_').pop(),
  363. labelShowEvent = $.Event('labelShow.jqvmap'),
  364. regionMouseOverEvent = $.Event('regionMouseOver.jqvmap');
  365. if (e.type == 'mouseover') {
  366. jQuery(params.container).trigger(regionMouseOverEvent, [code, mapData.pathes[code].name]);
  367. if (!regionMouseOverEvent.isDefaultPrevented()) {
  368. map.highlight(code, path);
  369. }
  370. if (params.showTooltip) {
  371. map.label.text(mapData.pathes[code].name);
  372. jQuery(params.container).trigger(labelShowEvent, [map.label, code]);
  373. if (!labelShowEvent.isDefaultPrevented()) {
  374. map.label.show();
  375. map.labelWidth = map.label.width();
  376. map.labelHeight = map.label.height();
  377. }
  378. }
  379. } else {
  380. map.unhighlight(code, path);
  381. map.label.hide();
  382. jQuery(params.container).trigger('regionMouseOut.jqvmap', [code, mapData.pathes[code].name]);
  383. }
  384. });
  385. jQuery(params.container).delegate(this.canvas.mode == 'svg' ? 'path' : 'shape', 'click', function (e) {
  386. if (!params.multiSelectRegion) {
  387. for (var key in mapData.pathes) {
  388. map.countries[key].currentFillColor = map.countries[key].getOriginalFill();
  389. map.countries[key].setFill(map.countries[key].getOriginalFill());
  390. }
  391. }
  392. var path = e.target;
  393. var code = e.target.id.split('_').pop();
  394. regionClickEvent = $.Event('regionClick.jqvmap');
  395. jQuery(params.container).trigger('regionClick.jqvmap', [code, mapData.pathes[code].name]);
  396. if (!regionClickEvent.isDefaultPrevented()) {
  397. if (map.selectedRegions.indexOf(code) !== -1) {
  398. map.deselect(code, path);
  399. } else {
  400. map.select(code, path);
  401. }
  402. }
  403. //console.log(selectedRegions);
  404. });
  405. if (params.showTooltip) {
  406. params.container.mousemove(function (e) {
  407. if (map.label.is(':visible')) {
  408. var left = e.pageX - 15 - map.labelWidth;
  409. var top = e.pageY - 15 - map.labelHeight;
  410. if(left < 0)
  411. left = e.pageX + 15;
  412. if(top < 0)
  413. top = e.pageY + 15;
  414. map.label.css({
  415. left: left,
  416. top: top
  417. });
  418. }
  419. });
  420. }
  421. this.setColors(params.colors);
  422. this.canvas.canvas.appendChild(this.rootGroup);
  423. this.applyTransform();
  424. this.colorScale = new ColorScale(params.scaleColors, params.normalizeFunction, params.valueMin, params.valueMax);
  425. if (params.values) {
  426. this.values = params.values;
  427. this.setValues(params.values);
  428. }
  429. if (params.selectedRegions) {
  430. if (params.selectedRegions instanceof Array) {
  431. for(var k in params.selectedRegions) {
  432. this.select(params.selectedRegions[k].toLowerCase());
  433. }
  434. } else {
  435. this.select(params.selectedRegions.toLowerCase());
  436. }
  437. }
  438. this.bindZoomButtons();
  439. if(params.pins) {
  440. /*if(params.pinMode) {
  441. if(params.pinMode != "id" && params.pinMode != "content") {
  442. params.pinMode = "content";
  443. }
  444. } else {
  445. params.pinMode = "content";
  446. }*/
  447. this.pinHandlers = false;
  448. this.placePins(params.pins, params.pinMode);
  449. }
  450. WorldMap.mapIndex++;
  451. };
  452. WorldMap.prototype = {
  453. transX: 0,
  454. transY: 0,
  455. scale: 1,
  456. baseTransX: 0,
  457. baseTransY: 0,
  458. baseScale: 1,
  459. width: 0,
  460. height: 0,
  461. countries: {},
  462. countriesColors: {},
  463. countriesData: {},
  464. zoomStep: 1.4,
  465. zoomMaxStep: 4,
  466. zoomCurStep: 1,
  467. setColors: function (key, color) {
  468. if (typeof key == 'string') {
  469. this.countries[key].setFill(color);
  470. this.countries[key].setAttribute("original", color);
  471. } else {
  472. var colors = key;
  473. for (var code in colors) {
  474. if (this.countries[code]) {
  475. this.countries[code].setFill(colors[code]);
  476. this.countries[code].setAttribute("original", colors[code]);
  477. }
  478. }
  479. }
  480. },
  481. setValues: function (values) {
  482. var max = 0,
  483. min = Number.MAX_VALUE,
  484. val;
  485. for (var cc in values) {
  486. val = parseFloat(values[cc]);
  487. if (val > max) {
  488. max = values[cc];
  489. }
  490. if (val && val < min) {
  491. min = val;
  492. }
  493. }
  494. this.colorScale.setMin(min);
  495. this.colorScale.setMax(max);
  496. var colors = {};
  497. for (cc in values) {
  498. val = parseFloat(values[cc]);
  499. if (val) {
  500. colors[cc] = this.colorScale.getColor(val);
  501. } else {
  502. colors[cc] = this.color;
  503. }
  504. }
  505. this.setColors(colors);
  506. this.values = values;
  507. },
  508. setBackgroundColor: function (backgroundColor) {
  509. this.container.css('background-color', backgroundColor);
  510. },
  511. setScaleColors: function (colors) {
  512. this.colorScale.setColors(colors);
  513. if (this.values) {
  514. this.setValues(this.values);
  515. }
  516. },
  517. setNormalizeFunction: function (f) {
  518. this.colorScale.setNormalizeFunction(f);
  519. if (this.values) {
  520. this.setValues(this.values);
  521. }
  522. },
  523. highlight: function (cc, path) {
  524. path = path || $('#' + this.getCountryId(cc))[0];
  525. if (this.hoverOpacity) {
  526. path.setOpacity(this.hoverOpacity);
  527. } else if (this.hoverColor) {
  528. path.currentFillColor = path.getFill() + '';
  529. path.setFill(this.hoverColor);
  530. }
  531. },
  532. unhighlight: function (cc, path) {
  533. path = path || $('#' + this.getCountryId(cc))[0];
  534. path.setOpacity(1);
  535. if (path.currentFillColor) {
  536. path.setFill(path.currentFillColor);
  537. }
  538. },
  539. select: function (cc, path) {
  540. path = path || $('#' + this.getCountryId(cc))[0];
  541. if(this.selectedRegions.indexOf(cc) < 0) {
  542. if (this.multiSelectRegion) {
  543. this.selectedRegions.push(cc);
  544. } else {
  545. this.selectedRegions = [cc];
  546. }
  547. // MUST BE after the change of selectedRegions
  548. // Otherwise, we might loop
  549. $(this.container).trigger('regionSelect.jqvmap', [cc]);
  550. if (this.selectedColor) {
  551. path.currentFillColor = this.selectedColor;
  552. path.setFill(this.selectedColor);
  553. }
  554. }
  555. },
  556. deselect: function (cc, path) {
  557. path = path || $('#' + this.getCountryId(cc))[0];
  558. if(this.selectedRegions.indexOf(cc) >= 0) {
  559. this.selectedRegions.splice(this.selectedRegions.indexOf(cc), 1);
  560. // MUST BE after the change of selectedRegions
  561. // Otherwise, we might loop
  562. $(this.container).trigger('regionDeselect.jqvmap', [cc]);
  563. path.currentFillColor = path.getOriginalFill();
  564. path.setFill(path.getOriginalFill());
  565. }
  566. },
  567. isSelected: function(cc) {
  568. return this.selectedRegions.indexOf(cc) >= 0;
  569. },
  570. resize: function () {
  571. var curBaseScale = this.baseScale;
  572. if (this.width / this.height > this.defaultWidth / this.defaultHeight) {
  573. this.baseScale = this.height / this.defaultHeight;
  574. this.baseTransX = Math.abs(this.width - this.defaultWidth * this.baseScale) / (2 * this.baseScale);
  575. } else {
  576. this.baseScale = this.width / this.defaultWidth;
  577. this.baseTransY = Math.abs(this.height - this.defaultHeight * this.baseScale) / (2 * this.baseScale);
  578. }
  579. this.scale *= this.baseScale / curBaseScale;
  580. this.transX *= this.baseScale / curBaseScale;
  581. this.transY *= this.baseScale / curBaseScale;
  582. },
  583. reset: function () {
  584. this.countryTitle.reset();
  585. for (var key in this.countries) {
  586. this.countries[key].setFill(WorldMap.defaultColor);
  587. }
  588. this.scale = this.baseScale;
  589. this.transX = this.baseTransX;
  590. this.transY = this.baseTransY;
  591. this.applyTransform();
  592. },
  593. applyTransform: function () {
  594. var maxTransX, maxTransY, minTransX, minTransY;
  595. if (this.defaultWidth * this.scale <= this.width) {
  596. maxTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale);
  597. minTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale);
  598. } else {
  599. maxTransX = 0;
  600. minTransX = (this.width - this.defaultWidth * this.scale) / this.scale;
  601. }
  602. if (this.defaultHeight * this.scale <= this.height) {
  603. maxTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale);
  604. minTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale);
  605. } else {
  606. maxTransY = 0;
  607. minTransY = (this.height - this.defaultHeight * this.scale) / this.scale;
  608. }
  609. if (this.transY > maxTransY) {
  610. this.transY = maxTransY;
  611. }
  612. else if (this.transY < minTransY) {
  613. this.transY = minTransY;
  614. }
  615. if (this.transX > maxTransX) {
  616. this.transX = maxTransX;
  617. }
  618. else if (this.transX < minTransX) {
  619. this.transX = minTransX;
  620. }
  621. this.canvas.applyTransformParams(this.scale, this.transX, this.transY);
  622. },
  623. makeDraggable: function () {
  624. var mouseDown = false;
  625. var oldPageX, oldPageY;
  626. var self = this;
  627. self.isMoving = false;
  628. self.isMovingTimeout = false;
  629. this.container.mousemove(function (e) {
  630. if (mouseDown) {
  631. var curTransX = self.transX;
  632. var curTransY = self.transY;
  633. self.transX -= (oldPageX - e.pageX) / self.scale;
  634. self.transY -= (oldPageY - e.pageY) / self.scale;
  635. self.applyTransform();
  636. oldPageX = e.pageX;
  637. oldPageY = e.pageY;
  638. self.isMoving = true;
  639. if (self.isMovingTimeout) {
  640. clearTimeout(self.isMovingTimeout);
  641. }
  642. self.container.trigger('drag');
  643. }
  644. return false;
  645. }).mousedown(function (e) {
  646. mouseDown = true;
  647. oldPageX = e.pageX;
  648. oldPageY = e.pageY;
  649. return false;
  650. }).mouseup(function () {
  651. mouseDown = false;
  652. self.isMovingTimeout = setTimeout(function () {
  653. self.isMoving = false;
  654. }, 100);
  655. return false;
  656. });
  657. },
  658. bindZoomButtons: function () {
  659. var map = this;
  660. this.container.find('.jqvmap-zoomin').click(function(){
  661. map.zoomIn();
  662. });
  663. this.container.find('.jqvmap-zoomout').click(function(){
  664. map.zoomOut();
  665. });
  666. },
  667. zoomIn: function () {
  668. var map = this;
  669. var sliderDelta = (jQuery('#zoom').innerHeight() - 6 * 2 - 15 * 2 - 3 * 2 - 7 - 6) / (this.zoomMaxStep - this.zoomCurStep);
  670. if (map.zoomCurStep < map.zoomMaxStep) {
  671. var curTransX = map.transX;
  672. var curTransY = map.transY;
  673. var curScale = map.scale;
  674. map.transX -= (map.width / map.scale - map.width / (map.scale * map.zoomStep)) / 2;
  675. map.transY -= (map.height / map.scale - map.height / (map.scale * map.zoomStep)) / 2;
  676. map.setScale(map.scale * map.zoomStep);
  677. map.zoomCurStep++;
  678. jQuery('#zoomSlider').css('top', parseInt(jQuery('#zoomSlider').css('top'), 10) - sliderDelta);
  679. map.container.trigger("zoomIn");
  680. }
  681. },
  682. zoomOut: function () {
  683. var map = this;
  684. var sliderDelta = (jQuery('#zoom').innerHeight() - 6 * 2 - 15 * 2 - 3 * 2 - 7 - 6) / (this.zoomMaxStep - this.zoomCurStep);
  685. if (map.zoomCurStep > 1) {
  686. var curTransX = map.transX;
  687. var curTransY = map.transY;
  688. var curScale = map.scale;
  689. map.transX += (map.width / (map.scale / map.zoomStep) - map.width / map.scale) / 2;
  690. map.transY += (map.height / (map.scale / map.zoomStep) - map.height / map.scale) / 2;
  691. map.setScale(map.scale / map.zoomStep);
  692. map.zoomCurStep--;
  693. jQuery('#zoomSlider').css('top', parseInt(jQuery('#zoomSlider').css('top'), 10) + sliderDelta);
  694. map.container.trigger("zoomOut");
  695. }
  696. },
  697. setScale: function (scale) {
  698. this.scale = scale;
  699. this.applyTransform();
  700. },
  701. getCountryId: function (cc) {
  702. return 'jqvmap' + this.index + '_' + cc;
  703. },
  704. getPinId: function (cc) {
  705. return this.getCountryId(cc)+'_pin';
  706. },
  707. placePins: function(pins, pinMode){
  708. var map = this;
  709. if(!pinMode || (pinMode != "content" && pinMode != "id")) {
  710. pinMode = "content";
  711. }
  712. if(pinMode == "content") {//treat pin as content
  713. jQuery.each(pins, function(index, pin){
  714. if(jQuery('#'+map.getCountryId(index)).length == 0){
  715. return;
  716. }
  717. //mapData.pathes[code].name
  718. var pinIndex = map.getPinId(index);
  719. if(jQuery('#'+pinIndex).length > 0){
  720. jQuery('#'+pinIndex).remove();
  721. }
  722. map.container.append('<div id="' + pinIndex + '" for="'+index+'" class="jqvmap_pin" style="position:absolute">' + pin + '</div>');
  723. });
  724. } else { //treat pin as id of an html content
  725. jQuery.each(pins, function(index, pin){
  726. if(jQuery('#'+map.getCountryId(index)).length == 0){
  727. return;
  728. }
  729. var pinIndex = map.getPinId(index);
  730. if(jQuery('#'+pinIndex).length > 0){
  731. jQuery('#'+pinIndex).remove();
  732. }
  733. map.container.append('<div id="' + pinIndex + '" for="'+index+'" class="jqvmap_pin" style="position:absolute"></div>');
  734. jQuery('#'+pinIndex).append(jQuery('#'+pin));
  735. });
  736. }
  737. this.positionPins();
  738. if(!this.pinHandlers){
  739. this.pinHandlers = true;//do only once
  740. var positionFix = function(){
  741. map.positionPins();
  742. };
  743. this.container.bind('zoomIn', positionFix)
  744. .bind('zoomOut', positionFix)
  745. .bind('drag', positionFix);
  746. }
  747. },
  748. positionPins: function(){
  749. var map = this;
  750. var pins = this.container.find('.jqvmap_pin');
  751. jQuery.each(pins, function(index, pinObj){
  752. pinObj = jQuery(pinObj);
  753. var countryId = map.getCountryId(pinObj.attr('for'));
  754. var countryObj = jQuery('#' + countryId);
  755. var bbox = document.getElementById(countryId).getBBox();
  756. var position = countryObj.position();
  757. var scale = map.scale;
  758. var left = position.left + (bbox.width / 2) * scale - pinObj.width() / 2,
  759. top = position.top + (bbox.height / 2) * scale - pinObj.height() / 2;
  760. pinObj.css('left',left).css('top',top);
  761. });
  762. },
  763. getPin: function(cc){
  764. var pinObj = jQuery('#'+this.getPinId(cc));
  765. return pinObj.html();
  766. },
  767. getPins: function(){
  768. var pins = this.container.find('.jqvmap_pin');
  769. var ret = new Object();
  770. jQuery.each(pins, function(index, pinObj){
  771. pinObj = jQuery(pinObj);
  772. var cc = pinObj.attr('for');
  773. var pinContent = pinObj.html();
  774. eval("ret." + cc + "=pinContent");
  775. });
  776. return JSON.stringify(ret);
  777. },
  778. removePin: function(cc) {
  779. jQuery('#'+this.getPinId(cc)).remove();
  780. },
  781. removePins: function(){
  782. this.container.find('.jqvmap_pin').remove();
  783. }
  784. };
  785. WorldMap.xlink = "http://www.w3.org/1999/xlink";
  786. WorldMap.mapIndex = 1;
  787. WorldMap.maps = {};
  788. var ColorScale = function (colors, normalizeFunction, minValue, maxValue) {
  789. if (colors) {
  790. this.setColors(colors);
  791. }
  792. if (normalizeFunction) {
  793. this.setNormalizeFunction(normalizeFunction);
  794. }
  795. if (minValue) {
  796. this.setMin(minValue);
  797. }
  798. if (minValue) {
  799. this.setMax(maxValue);
  800. }
  801. };
  802. ColorScale.prototype = {
  803. colors: [],
  804. setMin: function (min) {
  805. this.clearMinValue = min;
  806. if (typeof this.normalize === 'function') {
  807. this.minValue = this.normalize(min);
  808. } else {
  809. this.minValue = min;
  810. }
  811. },
  812. setMax: function (max) {
  813. this.clearMaxValue = max;
  814. if (typeof this.normalize === 'function') {
  815. this.maxValue = this.normalize(max);
  816. } else {
  817. this.maxValue = max;
  818. }
  819. },
  820. setColors: function (colors) {
  821. for (var i = 0; i < colors.length; i++) {
  822. colors[i] = ColorScale.rgbToArray(colors[i]);
  823. }
  824. this.colors = colors;
  825. },
  826. setNormalizeFunction: function (f) {
  827. if (f === 'polynomial') {
  828. this.normalize = function (value) {
  829. return Math.pow(value, 0.2);
  830. };
  831. }
  832. else if (f === 'linear') {
  833. delete this.normalize;
  834. } else {
  835. this.normalize = f;
  836. }
  837. this.setMin(this.clearMinValue);
  838. this.setMax(this.clearMaxValue);
  839. },
  840. getColor: function (value) {
  841. if (typeof this.normalize === 'function') {
  842. value = this.normalize(value);
  843. }
  844. var lengthes = [];
  845. var fullLength = 0;
  846. var l;
  847. for (var i = 0; i < this.colors.length - 1; i++) {
  848. l = this.vectorLength(this.vectorSubtract(this.colors[i + 1], this.colors[i]));
  849. lengthes.push(l);
  850. fullLength += l;
  851. }
  852. var c = (this.maxValue - this.minValue) / fullLength;
  853. for (i = 0; i < lengthes.length; i++) {
  854. lengthes[i] *= c;
  855. }
  856. i = 0;
  857. value -= this.minValue;
  858. while (value - lengthes[i] >= 0) {
  859. value -= lengthes[i];
  860. i++;
  861. }
  862. var color;
  863. if (i == this.colors.length - 1) {
  864. color = this.vectorToNum(this.colors[i]).toString(16);
  865. } else {
  866. color = (this.vectorToNum(this.vectorAdd(this.colors[i], this.vectorMult(this.vectorSubtract(this.colors[i + 1], this.colors[i]), (value) / (lengthes[i]))))).toString(16);
  867. }
  868. while (color.length < 6) {
  869. color = '0' + color;
  870. }
  871. return '#' + color;
  872. },
  873. vectorToNum: function (vector) {
  874. var num = 0;
  875. for (var i = 0; i < vector.length; i++) {
  876. num += Math.round(vector[i]) * Math.pow(256, vector.length - i - 1);
  877. }
  878. return num;
  879. },
  880. vectorSubtract: function (vector1, vector2) {
  881. var vector = [];
  882. for (var i = 0; i < vector1.length; i++) {
  883. vector[i] = vector1[i] - vector2[i];
  884. }
  885. return vector;
  886. },
  887. vectorAdd: function (vector1, vector2) {
  888. var vector = [];
  889. for (var i = 0; i < vector1.length; i++) {
  890. vector[i] = vector1[i] + vector2[i];
  891. }
  892. return vector;
  893. },
  894. vectorMult: function (vector, num) {
  895. var result = [];
  896. for (var i = 0; i < vector.length; i++) {
  897. result[i] = vector[i] * num;
  898. }
  899. return result;
  900. },
  901. vectorLength: function (vector) {
  902. var result = 0;
  903. for (var i = 0; i < vector.length; i++) {
  904. result += vector[i] * vector[i];
  905. }
  906. return Math.sqrt(result);
  907. }
  908. };
  909. ColorScale.arrayToRgb = function (ar) {
  910. var rgb = '#';
  911. var d;
  912. for (var i = 0; i < ar.length; i++) {
  913. d = ar[i].toString(16);
  914. rgb += d.length == 1 ? '0' + d : d;
  915. }
  916. return rgb;
  917. };
  918. ColorScale.rgbToArray = function (rgb) {
  919. rgb = rgb.substr(1);
  920. return [parseInt(rgb.substr(0, 2), 16), parseInt(rgb.substr(2, 2), 16), parseInt(rgb.substr(4, 2), 16)];
  921. };
  922. })(jQuery);