module.js 15 KB

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