module.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. angular.module('kibana.map2', [])
  2. .controller('map2', function ($scope, eventBus) {
  3. // Set and populate defaults
  4. var _d = {
  5. query: "*",
  6. map: "world",
  7. colors: ['#C8EEFF', '#0071A4'],
  8. size: 100,
  9. exclude: [],
  10. spyable: true,
  11. group: "default",
  12. index_limit: 0,
  13. display: {
  14. translate:[0, 0],
  15. scale:-1,
  16. data: {
  17. samples: 1000
  18. },
  19. geopoints: {
  20. enabled: true,
  21. enabledText: "Enabled",
  22. pointSize: 0.3,
  23. pointAlpha: 0.6
  24. },
  25. binning: {
  26. enabled: true,
  27. hexagonSize: 2,
  28. hexagonAlpha: 1.0,
  29. areaEncoding: true,
  30. areaEncodingField: "primary",
  31. colorEncoding: true,
  32. colorEncodingField: "primary"
  33. },
  34. choropleth: {
  35. enabled: false
  36. },
  37. bullseye: {
  38. enabled: false,
  39. coord: {
  40. lat: 0,
  41. lon: 0
  42. }
  43. },
  44. map: {
  45. type: "mercator"
  46. }
  47. },
  48. displayTabs: ["Geopoints", "Binning", "Choropleth", "Bullseye", "Data"],
  49. activeDisplayTab:"Geopoints"
  50. };
  51. _.defaults($scope.panel, _d)
  52. $scope.init = function () {
  53. eventBus.register($scope, 'time', function (event, time) {
  54. set_time(time)
  55. });
  56. eventBus.register($scope, 'query', function (event, query) {
  57. $scope.panel.query = _.isArray(query) ? query[0] : query;
  58. $scope.get_data();
  59. });
  60. // Now that we're all setup, request the time from our group
  61. eventBus.broadcast($scope.$id, $scope.panel.group, 'get_time');
  62. };
  63. $scope.isNumber = function (n) {
  64. return !isNaN(parseFloat(n)) && isFinite(n);
  65. };
  66. $scope.get_data = function () {
  67. // Make sure we have everything for the request to complete
  68. if (_.isUndefined($scope.panel.index) || _.isUndefined($scope.time))
  69. return
  70. $scope.panel.loading = true;
  71. var request = $scope.ejs.Request().indices($scope.panel.index);
  72. //Use a regular term facet if there is no secondary field
  73. if (typeof $scope.panel.secondaryfield === "undefined") {
  74. var facet = $scope.ejs.TermsFacet('map')
  75. .field($scope.panel.field)
  76. .size($scope.panel.display.data.samples)
  77. .exclude($scope.panel.exclude)
  78. .facetFilter(ejs.QueryFilter(
  79. ejs.FilteredQuery(
  80. ejs.QueryStringQuery($scope.panel.query || '*'),
  81. ejs.RangeFilter($scope.time.field)
  82. .from($scope.time.from)
  83. .to($scope.time.to))));
  84. } else {
  85. //otherwise, use term stats
  86. //NOTE: this will break if valueField is a geo_point
  87. // need to put in checks for that
  88. var facet = $scope.ejs.TermStatsFacet('map')
  89. .keyField($scope.panel.field)
  90. .valueField($scope.panel.secondaryfield)
  91. .size($scope.panel.display.data.samples)
  92. .facetFilter(ejs.QueryFilter(
  93. ejs.FilteredQuery(
  94. ejs.QueryStringQuery($scope.panel.query || '*'),
  95. ejs.RangeFilter($scope.time.field)
  96. .from($scope.time.from)
  97. .to($scope.time.to))));
  98. }
  99. // Then the insert into facet and make the request
  100. var request = request.facet(facet).size(0);
  101. $scope.populate_modal(request);
  102. var results = request.doSearch();
  103. // Populate scope when we have results
  104. results.then(function (results) {
  105. $scope.panel.loading = false;
  106. $scope.hits = results.hits.total;
  107. $scope.data = {};
  108. _.each(results.facets.map.terms, function (v) {
  109. var metric = 'count';
  110. //If it is a Term facet, use count, otherwise use Total
  111. //May retool this to allow users to pick mean/median/etc
  112. if (typeof $scope.panel.secondaryfield === "undefined") {
  113. metric = 'count';
  114. } else {
  115. metric = 'total';
  116. }
  117. //FIX THIS
  118. if (!$scope.isNumber(v.term)) {
  119. $scope.data[v.term.toUpperCase()] = v[metric];
  120. } else {
  121. $scope.data[v.term] = v[metric];
  122. }
  123. });
  124. $scope.$emit('render')
  125. });
  126. };
  127. // I really don't like this function, too much dom manip. Break out into directive?
  128. $scope.populate_modal = function (request) {
  129. $scope.modal = {
  130. title: "Inspector",
  131. body: "<h5>Last Elasticsearch Query</h5><pre>" + 'curl -XGET ' + config.elasticsearch + '/' + $scope.panel.index + "/_search?pretty -d'\n" + angular.toJson(JSON.parse(request.toString()), true) + "'</pre>"
  132. }
  133. };
  134. function set_time(time) {
  135. $scope.time = time;
  136. $scope.panel.index = _.isUndefined(time.index) ? $scope.panel.index : time.index
  137. $scope.get_data();
  138. }
  139. $scope.build_search = function (field, value) {
  140. $scope.panel.query = add_to_query($scope.panel.query, field, value, false)
  141. $scope.get_data();
  142. eventBus.broadcast($scope.$id, $scope.panel.group, 'query', $scope.panel.query);
  143. };
  144. $scope.isActive = function(tab) {
  145. return (tab.toLowerCase() === $scope.panel.activeDisplayTab.toLowerCase());
  146. }
  147. $scope.tabClick = function(tab) {
  148. $scope.panel.activeDisplayTab = tab;
  149. }
  150. })
  151. .filter('enabledText', function() {
  152. return function (value) {
  153. if (value === true) {
  154. return "Enabled";
  155. } else {
  156. return "Disabled";
  157. }
  158. }
  159. })
  160. .directive('map2', function () {
  161. return {
  162. restrict: 'A',
  163. link: function (scope, elem, attrs) {
  164. elem.html('<center><img src="common/img/load_big.gif"></center>')
  165. scope.worldData = null;
  166. scope.worldNames = null;
  167. scope.svg = null;
  168. scope.g = null;
  169. scope.ctrlKey = false;
  170. // Receive render events
  171. scope.$on('render', function () {
  172. render_panel();
  173. });
  174. // Or if the window is resized
  175. angular.element(window).bind('resize', function () {
  176. render_panel();
  177. });
  178. function render_panel() {
  179. // Using LABjs, wait until all scripts are loaded before rendering panel
  180. var scripts = $LAB.script("panels/map2/lib/d3.v3.min.js")
  181. .script("panels/map2/lib/topojson.v1.min.js")
  182. .script("panels/map2/lib/node-geohash.js")
  183. .script("panels/map2/lib/d3.hexbin.v0.min.js")
  184. .script("panels/map2/lib/queue.v1.min.js")
  185. .script("panels/map2/display/binning.js")
  186. .script("panels/map2/display/geopoints.js")
  187. .script("panels/map2/display/bullseye.js");
  188. // Populate element. Note that jvectormap appends, does not replace.
  189. scripts.wait(function () {
  190. elem.text('');
  191. //these files can take a bit of time to process, so save them in a variable
  192. //and use those on redraw
  193. if (scope.worldData === null || scope.worldNames === null) {
  194. queue()
  195. .defer(d3.json, "panels/map2/lib/world-110m.json")
  196. .defer(d3.tsv, "panels/map2/lib/world-country-names.tsv")
  197. .await(function(error, world, names) {
  198. scope.worldData = world;
  199. scope.worldNames = names;
  200. ready();
  201. });
  202. } else {
  203. ready();
  204. }
  205. });
  206. }
  207. /**
  208. * All map data has been loaded, go ahead and draw the map/data
  209. */
  210. function ready() {
  211. var world = scope.worldData,
  212. names = scope.worldNames;
  213. //Better way to get these values? Seems kludgy to use jQuery on the div...
  214. var width = $(elem[0]).width(),
  215. height = $(elem[0]).height();
  216. //scale to whichever dimension is smaller, helps to ensure the whole map is displayed
  217. var scale = (width > height) ? (height/5) : (width/5);
  218. /**
  219. * D3 and general config section
  220. */
  221. var projection;
  222. if (scope.panel.display.map.type === 'mercator') {
  223. projection = d3.geo.mercator()
  224. .translate([width/2, height/2])
  225. .scale(scale);
  226. } else if (scope.panel.display.map.type === 'orthographic') {
  227. projection = d3.geo.orthographic()
  228. .scale(248)
  229. .clipAngle(90);
  230. var λ = d3.scale.linear()
  231. .domain([0, width])
  232. .range([-180, 180]);
  233. var φ = d3.scale.linear()
  234. .domain([0, height])
  235. .range([90, -90]);
  236. }
  237. var zoom = d3.behavior.zoom()
  238. .scaleExtent([1, 8])
  239. .on("zoom", move);
  240. var path = d3.geo.path()
  241. .projection(projection);
  242. //used by choropleth
  243. var quantize = d3.scale.quantize()
  244. .domain([0, 1000])
  245. .range(d3.range(9).map(function(i) { return "q" + (i+1); }));
  246. //Extract name and two-letter codes for our countries
  247. var countries = topojson.feature(world, world.objects.countries).features;
  248. countries = countries.filter(function(d) {
  249. return names.some(function(n) {
  250. if (d.id == n.id) {
  251. d.name = n.name;
  252. return d.short = n.short;
  253. }
  254. });
  255. }).sort(function(a, b) {
  256. return a.name.localeCompare(b.name);
  257. });
  258. //Geocoded points are decoded into lat/lon, then projected onto x/y
  259. points = _.map(scope.data, function (k, v) {
  260. var decoded = geohash.decode(v);
  261. return [decoded.longitude, decoded.latitude];
  262. });
  263. /**
  264. * D3 SVG Setup
  265. */
  266. //set up some key listeners for our sphere dragging
  267. window.focus();
  268. d3.select(window)
  269. .on("keydown", function() {
  270. scope.ctrlKey = d3.event.ctrlKey;
  271. })
  272. .on("keyup", function() {
  273. scope.ctrlKey = d3.event.ctrlKey;
  274. });
  275. //remove our old svg...is there a better way to update than remove/append?
  276. d3.select(elem[0]).select("svg").remove();
  277. //create the new svg
  278. scope.svg = d3.select(elem[0]).append("svg")
  279. .attr("width", width)
  280. .attr("height", height)
  281. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
  282. .call(zoom);
  283. scope.g = scope.svg.append("g");
  284. //Overlay is used so that the entire map is draggable, not just the locations
  285. //where countries are
  286. scope.svg.append("rect")
  287. .attr("class", "overlay")
  288. .attr("width", width)
  289. .attr("height", height)
  290. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
  291. //set up listener for ctrl key
  292. //scope.svg
  293. //Draw the countries, if this is a choropleth, draw with fancy colors
  294. scope.g.selectAll("path")
  295. .data(countries)
  296. .enter().append("path")
  297. .attr("class", function(d) {
  298. if (scope.panel.display.choropleth.enabled) {
  299. return 'land ' + quantize(scope.data[d.short]);
  300. } else {
  301. return 'land';
  302. }
  303. })
  304. .attr("d", path);
  305. //draw boundaries
  306. scope.g.selectAll("land").append("path")
  307. .datum(topojson.mesh(world, world.objects.land, function(a, b) { return a !== b; }))
  308. .attr("class", "land boundary")
  309. .attr("d", path);
  310. if (scope.panel.display.map.type === 'orthographic') {
  311. scope.svg.style("cursor", "move")
  312. .call(d3.behavior.drag()
  313. .origin(function() { var rotate = projection.rotate(); return {x: 2 * rotate[0], y: -2 * rotate[1]}; })
  314. .on("drag", function() {
  315. if ( scope.ctrlKey) {
  316. projection.rotate([d3.event.x / 2, -d3.event.y / 2, projection.rotate()[2]]);
  317. scope.svg.selectAll("path").attr("d", path);
  318. //displayBinning(scope, dimensions, projection, path);
  319. }
  320. }));
  321. }
  322. /**
  323. * Display Options
  324. */
  325. //Hexagonal Binning
  326. if (scope.panel.display.binning.enabled) {
  327. //@todo fix this
  328. var dimensions = [width, height];
  329. displayBinning(scope, dimensions, projection, path);
  330. }
  331. //Raw geopoints
  332. if (scope.panel.display.geopoints.enabled) {
  333. displayGeopoints(scope, path);
  334. }
  335. if (scope.panel.display.bullseye.enabled) {
  336. displayBullseye(scope, projection, path);
  337. }
  338. /**
  339. * Zoom Functionality
  340. */
  341. if (scope.panel.display.scale != -1) {
  342. zoom.scale(scope.panel.display.scale).translate(scope.panel.display.translate);
  343. scope.g.style("stroke-width", 1 / scope.panel.display.scale).attr("transform", "translate(" + scope.panel.display.translate + ") scale(" + scope.panel.display.scale + ")");
  344. }
  345. function move() {
  346. if (! scope.ctrlKey) {
  347. var t = d3.event.translate,
  348. s = d3.event.scale;
  349. t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
  350. t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
  351. zoom.translate(t);
  352. scope.panel.display.translate = t;
  353. scope.panel.display.scale = s;
  354. scope.g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ") scale(" + s + ")");
  355. }
  356. }
  357. }
  358. }
  359. };
  360. });