module.js 15 KB

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