TileMapServiceImageryProvider.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import Cartesian2 from "../Core/Cartesian2.js";
  2. import Cartographic from "../Core/Cartographic.js";
  3. import Check from "../Core/Check.js";
  4. import defaultValue from "../Core/defaultValue.js";
  5. import defined from "../Core/defined.js";
  6. import deprecationWarning from "../Core/deprecationWarning.js";
  7. import GeographicProjection from "../Core/GeographicProjection.js";
  8. import GeographicTilingScheme from "../Core/GeographicTilingScheme.js";
  9. import Rectangle from "../Core/Rectangle.js";
  10. import RequestErrorEvent from "../Core/RequestErrorEvent.js";
  11. import Resource from "../Core/Resource.js";
  12. import RuntimeError from "../Core/RuntimeError.js";
  13. import TileProviderError from "../Core/TileProviderError.js";
  14. import WebMercatorTilingScheme from "../Core/WebMercatorTilingScheme.js";
  15. import UrlTemplateImageryProvider from "./UrlTemplateImageryProvider.js";
  16. /**
  17. * @typedef {object} TileMapServiceImageryProvider.ConstructorOptions
  18. *
  19. * Initialization options for the TileMapServiceImageryProvider constructor
  20. *
  21. * @property {Resource|string|Promise<Resource>|Promise<string>} [url] Path to image tiles on server. Deprecated
  22. * @property {string} [fileExtension='png'] The file extension for images on the server.
  23. * @property {Credit|string} [credit=''] A credit for the data source, which is displayed on the canvas.
  24. * @property {number} [minimumLevel=0] The minimum level-of-detail supported by the imagery provider. Take care when specifying
  25. * this that the number of tiles at the minimum level is small, such as four or less. A larger number is likely
  26. * to result in rendering problems.
  27. * @property {number} [maximumLevel] The maximum level-of-detail supported by the imagery provider, or undefined if there is no limit.
  28. * @property {Rectangle} [rectangle=Rectangle.MAX_VALUE] The rectangle, in radians, covered by the image.
  29. * @property {TilingScheme} [tilingScheme] The tiling scheme specifying how the ellipsoidal
  30. * surface is broken into tiles. If this parameter is not provided, a {@link WebMercatorTilingScheme}
  31. * is used.
  32. * @property {Ellipsoid} [ellipsoid] The ellipsoid. If the tilingScheme is specified,
  33. * this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither
  34. * parameter is specified, the WGS84 ellipsoid is used.
  35. * @property {number} [tileWidth=256] Pixel width of image tiles.
  36. * @property {number} [tileHeight=256] Pixel height of image tiles.
  37. * @property {boolean} [flipXY] Older versions of gdal2tiles.py flipped X and Y values in tilemapresource.xml.
  38. * @property {TileDiscardPolicy} [tileDiscardPolicy] A policy for discarding tile images according to some criteria
  39. * Specifying this option will do the same, allowing for loading of these incorrect tilesets.
  40. */
  41. /**
  42. * <div class="notice">
  43. * To construct a TileMapServiceImageryProvider, call {@link TileMapServiceImageryProvider.fromUrl}. Do not call the constructor directly.
  44. * </div>
  45. *
  46. * An imagery provider that provides tiled imagery as generated by
  47. * {@link http://www.maptiler.org/|MapTiler}, {@link http://www.klokan.cz/projects/gdal2tiles/|GDAL2Tiles}, etc.
  48. *
  49. * @alias TileMapServiceImageryProvider
  50. * @constructor
  51. * @extends UrlTemplateImageryProvider
  52. *
  53. * @param {TileMapServiceImageryProvider.ConstructorOptions} options Object describing initialization options
  54. *
  55. * @see ArcGisMapServerImageryProvider
  56. * @see BingMapsImageryProvider
  57. * @see GoogleEarthEnterpriseMapsProvider
  58. * @see OpenStreetMapImageryProvider
  59. * @see SingleTileImageryProvider
  60. * @see WebMapServiceImageryProvider
  61. * @see WebMapTileServiceImageryProvider
  62. * @see UrlTemplateImageryProvider
  63. *
  64. * @example
  65. * const tms = await Cesium.TileMapServiceImageryProvider.fromUrl(
  66. * "../images/cesium_maptiler/Cesium_Logo_Color", {
  67. * fileExtension: 'png',
  68. * maximumLevel: 4,
  69. * rectangle: new Cesium.Rectangle(
  70. * Cesium.Math.toRadians(-120.0),
  71. * Cesium.Math.toRadians(20.0),
  72. * Cesium.Math.toRadians(-60.0),
  73. * Cesium.Math.toRadians(40.0))
  74. * });
  75. */
  76. function TileMapServiceImageryProvider(options) {
  77. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  78. if (defined(options.url)) {
  79. deprecationWarning(
  80. "TileMapServiceImageryProvider options.url",
  81. "options.url was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use TileMapServiceImageryProvider.fromUrl instead."
  82. );
  83. this._metadataError = undefined;
  84. this._ready = false;
  85. let resource;
  86. const that = this;
  87. const promise = Promise.resolve(options.url)
  88. .then(function (url) {
  89. resource = Resource.createIfNeeded(url);
  90. resource.appendForwardSlash();
  91. that._tmsResource = resource;
  92. that._xmlResource = resource.getDerivedResource({
  93. url: "tilemapresource.xml",
  94. });
  95. return TileMapServiceImageryProvider._requestMetadata(
  96. options,
  97. that._tmsResource,
  98. that._xmlResource,
  99. that
  100. );
  101. })
  102. .catch((e) => {
  103. return Promise.reject(e);
  104. });
  105. UrlTemplateImageryProvider.call(this, promise);
  106. this._promise = promise;
  107. }
  108. // After readyPromise deprecation, this should become just
  109. // UrlTemplateImageryProvider.call(this, options);
  110. }
  111. TileMapServiceImageryProvider._requestMetadata = async function (
  112. options,
  113. tmsResource,
  114. xmlResource,
  115. provider
  116. ) {
  117. // Try to load remaining parameters from XML
  118. try {
  119. const xml = await xmlResource.fetchXML();
  120. return TileMapServiceImageryProvider._metadataSuccess(
  121. xml,
  122. options,
  123. tmsResource,
  124. xmlResource,
  125. provider
  126. );
  127. } catch (e) {
  128. if (e instanceof RequestErrorEvent) {
  129. return TileMapServiceImageryProvider._metadataFailure(
  130. options,
  131. tmsResource
  132. );
  133. }
  134. throw e;
  135. }
  136. };
  137. /**
  138. * Creates a TileMapServiceImageryProvider from the specified url.
  139. *
  140. * @param {Resource|String} url Path to image tiles on server.
  141. * @param {TileMapServiceImageryProvider.ConstructorOptions} [options] Object describing initialization options.
  142. * @returns {Promise<TileMapServiceImageryProvider>} A promise that resolves to the created TileMapServiceImageryProvider.
  143. *
  144. * @example
  145. * const tms = await Cesium.TileMapServiceImageryProvider.fromUrl(
  146. * '../images/cesium_maptiler/Cesium_Logo_Color', {
  147. * fileExtension: 'png',
  148. * maximumLevel: 4,
  149. * rectangle: new Cesium.Rectangle(
  150. * Cesium.Math.toRadians(-120.0),
  151. * Cesium.Math.toRadians(20.0),
  152. * Cesium.Math.toRadians(-60.0),
  153. * Cesium.Math.toRadians(40.0))
  154. * });
  155. *
  156. * @exception {RuntimeError} Unable to find expected tilesets or bbox attributes in tilemapresource.xml
  157. * @exception {RuntimeError} tilemapresource.xml specifies an unsupported profile attribute
  158. */
  159. TileMapServiceImageryProvider.fromUrl = async function (url, options) {
  160. //>>includeStart('debug', pragmas.debug);
  161. Check.defined("url", url);
  162. //>>includeEnd('debug');
  163. const resource = Resource.createIfNeeded(url);
  164. resource.appendForwardSlash();
  165. const tmsResource = resource;
  166. const xmlResource = resource.getDerivedResource({
  167. url: "tilemapresource.xml",
  168. });
  169. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  170. const metadata = await TileMapServiceImageryProvider._requestMetadata(
  171. options,
  172. tmsResource,
  173. xmlResource
  174. );
  175. // Once the deprecated behavior is removed, this can become
  176. // return new TileMapServiceImageryProvider(metadata);
  177. const provider = new TileMapServiceImageryProvider();
  178. UrlTemplateImageryProvider.call(provider, metadata);
  179. return provider;
  180. };
  181. if (defined(Object.create)) {
  182. TileMapServiceImageryProvider.prototype = Object.create(
  183. UrlTemplateImageryProvider.prototype
  184. );
  185. TileMapServiceImageryProvider.prototype.constructor = TileMapServiceImageryProvider;
  186. }
  187. /**
  188. * Mutates the properties of a given rectangle so it does not extend outside of the given tiling scheme's rectangle
  189. * @private
  190. */
  191. function confineRectangleToTilingScheme(rectangle, tilingScheme) {
  192. if (rectangle.west < tilingScheme.rectangle.west) {
  193. rectangle.west = tilingScheme.rectangle.west;
  194. }
  195. if (rectangle.east > tilingScheme.rectangle.east) {
  196. rectangle.east = tilingScheme.rectangle.east;
  197. }
  198. if (rectangle.south < tilingScheme.rectangle.south) {
  199. rectangle.south = tilingScheme.rectangle.south;
  200. }
  201. if (rectangle.north > tilingScheme.rectangle.north) {
  202. rectangle.north = tilingScheme.rectangle.north;
  203. }
  204. return rectangle;
  205. }
  206. function calculateSafeMinimumDetailLevel(
  207. tilingScheme,
  208. rectangle,
  209. minimumLevel
  210. ) {
  211. // Check the number of tiles at the minimum level. If it's more than four,
  212. // try requesting the lower levels anyway, because starting at the higher minimum
  213. // level will cause too many tiles to be downloaded and rendered.
  214. const swTile = tilingScheme.positionToTileXY(
  215. Rectangle.southwest(rectangle),
  216. minimumLevel
  217. );
  218. const neTile = tilingScheme.positionToTileXY(
  219. Rectangle.northeast(rectangle),
  220. minimumLevel
  221. );
  222. const tileCount =
  223. (Math.abs(neTile.x - swTile.x) + 1) * (Math.abs(neTile.y - swTile.y) + 1);
  224. if (tileCount > 4) {
  225. return 0;
  226. }
  227. return minimumLevel;
  228. }
  229. /**
  230. * Parses the results of a successful xml request
  231. * @private
  232. *
  233. * @param {Object} xml
  234. * @param {TileMapServiceImageryProvider.ConstructorOptions} options
  235. * @param {Resource} tmsResource
  236. * @param {Resource} xmlResource
  237. * @returns {UrlTemplateImageryProvider.ConstructorOptions}
  238. */
  239. TileMapServiceImageryProvider._metadataSuccess = function (
  240. xml,
  241. options,
  242. tmsResource,
  243. xmlResource,
  244. provider
  245. ) {
  246. const tileFormatRegex = /tileformat/i;
  247. const tileSetRegex = /tileset/i;
  248. const tileSetsRegex = /tilesets/i;
  249. const bboxRegex = /boundingbox/i;
  250. let format, bbox, tilesets;
  251. const tilesetsList = []; //list of TileSets
  252. // Allowing options properties (already copied to that) to override XML values
  253. // Iterate XML Document nodes for properties
  254. const nodeList = xml.childNodes[0].childNodes;
  255. for (let i = 0; i < nodeList.length; i++) {
  256. if (tileFormatRegex.test(nodeList.item(i).nodeName)) {
  257. format = nodeList.item(i);
  258. } else if (tileSetsRegex.test(nodeList.item(i).nodeName)) {
  259. tilesets = nodeList.item(i); // Node list of TileSets
  260. const tileSetNodes = nodeList.item(i).childNodes;
  261. // Iterate the nodes to find all TileSets
  262. for (let j = 0; j < tileSetNodes.length; j++) {
  263. if (tileSetRegex.test(tileSetNodes.item(j).nodeName)) {
  264. // Add them to tilesets list
  265. tilesetsList.push(tileSetNodes.item(j));
  266. }
  267. }
  268. } else if (bboxRegex.test(nodeList.item(i).nodeName)) {
  269. bbox = nodeList.item(i);
  270. }
  271. }
  272. let message;
  273. if (!defined(tilesets) || !defined(bbox)) {
  274. message = `Unable to find expected tilesets or bbox attributes in ${xmlResource.url}.`;
  275. if (defined(provider)) {
  276. TileProviderError.reportError(
  277. undefined,
  278. provider,
  279. provider.errorEvent,
  280. message
  281. );
  282. }
  283. throw new RuntimeError(message);
  284. }
  285. const fileExtension = defaultValue(
  286. options.fileExtension,
  287. format.getAttribute("extension")
  288. );
  289. const tileWidth = defaultValue(
  290. options.tileWidth,
  291. parseInt(format.getAttribute("width"), 10)
  292. );
  293. const tileHeight = defaultValue(
  294. options.tileHeight,
  295. parseInt(format.getAttribute("height"), 10)
  296. );
  297. let minimumLevel = defaultValue(
  298. options.minimumLevel,
  299. parseInt(tilesetsList[0].getAttribute("order"), 10)
  300. );
  301. const maximumLevel = defaultValue(
  302. options.maximumLevel,
  303. parseInt(tilesetsList[tilesetsList.length - 1].getAttribute("order"), 10)
  304. );
  305. const tilingSchemeName = tilesets.getAttribute("profile");
  306. let tilingScheme = options.tilingScheme;
  307. if (!defined(tilingScheme)) {
  308. if (
  309. tilingSchemeName === "geodetic" ||
  310. tilingSchemeName === "global-geodetic"
  311. ) {
  312. tilingScheme = new GeographicTilingScheme({
  313. ellipsoid: options.ellipsoid,
  314. });
  315. } else if (
  316. tilingSchemeName === "mercator" ||
  317. tilingSchemeName === "global-mercator"
  318. ) {
  319. tilingScheme = new WebMercatorTilingScheme({
  320. ellipsoid: options.ellipsoid,
  321. });
  322. } else {
  323. message = `${xmlResource.url} specifies an unsupported profile attribute, ${tilingSchemeName}.`;
  324. if (defined(provider)) {
  325. TileProviderError.reportError(
  326. undefined,
  327. provider,
  328. provider.errorEvent,
  329. message
  330. );
  331. }
  332. throw new RuntimeError(message);
  333. }
  334. }
  335. // rectangle handling
  336. let rectangle = Rectangle.clone(options.rectangle);
  337. if (!defined(rectangle)) {
  338. let sw;
  339. let ne;
  340. let swXY;
  341. let neXY;
  342. // In older versions of gdal x and y values were flipped, which is why we check for an option to flip
  343. // the values here as well. Unfortunately there is no way to autodetect whether flipping is needed.
  344. const flipXY = defaultValue(options.flipXY, false);
  345. if (flipXY) {
  346. swXY = new Cartesian2(
  347. parseFloat(bbox.getAttribute("miny")),
  348. parseFloat(bbox.getAttribute("minx"))
  349. );
  350. neXY = new Cartesian2(
  351. parseFloat(bbox.getAttribute("maxy")),
  352. parseFloat(bbox.getAttribute("maxx"))
  353. );
  354. } else {
  355. swXY = new Cartesian2(
  356. parseFloat(bbox.getAttribute("minx")),
  357. parseFloat(bbox.getAttribute("miny"))
  358. );
  359. neXY = new Cartesian2(
  360. parseFloat(bbox.getAttribute("maxx")),
  361. parseFloat(bbox.getAttribute("maxy"))
  362. );
  363. }
  364. // Determine based on the profile attribute if this tileset was generated by gdal2tiles.py, which
  365. // uses 'mercator' and 'geodetic' profiles, or by a tool compliant with the TMS standard, which is
  366. // 'global-mercator' and 'global-geodetic' profiles. In the gdal2Tiles case, X and Y are always in
  367. // geodetic degrees.
  368. const isGdal2tiles =
  369. tilingSchemeName === "geodetic" || tilingSchemeName === "mercator";
  370. if (
  371. tilingScheme.projection instanceof GeographicProjection ||
  372. isGdal2tiles
  373. ) {
  374. sw = Cartographic.fromDegrees(swXY.x, swXY.y);
  375. ne = Cartographic.fromDegrees(neXY.x, neXY.y);
  376. } else {
  377. const projection = tilingScheme.projection;
  378. sw = projection.unproject(swXY);
  379. ne = projection.unproject(neXY);
  380. }
  381. rectangle = new Rectangle(
  382. sw.longitude,
  383. sw.latitude,
  384. ne.longitude,
  385. ne.latitude
  386. );
  387. }
  388. // The rectangle must not be outside the bounds allowed by the tiling scheme.
  389. rectangle = confineRectangleToTilingScheme(rectangle, tilingScheme);
  390. // clamp our minimum detail level to something that isn't going to request a ridiculous number of tiles
  391. minimumLevel = calculateSafeMinimumDetailLevel(
  392. tilingScheme,
  393. rectangle,
  394. minimumLevel
  395. );
  396. const templateResource = tmsResource.getDerivedResource({
  397. url: `{z}/{x}/{reverseY}.${fileExtension}`,
  398. });
  399. return {
  400. url: templateResource,
  401. tilingScheme: tilingScheme,
  402. rectangle: rectangle,
  403. tileWidth: tileWidth,
  404. tileHeight: tileHeight,
  405. minimumLevel: minimumLevel,
  406. maximumLevel: maximumLevel,
  407. tileDiscardPolicy: options.tileDiscardPolicy,
  408. credit: options.credit,
  409. };
  410. };
  411. /**
  412. * Handle xml request failure by providing the default values
  413. * @private
  414. *
  415. * @param {TileMapServiceImageryProvider.ConstructorOptions} options
  416. * @param {Resource} tmsResource
  417. * @returns {UrlTemplateImageryProvider.ConstructorOptions}
  418. */
  419. TileMapServiceImageryProvider._metadataFailure = function (
  420. options,
  421. tmsResource
  422. ) {
  423. // Can't load XML, still allow options and defaults
  424. const fileExtension = defaultValue(options.fileExtension, "png");
  425. const tileWidth = defaultValue(options.tileWidth, 256);
  426. const tileHeight = defaultValue(options.tileHeight, 256);
  427. const maximumLevel = options.maximumLevel;
  428. const tilingScheme = defined(options.tilingScheme)
  429. ? options.tilingScheme
  430. : new WebMercatorTilingScheme({ ellipsoid: options.ellipsoid });
  431. let rectangle = defaultValue(options.rectangle, tilingScheme.rectangle);
  432. // The rectangle must not be outside the bounds allowed by the tiling scheme.
  433. rectangle = confineRectangleToTilingScheme(rectangle, tilingScheme);
  434. // make sure we use a safe minimum detail level, so we don't request a ridiculous number of tiles
  435. const minimumLevel = calculateSafeMinimumDetailLevel(
  436. tilingScheme,
  437. rectangle,
  438. options.minimumLevel
  439. );
  440. const templateResource = tmsResource.getDerivedResource({
  441. url: `{z}/{x}/{reverseY}.${fileExtension}`,
  442. });
  443. return {
  444. url: templateResource,
  445. tilingScheme: tilingScheme,
  446. rectangle: rectangle,
  447. tileWidth: tileWidth,
  448. tileHeight: tileHeight,
  449. minimumLevel: minimumLevel,
  450. maximumLevel: maximumLevel,
  451. tileDiscardPolicy: options.tileDiscardPolicy,
  452. credit: options.credit,
  453. };
  454. };
  455. export default TileMapServiceImageryProvider;