module.js 15 KB

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