module.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. type: "mercator"
  19. },
  20. geopoints: {
  21. enabled: false,
  22. enabledText: "Enabled",
  23. pointSize: 0.3,
  24. pointAlpha: 0.6
  25. },
  26. binning: {
  27. enabled: false,
  28. hexagonSize: 2,
  29. hexagonAlpha: 1.0,
  30. areaEncoding: true,
  31. areaEncodingField: "primary",
  32. colorEncoding: true,
  33. colorEncodingField: "primary"
  34. },
  35. choropleth: {
  36. enabled: false
  37. },
  38. bullseye: {
  39. enabled: false,
  40. coord: {
  41. lat: 0,
  42. lon: 0
  43. }
  44. }
  45. },
  46. activeDisplayTab:"Geopoints"
  47. };
  48. _.defaults($scope.panel, _d)
  49. $scope.init = function () {
  50. eventBus.register($scope, 'time', function (event, time) {
  51. set_time(time)
  52. });
  53. eventBus.register($scope, 'query', function (event, query) {
  54. $scope.panel.query = _.isArray(query) ? query[0] : query;
  55. $scope.get_data();
  56. });
  57. // Now that we're all setup, request the time from our group
  58. eventBus.broadcast($scope.$id, $scope.panel.group, 'get_time');
  59. };
  60. $scope.isNumber = function (n) {
  61. return !isNaN(parseFloat(n)) && isFinite(n);
  62. };
  63. $scope.get_data = function () {
  64. // Make sure we have everything for the request to complete
  65. if (_.isUndefined($scope.panel.index) || _.isUndefined($scope.time))
  66. return
  67. $scope.panel.loading = true;
  68. var request = $scope.ejs.Request().indices($scope.panel.index);
  69. //Use a regular term facet if there is no secondary field
  70. if (typeof $scope.panel.secondaryfield === "undefined") {
  71. var facet = $scope.ejs.TermsFacet('map')
  72. .field($scope.panel.field)
  73. .size($scope.panel.display.data.samples)
  74. .exclude($scope.panel.exclude)
  75. .facetFilter(ejs.QueryFilter(
  76. ejs.FilteredQuery(
  77. ejs.QueryStringQuery($scope.panel.query || '*'),
  78. ejs.RangeFilter($scope.time.field)
  79. .from($scope.time.from)
  80. .to($scope.time.to))));
  81. } else {
  82. //otherwise, use term stats
  83. //NOTE: this will break if valueField is a geo_point
  84. // need to put in checks for that
  85. var facet = $scope.ejs.TermStatsFacet('map')
  86. .keyField($scope.panel.field)
  87. .valueField($scope.panel.secondaryfield)
  88. .size($scope.panel.display.data.samples)
  89. .facetFilter(ejs.QueryFilter(
  90. ejs.FilteredQuery(
  91. ejs.QueryStringQuery($scope.panel.query || '*'),
  92. ejs.RangeFilter($scope.time.field)
  93. .from($scope.time.from)
  94. .to($scope.time.to))));
  95. }
  96. // Then the insert into facet and make the request
  97. var request = request.facet(facet).size(0);
  98. $scope.populate_modal(request);
  99. var results = request.doSearch();
  100. // Populate scope when we have results
  101. results.then(function (results) {
  102. $scope.panel.loading = false;
  103. $scope.hits = results.hits.total;
  104. $scope.data = {};
  105. _.each(results.facets.map.terms, function (v) {
  106. var metric = 'count';
  107. //If it is a Term facet, use count, otherwise use Total
  108. //May retool this to allow users to pick mean/median/etc
  109. if (typeof $scope.panel.secondaryfield === "undefined") {
  110. metric = 'count';
  111. } else {
  112. metric = 'total';
  113. }
  114. //FIX THIS
  115. if (!$scope.isNumber(v.term)) {
  116. $scope.data[v.term.toUpperCase()] = v[metric];
  117. } else {
  118. $scope.data[v.term] = v[metric];
  119. }
  120. });
  121. $scope.$emit('render')
  122. });
  123. };
  124. // I really don't like this function, too much dom manip. Break out into directive?
  125. $scope.populate_modal = function (request) {
  126. $scope.modal = {
  127. title: "Inspector",
  128. 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>"
  129. }
  130. };
  131. function set_time(time) {
  132. $scope.time = time;
  133. $scope.panel.index = _.isUndefined(time.index) ? $scope.panel.index : time.index
  134. $scope.get_data();
  135. }
  136. $scope.build_search = function (field, value) {
  137. $scope.panel.query = add_to_query($scope.panel.query, field, value, false)
  138. $scope.get_data();
  139. eventBus.broadcast($scope.$id, $scope.panel.group, 'query', $scope.panel.query);
  140. };
  141. $scope.isActive = function(tab) {
  142. return (tab.toLowerCase() === $scope.panel.activeDisplayTab.toLowerCase());
  143. }
  144. $scope.tabClick = function(tab) {
  145. $scope.panel.activeDisplayTab = tab;
  146. }
  147. })
  148. .filter('enabledText', function() {
  149. return function (value) {
  150. if (value === true) {
  151. return "Enabled";
  152. } else {
  153. return "Disabled";
  154. }
  155. }
  156. })
  157. .directive('map2', function () {
  158. return {
  159. restrict: 'A',
  160. template: '<div class="loading"><center><img src="common/img/load_big.gif" style="display:none"></center></div><div id="{{uuid}}"></div>',
  161. link: function (scope, elem, attrs) {
  162. //elem.html('')
  163. scope.worldData = null;
  164. scope.worldNames = null;
  165. scope.ctrlKey = false;
  166. //These are various options that should not be cached in scope.panel
  167. scope.options = {
  168. data: {
  169. dropdown:[
  170. {
  171. "text": "Mercator (Flat)",
  172. id: "mercator"
  173. },
  174. {
  175. text: "Orthographic (Sphere)",
  176. id: "orthographic"
  177. }
  178. ]
  179. }
  180. };
  181. //These should be moved to utility classes
  182. var s4 = function() {
  183. return Math.floor((1 + Math.random()) * 0x10000)
  184. .toString(16)
  185. .substring(1);
  186. };
  187. scope.uuid = s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  188. s4() + '-' + s4() + s4() + s4();
  189. // Receive render events
  190. scope.$on('render', function () {
  191. console.log("$on render");
  192. if (typeof scope.svg === 'undefined') {
  193. console.log("init");
  194. init_panel();
  195. } else {
  196. console.log("render");
  197. render_panel();
  198. }
  199. });
  200. // Or if the window is resized
  201. angular.element(window).bind('resize', function () {
  202. console.log("resize render");
  203. if (typeof scope.svg === 'undefined') {
  204. console.log("init");
  205. init_panel();
  206. } else {
  207. console.log("render");
  208. render_panel();
  209. }
  210. });
  211. function init_panel() {
  212. // Using LABjs, wait until all scripts are loaded before rendering panel
  213. var scripts = $LAB.script("panels/map2/lib/d3.v3.min.js?rand="+Math.floor(Math.random()*10000))
  214. .script("panels/map2/lib/topojson.v1.min.js?rand="+Math.floor(Math.random()*10000))
  215. .script("panels/map2/lib/node-geohash.js?rand="+Math.floor(Math.random()*10000))
  216. .script("panels/map2/lib/d3.hexbin.v0.min.js?rand="+Math.floor(Math.random()*10000))
  217. .script("panels/map2/lib/queue.v1.min.js?rand="+Math.floor(Math.random()*10000))
  218. .script("panels/map2/display/binning.js?rand="+Math.floor(Math.random()*10000))
  219. .script("panels/map2/display/geopoints.js?rand="+Math.floor(Math.random()*10000))
  220. .script("panels/map2/display/bullseye.js?rand="+Math.floor(Math.random()*10000));
  221. // Populate element. Note that jvectormap appends, does not replace.
  222. scripts.wait(function () {
  223. queue()
  224. .defer(d3.json, "panels/map2/lib/world-110m.json")
  225. .defer(d3.tsv, "panels/map2/lib/world-country-names.tsv")
  226. .await(function(error, world, names) {
  227. scope.worldData = world;
  228. scope.worldNames = names;
  229. console.log('initializing svg');
  230. //Better way to get these values? Seems kludgy to use jQuery on the div...
  231. var width = $(elem[0]).width(),
  232. height = $(elem[0]).height();
  233. //scale to whichever dimension is smaller, helps to ensure the whole map is displayed
  234. scope.scale = (width > height) ? (height/5) : (width/5);
  235. scope.zoom = d3.behavior.zoom()
  236. .scaleExtent([1, 8])
  237. .on("zoom", translate_map);
  238. //used by choropleth
  239. scope.quantize = d3.scale.quantize()
  240. .domain([0, 1000])
  241. .range(d3.range(9).map(function(i) { return "q" + (i+1); }));
  242. //Extract name and two-letter codes for our countries
  243. scope.countries = topojson.feature(scope.worldData, scope.worldData.objects.countries).features;
  244. scope.countries = scope.countries.filter(function(d) {
  245. return scope.worldNames.some(function(n) {
  246. if (d.id == n.id) {
  247. d.name = n.name;
  248. return d.short = n.short;
  249. }
  250. });
  251. }).sort(function(a, b) {
  252. return a.name.localeCompare(b.name);
  253. });
  254. //remove our old svg...is there a better way to update than remove/append?
  255. //d3.select("#" + scope.uuid).select("svg").remove();
  256. //create the new svg
  257. scope.svg = d3.select(elem[0]).append("svg")
  258. .attr("width", width)
  259. .attr("height", height)
  260. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
  261. .call(scope.zoom);
  262. scope.g = scope.svg.append("g");
  263. //Overlay is used so that the entire map is draggable, not just the locations
  264. //where countries are
  265. scope.svg.append("rect")
  266. .attr("class", "overlay")
  267. .attr("width", width)
  268. .attr("height", height)
  269. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
  270. console.log("finished initing");
  271. render_panel();
  272. });
  273. });
  274. }
  275. function render_panel() {
  276. console.log("render_panel scope.svg", scope.svg);
  277. var width = $(elem[0]).width(),
  278. height = $(elem[0]).height();
  279. /**
  280. * D3 and general config section
  281. */
  282. scope.projection;
  283. if (scope.panel.display.data.type === 'mercator') {
  284. scope.projection = d3.geo.mercator()
  285. .translate([width/2, height/2])
  286. .scale(scope.scale);
  287. } else if (scope.panel.display.data.type === 'orthographic') {
  288. scope.projection = d3.geo.orthographic()
  289. .translate([width/2, height/2])
  290. .scale(100)
  291. .clipAngle(90);
  292. var λ = d3.scale.linear()
  293. .domain([0, width])
  294. .range([-180, 180]);
  295. var φ = d3.scale.linear()
  296. .domain([0, height])
  297. .range([90, -90]);
  298. }
  299. var path = d3.geo.path()
  300. .projection(scope.projection);
  301. //Geocoded points are decoded into lat/lon, then projected onto x/y
  302. scope.points = _.map(scope.data, function (k, v) {
  303. var decoded = geohash.decode(v);
  304. return [decoded.longitude, decoded.latitude];
  305. });
  306. scope.projectedPoints = _.map(scope.points, function (k, v) {
  307. return scope.projection(v);
  308. });
  309. //set up listener for ctrl key
  310. //scope.svg
  311. //Draw the countries, if this is a choropleth, draw with fancy colors
  312. scope.g.selectAll("countries")
  313. .data(scope.countries)
  314. .enter().append("path")
  315. .attr("class", function(d) {
  316. if (scope.panel.display.choropleth.enabled) {
  317. return 'land ' + scope.quantize(scope.data[d.short]);
  318. } else {
  319. return 'land';
  320. }
  321. })
  322. .attr("d", path);
  323. //draw boundaries
  324. scope.g.selectAll("land").append("path")
  325. .datum(topojson.mesh(scope.worldData, scope.worldData.objects.land, function(a, b) { return a !== b; }))
  326. .attr("class", "land boundary")
  327. .attr("d", path);
  328. if (scope.panel.display.data.type === 'orthographic') {
  329. //set up some key listeners for our sphere dragging
  330. window.focus();
  331. d3.select(window)
  332. .on("keydown", function() {
  333. scope.ctrlKey = d3.event.ctrlKey;
  334. })
  335. .on("keyup", function() {
  336. scope.ctrlKey = d3.event.ctrlKey;
  337. });
  338. scope.svg.style("cursor", "move")
  339. .call(d3.behavior.drag()
  340. .origin(function() { var rotate = projection.rotate(); return {x: 2 * rotate[0], y: -2 * rotate[1]}; })
  341. .on("drag", function() {
  342. if ( scope.ctrlKey) {
  343. projection.rotate([d3.event.x / 2, -d3.event.y / 2, projection.rotate()[2]]);
  344. scope.svg.selectAll("path").attr("d", path);
  345. //displayBinning(scope, dimensions, projection, path);
  346. }
  347. }));
  348. }
  349. /**
  350. * Display Options
  351. */
  352. //Hexagonal Binning
  353. if (scope.panel.display.binning.enabled) {
  354. //@todo fix this
  355. var dimensions = [width, height];
  356. displayBinning(scope, dimensions, scope.projection, path);
  357. }
  358. //Raw geopoints
  359. //if (scope.panel.display.geopoints.enabled) {
  360. displayGeopoints(scope, path);
  361. //}
  362. //if (scope.panel.display.bullseye.enabled) {
  363. displayBullseye(scope, scope.projection, path);
  364. //}
  365. //d3.select(elem[0]).select(".loading").remove();
  366. /**
  367. * Zoom Functionality
  368. */
  369. if (scope.panel.display.scale != -1) {
  370. scope.zoom.scale(scope.panel.display.scale).translate(scope.panel.display.translate);
  371. scope.g.style("stroke-width", 1 / scope.panel.display.scale).attr("transform", "translate(" + scope.panel.display.translate + ") scale(" + scope.panel.display.scale + ")");
  372. }
  373. }
  374. function translate_map() {
  375. var width = $(elem[0]).width(),
  376. height = $(elem[0]).height();
  377. if (! scope.ctrlKey) {
  378. var t = d3.event.translate,
  379. s = d3.event.scale;
  380. t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
  381. t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
  382. scope.zoom.translate(t);
  383. scope.panel.display.translate = t;
  384. scope.panel.display.scale = s;
  385. scope.g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ") scale(" + s + ")");
  386. }
  387. }
  388. }
  389. };
  390. });