module.js 15 KB

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