module.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. // Receive render events
  170. scope.$on('render', function () {
  171. render_panel();
  172. });
  173. // Or if the window is resized
  174. angular.element(window).bind('resize', function () {
  175. render_panel();
  176. });
  177. function render_panel() {
  178. // Using LABjs, wait until all scripts are loaded before rendering panel
  179. var scripts = $LAB.script("panels/map2/lib/d3.v3.min.js")
  180. .script("panels/map2/lib/topojson.v1.min.js")
  181. .script("panels/map2/lib/node-geohash.js")
  182. .script("panels/map2/lib/d3.hexbin.v0.min.js")
  183. .script("panels/map2/lib/queue.v1.min.js")
  184. .script("panels/map2/display/binning.js")
  185. .script("panels/map2/display/geopoints.js")
  186. .script("panels/map2/display/bullseye.js");
  187. // Populate element. Note that jvectormap appends, does not replace.
  188. scripts.wait(function () {
  189. elem.text('');
  190. //these files can take a bit of time to process, so save them in a variable
  191. //and use those on redraw
  192. if (scope.worldData === null || scope.worldNames === null) {
  193. queue()
  194. .defer(d3.json, "panels/map2/lib/world-110m.json")
  195. .defer(d3.tsv, "panels/map2/lib/world-country-names.tsv")
  196. .await(function(error, world, names) {
  197. scope.worldData = world;
  198. scope.worldNames = names;
  199. ready();
  200. });
  201. } else {
  202. ready();
  203. }
  204. });
  205. }
  206. /**
  207. * All map data has been loaded, go ahead and draw the map/data
  208. */
  209. function ready() {
  210. var world = scope.worldData,
  211. names = scope.worldNames;
  212. //Better way to get these values? Seems kludgy to use jQuery on the div...
  213. var width = $(elem[0]).width(),
  214. height = $(elem[0]).height();
  215. //scale to whichever dimension is smaller, helps to ensure the whole map is displayed
  216. var scale = (width > height) ? (height/5) : (width/5);
  217. /**
  218. * D3 and general config section
  219. */
  220. var projection;
  221. if (typeof scope.panel.display.map === 'undefined') {
  222. scope.panel.display.map = {type: 'orthographic'};
  223. }
  224. if (scope.panel.display.map.type === 'mercator') {
  225. projection = d3.geo.mercator()
  226. .translate([width/2, height/2])
  227. .scale(scale);
  228. } else if (scope.panel.display.map.type === 'orthographic') {
  229. projection = d3.geo.orthographic()
  230. .scale(248)
  231. .clipAngle(90);
  232. var λ = d3.scale.linear()
  233. .domain([0, width])
  234. .range([-180, 180]);
  235. var φ = d3.scale.linear()
  236. .domain([0, height])
  237. .range([90, -90]);
  238. }
  239. var zoom = d3.behavior.zoom()
  240. .scaleExtent([1, 8])
  241. .on("zoom", move);
  242. var path = d3.geo.path()
  243. .projection(projection);
  244. //used by choropleth
  245. var quantize = d3.scale.quantize()
  246. .domain([0, 1000])
  247. .range(d3.range(9).map(function(i) { return "q" + (i+1); }));
  248. //Extract name and two-letter codes for our countries
  249. var countries = topojson.feature(world, world.objects.countries).features;
  250. countries = countries.filter(function(d) {
  251. return names.some(function(n) {
  252. if (d.id == n.id) {
  253. d.name = n.name;
  254. return d.short = n.short;
  255. }
  256. });
  257. }).sort(function(a, b) {
  258. return a.name.localeCompare(b.name);
  259. });
  260. //Geocoded points are decoded into lat/lon, then projected onto x/y
  261. points = _.map(scope.data, function (k, v) {
  262. var decoded = geohash.decode(v);
  263. return projection([decoded.longitude, decoded.latitude]);
  264. });
  265. /**
  266. * D3 SVG Setup
  267. */
  268. var ctrlKey = false;
  269. //set up listener for ctrl key
  270. d3.select("body")
  271. .on("keydown", function() {
  272. ctrlKey = d3.event.ctrlKey;
  273. })
  274. .on("keyup", function() {
  275. ctrlKey = d3.event.ctrlKey;
  276. });
  277. //remove our old svg...is there a better way to update than remove/append?
  278. d3.select(elem[0]).select("svg").remove();
  279. //create the new svg
  280. scope.svg = d3.select(elem[0]).append("svg")
  281. .attr("width", width)
  282. .attr("height", height)
  283. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
  284. .call(zoom);
  285. scope.g = scope.svg.append("g");
  286. //Overlay is used so that the entire map is draggable, not just the locations
  287. //where countries are
  288. scope.svg.append("rect")
  289. .attr("class", "overlay")
  290. .attr("width", width)
  291. .attr("height", height)
  292. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
  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 (ctrlKey) {
  316. projection.rotate([d3.event.x / 2, -d3.event.y / 2, projection.rotate()[2]]);
  317. scope.svg.selectAll("path").attr("d", path);
  318. }
  319. }));
  320. }
  321. /**
  322. * Display Options
  323. */
  324. //Hexagonal Binning
  325. if (scope.panel.display.binning.enabled) {
  326. //@todo fix this
  327. var dimensions = [width, height];
  328. displayBinning(scope, dimensions, projection);
  329. }
  330. //Raw geopoints
  331. if (scope.panel.display.geopoints.enabled) {
  332. displayGeopoints(scope);
  333. }
  334. if (scope.panel.display.bullseye.enabled) {
  335. displayBullseye(scope, projection, path);
  336. }
  337. /**
  338. * Zoom Functionality
  339. */
  340. if (scope.panel.display.scale != -1) {
  341. zoom.scale(scope.panel.display.scale).translate(scope.panel.display.translate);
  342. scope.g.style("stroke-width", 1 / scope.panel.display.scale).attr("transform", "translate(" + scope.panel.display.translate + ") scale(" + scope.panel.display.scale + ")");
  343. }
  344. function move() {
  345. if (!ctrlKey) {
  346. var t = d3.event.translate,
  347. s = d3.event.scale;
  348. t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
  349. t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
  350. zoom.translate(t);
  351. scope.panel.display.translate = t;
  352. scope.panel.display.scale = s;
  353. scope.g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ") scale(" + s + ")");
  354. }
  355. }
  356. }
  357. }
  358. };
  359. });