leaflet-rastercoords.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * leaflet plugin for plain image map projection
  3. * @copyright 2016- commenthol
  4. * @license MIT
  5. */
  6. /* globals define */
  7. ;(function (factory) {
  8. var L
  9. if (typeof define === 'function' && define.amd) {
  10. // AMD
  11. define(['leaflet'], factory)
  12. } else if (typeof module !== 'undefined') {
  13. // Node/CommonJS
  14. L = require('leaflet')
  15. module.exports = factory(L)
  16. } else {
  17. // Browser globals
  18. if (typeof window.L === 'undefined') {
  19. throw new Error('Leaflet must be loaded first')
  20. }
  21. factory(window.L)
  22. }
  23. }(function (L) {
  24. /**
  25. * L.RasterCoords
  26. * @param {L.map} map - the map used
  27. * @param {Array} imgsize - [ width, height ] image dimensions
  28. * @param {Number} [tilesize] - tilesize in pixels. Default=256
  29. */
  30. L.RasterCoords = function (map, imgsize, tilesize) {
  31. this.map = map
  32. this.width = imgsize[0]
  33. this.height = imgsize[1]
  34. this.tilesize = tilesize || 256
  35. this.zoom = this.zoomLevel()
  36. if (this.width && this.height) {
  37. this.setMaxBounds()
  38. }
  39. }
  40. L.RasterCoords.prototype = {
  41. /**
  42. * calculate accurate zoom level for the given image size
  43. */
  44. zoomLevel: function () {
  45. return Math.ceil(
  46. Math.log(
  47. Math.max(this.width, this.height) /
  48. this.tilesize
  49. ) / Math.log(2)
  50. )
  51. },
  52. /**
  53. * unproject `coords` to the raster coordinates used by the raster image projection
  54. * @param {Array} coords - [ x, y ]
  55. * @return {L.LatLng} - internal coordinates
  56. */
  57. unproject: function (coords) {
  58. return this.map.unproject(coords, this.zoom)
  59. },
  60. /**
  61. * project `coords` back to image coordinates
  62. * @param {Array} coords - [ x, y ]
  63. * @return {L.LatLng} - image coordinates
  64. */
  65. project: function (coords) {
  66. return this.map.project(coords, this.zoom)
  67. },
  68. /**
  69. * sets the max bounds on map
  70. */
  71. setMaxBounds: function () {
  72. var southWest = this.unproject([0, this.height])
  73. var northEast = this.unproject([this.width, 0])
  74. this.map.setMaxBounds(new L.LatLngBounds(southWest, northEast))
  75. }
  76. }
  77. return L.RasterCoords
  78. }))
  79. ; // eslint-disable-line semi