module.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. angular.module('kibana.map2', [])
  2. .controller('map2', function ($scope, eventBus, keylistener) {
  3. // Set and populate defaults
  4. var _d = {
  5. status : "Broken",
  6. query: "*",
  7. map: "world",
  8. colors: ['#C8EEFF', '#0071A4'],
  9. size: 100,
  10. exclude: [],
  11. spyable: true,
  12. group: "default",
  13. index_limit: 0,
  14. display: {
  15. translate:[0, 0],
  16. scale:-1,
  17. data: {
  18. samples: 1000,
  19. type: "mercator",
  20. dropdown:[
  21. {
  22. "text": "Mercator (Flat)",
  23. id: "mercator"
  24. },
  25. {
  26. text: "Orthographic (Sphere)",
  27. id: "orthographic"
  28. }
  29. ]
  30. },
  31. geopoints: {
  32. enabled: false,
  33. enabledText: "Enabled",
  34. pointSize: 0.3,
  35. pointAlpha: 0.6
  36. },
  37. binning: {
  38. enabled: false,
  39. hexagonSize: 2,
  40. hexagonAlpha: 1.0,
  41. areaEncoding: true,
  42. areaEncodingField: "primary",
  43. colorEncoding: true,
  44. colorEncodingField: "primary"
  45. },
  46. choropleth: {
  47. enabled: false
  48. },
  49. bullseye: {
  50. enabled: false,
  51. coord: {
  52. lat: 0,
  53. lon: 0
  54. }
  55. }
  56. },
  57. activeDisplayTab:"Geopoints"
  58. };
  59. _.defaults($scope.panel, _d)
  60. $scope.init = function () {
  61. eventBus.register($scope, 'time', function (event, time) {
  62. set_time(time)
  63. });
  64. eventBus.register($scope, 'query', function (event, query) {
  65. $scope.panel.query = _.isArray(query) ? query[0] : query;
  66. $scope.get_data();
  67. });
  68. // Now that we're all setup, request the time from our group
  69. eventBus.broadcast($scope.$id, $scope.panel.group, 'get_time');
  70. $scope.keylistener = keylistener;
  71. };
  72. $scope.get_data = function () {
  73. // Make sure we have everything for the request to complete
  74. if (_.isUndefined($scope.index) || _.isUndefined($scope.time))
  75. return
  76. $scope.panel.loading = true;
  77. var request = $scope.ejs.Request().indices($scope.index);
  78. var metric = 'count';
  79. //Use a regular term facet if there is no secondary field
  80. if (typeof $scope.panel.secondaryfield === "undefined") {
  81. var facet = $scope.ejs.TermsFacet('map')
  82. .field($scope.panel.field)
  83. .size($scope.panel.display.data.samples)
  84. .exclude($scope.panel.exclude)
  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. metric = 'count';
  92. } else {
  93. //otherwise, use term stats
  94. //NOTE: this will break if valueField is a geo_point
  95. // need to put in checks for that
  96. var facet = $scope.ejs.TermStatsFacet('map')
  97. .keyField($scope.panel.field)
  98. .valueField($scope.panel.secondaryfield)
  99. .size($scope.panel.display.data.samples)
  100. .facetFilter(ejs.QueryFilter(
  101. ejs.FilteredQuery(
  102. ejs.QueryStringQuery($scope.panel.query || '*'),
  103. ejs.RangeFilter($scope.time.field)
  104. .from($scope.time.from)
  105. .to($scope.time.to))));
  106. metric = 'total';
  107. }
  108. // Then the insert into facet and make the request
  109. var request = request.facet(facet).size(0);
  110. $scope.populate_modal(request);
  111. var results = request.doSearch();
  112. // Populate scope when we have results
  113. results.then(function (results) {
  114. $scope.panel.loading = false;
  115. $scope.hits = results.hits.total;
  116. $scope.data = {};
  117. _.each(results.facets.map.terms, function (v) {
  118. if (!_.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.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.index = _.isUndefined(time.index) ? $scope.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. //directive level variables related to d3
  165. var dr = {};
  166. scope.initializing = false;
  167. dr.worldData = null;
  168. dr.worldNames = null;
  169. /**
  170. * Initialize the panels if new, or render existing panels
  171. */
  172. scope.init_or_render = function() {
  173. if (typeof dr.svg === 'undefined') {
  174. console.log("init");
  175. //prevent duplicate initialization steps, if render is called again
  176. //before the svg is setup
  177. if (!scope.initializing) {
  178. init_panel();
  179. }
  180. } else {
  181. console.log("render");
  182. render_panel();
  183. }
  184. };
  185. /**
  186. * Receive render events
  187. */
  188. scope.$on('render', function () {
  189. scope.init_or_render();
  190. });
  191. /**
  192. * On window resize, re-render the panel
  193. */
  194. angular.element(window).bind('resize', function () {
  195. scope.init_or_render();
  196. });
  197. /**
  198. * Load the various panel-specific scripts, map data, then initialize
  199. * the svg and set appropriate D3 settings
  200. */
  201. function init_panel() {
  202. scope.initializing = true;
  203. // Using LABjs, wait until all scripts are loaded before rendering panel
  204. var scripts = $LAB.script("common/lib/d3.v3.min.js?rand="+Math.floor(Math.random()*10000))
  205. .script("panels/map2/lib/topojson.v1.min.js?rand="+Math.floor(Math.random()*10000))
  206. .script("panels/map2/lib/node-geohash.js?rand="+Math.floor(Math.random()*10000))
  207. .script("panels/map2/lib/d3.hexbin.v0.min.js?rand="+Math.floor(Math.random()*10000))
  208. .script("panels/map2/lib/queue.v1.min.js?rand="+Math.floor(Math.random()*10000))
  209. .script("panels/map2/display/binning.js?rand="+Math.floor(Math.random()*10000))
  210. .script("panels/map2/display/geopoints.js?rand="+Math.floor(Math.random()*10000))
  211. .script("panels/map2/display/bullseye.js?rand="+Math.floor(Math.random()*10000));
  212. // Populate element. Note that jvectormap appends, does not replace.
  213. scripts.wait(function () {
  214. queue()
  215. .defer(d3.json, "panels/map2/lib/world-110m.json")
  216. .defer(d3.tsv, "panels/map2/lib/world-country-names.tsv")
  217. .await(function(error, world, names) {
  218. dr.worldData = world;
  219. dr.worldNames = names;
  220. //Better way to get these values? Seems kludgy to use jQuery on the div...
  221. var width = $(elem[0]).width(),
  222. height = $(elem[0]).height();
  223. //scale to whichever dimension is smaller, helps to ensure the whole map is displayed
  224. dr.scale = (width > height) ? (height/5) : (width/5);
  225. dr.zoom = d3.behavior.zoom()
  226. .scaleExtent([1, 20])
  227. .on("zoom", translate_map);
  228. //used by choropleth
  229. //@todo change domain so that it reflects the domain of the data
  230. dr.quantize = d3.scale.quantize()
  231. .domain([0, 1000])
  232. .range(d3.range(9).map(function(i) { return "q" + (i+1); }));
  233. //Extract name and two-letter codes for our countries
  234. dr.countries = topojson.feature(dr.worldData, dr.worldData.objects.countries).features;
  235. dr.countries = dr.countries.filter(function(d) {
  236. return dr.worldNames.some(function(n) {
  237. if (d.id == n.id) {
  238. d.name = n.name;
  239. return d.short = n.short;
  240. }
  241. });
  242. }).sort(function(a, b) {
  243. return a.name.localeCompare(b.name);
  244. });
  245. //create the new svg
  246. dr.svg = d3.select(elem[0]).append("svg")
  247. .attr("width", "100%")
  248. .attr("height", "100%")
  249. .attr("viewBox", "0 0 " + width + " " + height)
  250. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
  251. .call(dr.zoom);
  252. dr.g = dr.svg.append("g");
  253. scope.initializing = false;
  254. render_panel();
  255. });
  256. });
  257. }
  258. /**
  259. * Render updates to the SVG. Typically happens when the data changes (time, query)
  260. * or when new options are selected
  261. */
  262. function render_panel() {
  263. var width = $(elem[0]).width(),
  264. height = $(elem[0]).height();
  265. //Projection is dependant on the map-type
  266. if (scope.panel.display.data.type === 'mercator') {
  267. dr.projection = d3.geo.mercator()
  268. .translate([width/2, height/2])
  269. .scale(dr.scale);
  270. } else if (scope.panel.display.data.type === 'orthographic') {
  271. dr.projection = d3.geo.orthographic()
  272. .translate([width/2, height/2])
  273. .scale(100)
  274. .clipAngle(90);
  275. //recenters the sphere more towards the US...not really necessary
  276. dr.projection.rotate([100 / 2, 20 / 2, dr.projection.rotate()[2]]);
  277. }
  278. dr.path = d3.geo.path()
  279. .projection(dr.projection).pointRadius(0.2);
  280. console.log(scope.data);
  281. //Geocoded points are decoded into lonlat
  282. dr.points = _.map(scope.data, function (k, v) {
  283. //console.log(k,v);
  284. var decoded = geohash.decode(v);
  285. return [decoded.longitude, decoded.latitude];
  286. });
  287. //And also projected projected to x/y. Both sets of points are used
  288. //by different functions
  289. dr.projectedPoints = _.map(dr.points, function (coords) {
  290. return dr.projection(coords);
  291. });
  292. dr.svg.select(".overlay").remove();
  293. dr.svg.append("rect")
  294. .attr("class", "overlay")
  295. .attr("width", width)
  296. .attr("height", height)
  297. .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
  298. //Draw the countries, if this is a choropleth, draw with fancy colors
  299. var countryPath = dr.g.selectAll(".land")
  300. .data(dr.countries);
  301. countryPath.enter().append("path")
  302. .attr("class", function(d) {
  303. if (scope.panel.display.choropleth.enabled) {
  304. return 'land ' + dr.quantize(scope.data[d.short]);
  305. } else {
  306. return 'land';
  307. }
  308. })
  309. .attr("d", dr.path);
  310. countryPath.exit().remove();
  311. //If this is a sphere, set up drag and keypress listeners
  312. if (scope.panel.display.data.type === 'orthographic') {
  313. dr.svg.style("cursor", "move")
  314. .call(d3.behavior.drag()
  315. .origin(function() { var rotate = dr.projection.rotate(); return {x: 2 * rotate[0], y: -2 * rotate[1]}; })
  316. .on("drag", function() {
  317. if (scope.keylistener.keyActive(17)) {
  318. dr.projection.rotate([d3.event.x / 2, -d3.event.y / 2, dr.projection.rotate()[2]]);
  319. //dr.svg.selectAll("path").attr("d", dr.path);
  320. dr.g.selectAll("path").attr("d", dr.path);
  321. }
  322. }));
  323. }
  324. //Special fix for when the user changes from mercator -> orthographic
  325. //The globe won't redraw automatically, we need to force it
  326. if (scope.panel.display.data.type === 'orthographic') {
  327. dr.svg.selectAll("path").attr("d", dr.path);
  328. }
  329. /**
  330. * Display option rendering
  331. * Order is important to render order here!
  332. */
  333. //@todo fix this
  334. var dimensions = [width, height];
  335. displayBinning(scope, dr, dimensions);
  336. displayGeopoints(scope, dr);
  337. displayBullseye(scope, dr);
  338. //If the panel scale is not default (e.g. the user has moved the maps around)
  339. //set the scale and position to the last saved config
  340. if (scope.panel.display.scale != -1) {
  341. dr.zoom.scale(scope.panel.display.scale).translate(scope.panel.display.translate);
  342. dr.g.style("stroke-width", 1 / scope.panel.display.scale).attr("transform", "translate(" + scope.panel.display.translate + ") scale(" + scope.panel.display.scale + ")");
  343. }
  344. }
  345. /**
  346. * On D3 zoom events, pan/zoom the map
  347. * Only applies if the ctrl-key is not pressed, so it doesn't clobber
  348. * sphere dragging
  349. */
  350. function translate_map() {
  351. var width = $(elem[0]).width(),
  352. height = $(elem[0]).height();
  353. if (! scope.keylistener.keyActive(17)) {
  354. var t = d3.event.translate,
  355. s = d3.event.scale;
  356. t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
  357. t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
  358. dr.zoom.translate(t);
  359. scope.panel.display.translate = t;
  360. scope.panel.display.scale = s;
  361. dr.g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ") scale(" + s + ")");
  362. }
  363. }
  364. }
  365. };
  366. });