module.js 16 KB

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