module.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. data: {
  15. samples: 1000
  16. },
  17. geopoints: {
  18. enabled: true,
  19. enabledText: "Enabled",
  20. pointSize: 1,
  21. pointAlpha: 0.6
  22. },
  23. binning: {
  24. enabled: true,
  25. hexagonSize: 10,
  26. hexagonAlpha: 1.0,
  27. areaEncoding: true,
  28. areaEncodingField: "primary",
  29. colorEncoding: true,
  30. colorEncodingField: "primary"
  31. }
  32. },
  33. displayTabs: ["Geopoints", "Binning", "Data"],
  34. activeDisplayTab:"Geopoints"
  35. };
  36. _.defaults($scope.panel, _d)
  37. $scope.init = function () {
  38. console.log("init");
  39. eventBus.register($scope, 'time', function (event, time) {
  40. set_time(time)
  41. });
  42. eventBus.register($scope, 'query', function (event, query) {
  43. $scope.panel.query = _.isArray(query) ? query[0] : query;
  44. $scope.get_data();
  45. });
  46. // Now that we're all setup, request the time from our group
  47. eventBus.broadcast($scope.$id, $scope.panel.group, 'get_time')
  48. };
  49. $scope.isNumber = function (n) {
  50. return !isNaN(parseFloat(n)) && isFinite(n);
  51. };
  52. $scope.get_data = function () {
  53. console.log("get_data");
  54. // Make sure we have everything for the request to complete
  55. if (_.isUndefined($scope.panel.index) || _.isUndefined($scope.time))
  56. return
  57. $scope.panel.loading = true;
  58. var request = $scope.ejs.Request().indices($scope.panel.index);
  59. console.log("fields", $scope.panel.field, $scope.panel.secondaryfield);
  60. //Use a regular term facet if there is no secondary field
  61. if (typeof $scope.panel.secondaryfield === "undefined") {
  62. var facet = $scope.ejs.TermsFacet('map')
  63. .field($scope.panel.field)
  64. .size($scope.panel.display.data.samples)
  65. .exclude($scope.panel.exclude)
  66. .facetFilter(ejs.QueryFilter(
  67. ejs.FilteredQuery(
  68. ejs.QueryStringQuery($scope.panel.query || '*'),
  69. ejs.RangeFilter($scope.time.field)
  70. .from($scope.time.from)
  71. .to($scope.time.to))));
  72. } else {
  73. //otherwise, use term stats
  74. //NOTE: this will break if valueField is a geo_point
  75. // need to put in checks for that
  76. var facet = $scope.ejs.TermStatsFacet('map')
  77. .keyField($scope.panel.field)
  78. .valueField($scope.panel.secondaryfield)
  79. .size($scope.panel.display.data.samples)
  80. .facetFilter(ejs.QueryFilter(
  81. ejs.FilteredQuery(
  82. ejs.QueryStringQuery($scope.panel.query || '*'),
  83. ejs.RangeFilter($scope.time.field)
  84. .from($scope.time.from)
  85. .to($scope.time.to))));
  86. }
  87. // Then the insert into facet and make the request
  88. var request = request.facet(facet).size(0);
  89. $scope.populate_modal(request);
  90. var results = request.doSearch();
  91. // Populate scope when we have results
  92. results.then(function (results) {
  93. $scope.panel.loading = false;
  94. $scope.hits = results.hits.total;
  95. $scope.data = {};
  96. _.each(results.facets.map.terms, function (v) {
  97. var metric = 'count';
  98. //If it is a Term facet, use count, otherwise use Total
  99. //May retool this to allow users to pick mean/median/etc
  100. if (typeof $scope.panel.secondaryfield === "undefined") {
  101. metric = 'count';
  102. } else {
  103. metric = 'total';
  104. }
  105. //FIX THIS
  106. if (!$scope.isNumber(v.term)) {
  107. $scope.data[v.term.toUpperCase()] = v[metric];
  108. } else {
  109. $scope.data[v.term] = v[metric];
  110. }
  111. });
  112. console.log("emit render");
  113. $scope.$emit('render')
  114. });
  115. };
  116. // I really don't like this function, too much dom manip. Break out into directive?
  117. $scope.populate_modal = function (request) {
  118. $scope.modal = {
  119. title: "Inspector",
  120. 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>",
  121. }
  122. };
  123. function set_time(time) {
  124. $scope.time = time;
  125. $scope.panel.index = _.isUndefined(time.index) ? $scope.panel.index : time.index
  126. $scope.get_data();
  127. }
  128. $scope.build_search = function (field, value) {
  129. $scope.panel.query = add_to_query($scope.panel.query, field, value, false)
  130. $scope.get_data();
  131. eventBus.broadcast($scope.$id, $scope.panel.group, 'query', $scope.panel.query);
  132. };
  133. $scope.isActive = function(tab) {
  134. return (tab.toLowerCase() === $scope.panel.activeDisplayTab.toLowerCase());
  135. }
  136. $scope.tabClick = function(tab) {
  137. $scope.panel.activeDisplayTab = tab;
  138. }
  139. })
  140. .filter('enabledText', function() {
  141. return function (value) {
  142. if (value === true) {
  143. return "Enabled";
  144. } else {
  145. return "Disabled";
  146. }
  147. }
  148. })
  149. .directive('map2', function () {
  150. return {
  151. restrict: 'A',
  152. link: function (scope, elem, attrs) {
  153. elem.html('<center><img src="common/img/load_big.gif"></center>')
  154. // Receive render events
  155. scope.$on('render', function () {
  156. console.log("render");
  157. render_panel();
  158. });
  159. // Or if the window is resized
  160. angular.element(window).bind('resize', function () {
  161. console.log("resize");
  162. render_panel();
  163. });
  164. function render_panel() {
  165. //console.log("render_panel");
  166. //console.log(scope.panel);
  167. //console.log(elem);
  168. // Using LABjs, wait until all scripts are loaded before rendering panel
  169. var scripts = $LAB.script("panels/map2/lib/d3.v3.min.js")
  170. .script("panels/map2/lib/topojson.v0.min.js")
  171. .script("panels/map2/lib/node-geohash.js")
  172. .script("panels/map2/lib/d3.hexbin.v0.min.js");
  173. // Populate element. Note that jvectormap appends, does not replace.
  174. scripts.wait(function () {
  175. elem.text('');
  176. //Better way to get these values? Seems kludgy to use jQuery on the div...
  177. var width = $(elem[0]).width(),
  178. height = $(elem[0]).height();
  179. console.log("draw map", width, height);
  180. //Scale the map by whichever dimension is the smallest, helps to make sure the whole map is shown
  181. var scale = (width > height) ? (height / 2 / Math.PI) : (width / 2 / Math.PI);
  182. var projection = d3.geo.mercator()
  183. .translate([0, 0])
  184. .scale(scale);
  185. var zoom = d3.behavior.zoom()
  186. .scaleExtent([1, 8])
  187. .on("zoom", move);
  188. var path = d3.geo.path()
  189. .projection(projection);
  190. var svg = d3.select(elem[0]).append("svg")
  191. .attr("width", width)
  192. .attr("height", height)
  193. .append("g")
  194. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
  195. .call(zoom);
  196. var g = svg.append("g");
  197. svg.append("rect")
  198. .attr("class", "overlay")
  199. .attr("x", -width / 2)
  200. .attr("y", -height / 2)
  201. .attr("width", width)
  202. .attr("height", height);
  203. d3.json("panels/map2/lib/world-50m.json", function (error, world) {
  204. g.append("path")
  205. .datum(topojson.object(world, world.objects.countries))
  206. .attr("class", "land")
  207. .attr("d", path);
  208. g.append("path")
  209. .datum(topojson.mesh(world, world.objects.countries, function (a, b) {
  210. return a !== b;
  211. }))
  212. .attr("class", "boundary")
  213. .attr("d", path);
  214. //Geocoded points are decoded into lat/lon, then projected onto x/y
  215. points = _.map(scope.data, function (k, v) {
  216. var decoded = geohash.decode(v);
  217. return projection([decoded.longitude, decoded.latitude]);
  218. });
  219. var binPoints = [];
  220. //primary field is just binning raw counts
  221. //secondary field is binning some metric like mean/median/total. Hexbins doesn't support that,
  222. //so we cheat a little and just add more points to compensate.
  223. //However, we don't want to add a million points, so normalize against the largest value
  224. if (scope.panel.display.binning.areaEncodingField === 'secondary') {
  225. var max = Math.max.apply(Math, _.map(scope.data, function(k,v){return k;})),
  226. scale = 10/max;
  227. _.map(scope.data, function (k, v) {
  228. var decoded = geohash.decode(v);
  229. return _.map(_.range(0, k*scale), function(a,b) {
  230. binPoints.push(projection([decoded.longitude, decoded.latitude]));
  231. })
  232. });
  233. } else {
  234. binPoints = points;
  235. }
  236. //hexagonal binning
  237. if (scope.panel.display.binning.enabled) {
  238. var hexbin = d3.hexbin()
  239. .size([width, height])
  240. .radius(scope.panel.display.binning.hexagonSize);
  241. //bin and sort the points, so we can set the various ranges appropriately
  242. var binnedPoints = hexbin(binPoints).sort(function(a, b) { return b.length - a.length; });;
  243. console.log(binnedPoints);
  244. //clean up some memory
  245. binPoints = [];
  246. var radius = d3.scale.sqrt()
  247. .domain([0, binnedPoints[0].length])
  248. .range([0, scope.panel.display.binning.hexagonSize]);
  249. var color = d3.scale.linear()
  250. .domain([0,binnedPoints[0].length])
  251. .range(["white", "steelblue"])
  252. .interpolate(d3.interpolateLab);
  253. g.selectAll(".hexagon")
  254. .data(binnedPoints)
  255. .enter().append("path")
  256. .attr("d", function (d) {
  257. if (scope.panel.display.binning.areaEncoding === false) {
  258. return hexbin.hexagon();
  259. } else {
  260. return hexbin.hexagon(radius(d.length));
  261. }
  262. })
  263. .attr("class", "hexagon")
  264. .attr("transform", function (d) {
  265. return "translate(" + d.x + "," + d.y + ")";
  266. })
  267. .style("fill", function (d) {
  268. if (scope.panel.display.binning.colorEncoding === false) {
  269. return color(binnedPoints[0].length / 2);
  270. } else {
  271. return color(d.length);
  272. }
  273. })
  274. .attr("opacity", scope.panel.display.binning.hexagonAlpha);
  275. }
  276. //Raw geopoints
  277. if (scope.panel.display.geopoints.enabled) {
  278. g.selectAll("circles.points")
  279. .data(points)
  280. .enter()
  281. .append("circle")
  282. .attr("r", scope.panel.display.geopoints.pointSize)
  283. .attr("opacity", scope.panel.display.geopoints.pointAlpha)
  284. .attr("transform", function (d) {
  285. return "translate(" + d[0] + "," + d[1] + ")";
  286. });
  287. }
  288. });
  289. function move() {
  290. var t = d3.event.translate,
  291. s = d3.event.scale;
  292. t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
  293. t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
  294. zoom.translate(t);
  295. g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ")scale(" + s + ")");
  296. }
  297. })
  298. }
  299. }
  300. };
  301. });