module.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. },
  38. displayTabs: ["Geopoints", "Binning", "Choropleth", "Data"],
  39. activeDisplayTab:"Geopoints"
  40. };
  41. _.defaults($scope.panel, _d)
  42. $scope.init = function () {
  43. console.log("init");
  44. eventBus.register($scope, 'time', function (event, time) {
  45. set_time(time)
  46. });
  47. eventBus.register($scope, 'query', function (event, query) {
  48. $scope.panel.query = _.isArray(query) ? query[0] : query;
  49. $scope.get_data();
  50. });
  51. // Now that we're all setup, request the time from our group
  52. eventBus.broadcast($scope.$id, $scope.panel.group, 'get_time')
  53. };
  54. $scope.isNumber = function (n) {
  55. return !isNaN(parseFloat(n)) && isFinite(n);
  56. };
  57. $scope.get_data = function () {
  58. console.log("get_data");
  59. // Make sure we have everything for the request to complete
  60. if (_.isUndefined($scope.panel.index) || _.isUndefined($scope.time))
  61. return
  62. $scope.panel.loading = true;
  63. var request = $scope.ejs.Request().indices($scope.panel.index);
  64. console.log("fields", $scope.panel.field, $scope.panel.secondaryfield);
  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. console.log("emit render");
  118. $scope.$emit('render')
  119. });
  120. };
  121. // I really don't like this function, too much dom manip. Break out into directive?
  122. $scope.populate_modal = function (request) {
  123. $scope.modal = {
  124. title: "Inspector",
  125. 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>",
  126. }
  127. };
  128. function set_time(time) {
  129. $scope.time = time;
  130. $scope.panel.index = _.isUndefined(time.index) ? $scope.panel.index : time.index
  131. $scope.get_data();
  132. }
  133. $scope.build_search = function (field, value) {
  134. $scope.panel.query = add_to_query($scope.panel.query, field, value, false)
  135. $scope.get_data();
  136. eventBus.broadcast($scope.$id, $scope.panel.group, 'query', $scope.panel.query);
  137. };
  138. $scope.isActive = function(tab) {
  139. return (tab.toLowerCase() === $scope.panel.activeDisplayTab.toLowerCase());
  140. }
  141. $scope.tabClick = function(tab) {
  142. $scope.panel.activeDisplayTab = tab;
  143. }
  144. })
  145. .filter('enabledText', function() {
  146. return function (value) {
  147. if (value === true) {
  148. return "Enabled";
  149. } else {
  150. return "Disabled";
  151. }
  152. }
  153. })
  154. .directive('map2', function () {
  155. return {
  156. restrict: 'A',
  157. link: function (scope, elem, attrs) {
  158. elem.html('<center><img src="common/img/load_big.gif"></center>')
  159. var worldData = null,
  160. worldNames = null;
  161. // Receive render events
  162. scope.$on('render', function () {
  163. console.log("render");
  164. render_panel();
  165. });
  166. // Or if the window is resized
  167. angular.element(window).bind('resize', function () {
  168. console.log("resize");
  169. render_panel();
  170. });
  171. function render_panel() {
  172. // Using LABjs, wait until all scripts are loaded before rendering panel
  173. var scripts = $LAB.script("panels/map2/lib/d3.v3.min.js")
  174. .script("panels/map2/lib/topojson.v1.min.js")
  175. .script("panels/map2/lib/node-geohash.js")
  176. .script("panels/map2/lib/d3.hexbin.v0.min.js")
  177. .script("panels/map2/lib/queue.v1.min.js");
  178. // Populate element. Note that jvectormap appends, does not replace.
  179. scripts.wait(function () {
  180. elem.text('');
  181. if (worldData === null || worldNames === null) {
  182. queue()
  183. .defer(d3.json, "panels/map2/lib/world-110m.json")
  184. .defer(d3.tsv, "panels/map2/lib/world-country-names.tsv")
  185. .await(function(error, world, names) {
  186. worldData = world;
  187. worldNames = names;
  188. ready();
  189. });
  190. } else {
  191. ready();
  192. }
  193. });
  194. }
  195. function ready() {
  196. var world = worldData,
  197. names = worldNames;
  198. //Better way to get these values? Seems kludgy to use jQuery on the div...
  199. var width = $(elem[0]).width(),
  200. height = $(elem[0]).height();
  201. console.log("draw map", width, height);
  202. var scale = (width > height) ? (height / 2 / Math.PI) : (width / 2 / Math.PI);
  203. var projection = d3.geo.mercator()
  204. .translate([0,0])
  205. .scale(scale);
  206. var zoom = d3.behavior.zoom()
  207. .scaleExtent([1, 8])
  208. .on("zoom", move);
  209. var path = d3.geo.path()
  210. .projection(projection);
  211. var svg = d3.select(elem[0]).append("svg")
  212. .attr("width", width)
  213. .attr("height", height)
  214. .append("g")
  215. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
  216. .call(zoom);
  217. var g = svg.append("g");
  218. svg.append("rect")
  219. .attr("class", "overlay")
  220. .attr("x", -width / 2)
  221. .attr("y", -height / 2)
  222. .attr("width", width)
  223. .attr("height", height);
  224. /*
  225. d3.json("panels/map2/lib/world-50m.json", function (error, world) {
  226. g.append("path")
  227. .datum(topojson.object(world, world.objects.countries))
  228. .attr("class", "land")
  229. .attr("d", path);
  230. g.append("path")
  231. .datum(topojson.mesh(world, world.objects.countries, function (a, b) {
  232. return a !== b;
  233. }))
  234. .attr("class", "boundary")
  235. .attr("d", path);
  236. */
  237. console.log(world);
  238. console.log("feature", topojson.feature(world, world.objects.countries));
  239. var countries = topojson.feature(world, world.objects.countries).features;
  240. countries = countries.filter(function(d) {
  241. return names.some(function(n) {
  242. if (d.id == n.id) {
  243. d.name = n.name;
  244. return d.short = n.short;
  245. }
  246. });
  247. }).sort(function(a, b) {
  248. return a.name.localeCompare(b.name);
  249. });
  250. var quantize = d3.scale.quantize()
  251. .domain([0, 1000])
  252. .range(d3.range(9).map(function(i) { return "q" + (i+1); }));
  253. g.selectAll("path")
  254. .data(countries)
  255. .enter().append("path")
  256. .attr("class", function(d) {
  257. if (scope.panel.display.choropleth.enabled) {
  258. return 'land ' + quantize(scope.data[d.short]);
  259. } else {
  260. return 'land';
  261. }
  262. })
  263. .attr("d", path);
  264. g.append("path")
  265. .datum(topojson.mesh(world, world.objects.land, function(a, b) { return a !== b; }))
  266. .attr("class", "land boundary")
  267. .attr("d", path);
  268. //Geocoded points are decoded into lat/lon, then projected onto x/y
  269. points = _.map(scope.data, function (k, v) {
  270. var decoded = geohash.decode(v);
  271. return projection([decoded.longitude, decoded.latitude]);
  272. });
  273. //hexagonal binning
  274. if (scope.panel.display.binning.enabled) {
  275. var binPoints = [];
  276. //primary field is just binning raw counts
  277. //secondary field is binning some metric like mean/median/total. Hexbins doesn't support that,
  278. //so we cheat a little and just add more points to compensate.
  279. //However, we don't want to add a million points, so normalize against the largest value
  280. if (scope.panel.display.binning.areaEncodingField === 'secondary') {
  281. var max = Math.max.apply(Math, _.map(scope.data, function(k,v){return k;})),
  282. scale = 10/max;
  283. _.map(scope.data, function (k, v) {
  284. var decoded = geohash.decode(v);
  285. return _.map(_.range(0, k*scale), function(a,b) {
  286. binPoints.push(projection([decoded.longitude, decoded.latitude]));
  287. })
  288. });
  289. } else {
  290. binPoints = points;
  291. }
  292. var hexbin = d3.hexbin()
  293. .size([width, height])
  294. .radius(scope.panel.display.binning.hexagonSize);
  295. //bin and sort the points, so we can set the various ranges appropriately
  296. var binnedPoints = hexbin(binPoints).sort(function(a, b) { return b.length - a.length; });;
  297. console.log("binnedpoints",binnedPoints);
  298. //clean up some memory
  299. binPoints = [];
  300. var radius = d3.scale.sqrt()
  301. .domain([0, binnedPoints[0].length])
  302. .range([0, scope.panel.display.binning.hexagonSize]);
  303. var color = d3.scale.linear()
  304. .domain([0,binnedPoints[0].length])
  305. .range(["white", "steelblue"])
  306. .interpolate(d3.interpolateLab);
  307. g.selectAll(".hexagon")
  308. .data(binnedPoints)
  309. .enter().append("path")
  310. .attr("d", function (d) {
  311. if (scope.panel.display.binning.areaEncoding === false) {
  312. return hexbin.hexagon();
  313. } else {
  314. return hexbin.hexagon(radius(d.length));
  315. }
  316. })
  317. .attr("class", "hexagon")
  318. .attr("transform", function (d) {
  319. return "translate(" + d.x + "," + d.y + ")";
  320. })
  321. .style("fill", function (d) {
  322. if (scope.panel.display.binning.colorEncoding === false) {
  323. return color(binnedPoints[0].length / 2);
  324. } else {
  325. return color(d.length);
  326. }
  327. })
  328. .attr("opacity", scope.panel.display.binning.hexagonAlpha);
  329. }
  330. //Raw geopoints
  331. if (scope.panel.display.geopoints.enabled) {
  332. g.selectAll("circles.points")
  333. .data(points)
  334. .enter()
  335. .append("circle")
  336. .attr("r", scope.panel.display.geopoints.pointSize)
  337. .attr("opacity", scope.panel.display.geopoints.pointAlpha)
  338. .attr("transform", function (d) {
  339. return "translate(" + d[0] + "," + d[1] + ")";
  340. });
  341. }
  342. console.log("initial", scope.panel.display.scale, scope.panel.display.translate);
  343. if (scope.panel.display.scale != -1) {
  344. zoom.scale(scope.panel.display.scale).translate(scope.panel.display.translate);
  345. g.style("stroke-width", 1 / scope.panel.display.scale).attr("transform", "translate(" + scope.panel.display.translate + ") scale(" + scope.panel.display.scale + ")");
  346. //svg.redraw();
  347. }
  348. function move() {
  349. var t = d3.event.translate,
  350. s = d3.event.scale;
  351. t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
  352. t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
  353. zoom.translate(t);
  354. scope.panel.display.translate = t;
  355. scope.panel.display.scale = s;
  356. g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ")scale(" + s + ")");
  357. //console.log("move", scope.panel.display.scale, scope.panel.display.translate);
  358. }
  359. }
  360. }
  361. };
  362. });