GeoJsonDataSource.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. import ArcType from "../Core/ArcType.js";
  2. import Cartesian3 from "../Core/Cartesian3.js";
  3. import Color from "../Core/Color.js";
  4. import createGuid from "../Core/createGuid.js";
  5. import Credit from "../Core/Credit.js";
  6. import defaultValue from "../Core/defaultValue.js";
  7. import defined from "../Core/defined.js";
  8. import DeveloperError from "../Core/DeveloperError.js";
  9. import Event from "../Core/Event.js";
  10. import getFilenameFromUri from "../Core/getFilenameFromUri.js";
  11. import PinBuilder from "../Core/PinBuilder.js";
  12. import PolygonHierarchy from "../Core/PolygonHierarchy.js";
  13. import Resource from "../Core/Resource.js";
  14. import RuntimeError from "../Core/RuntimeError.js";
  15. import HeightReference from "../Scene/HeightReference.js";
  16. import VerticalOrigin from "../Scene/VerticalOrigin.js";
  17. import * as topojson from "topojson-client";
  18. import BillboardGraphics from "./BillboardGraphics.js";
  19. import CallbackProperty from "./CallbackProperty.js";
  20. import ColorMaterialProperty from "./ColorMaterialProperty.js";
  21. import ConstantPositionProperty from "./ConstantPositionProperty.js";
  22. import ConstantProperty from "./ConstantProperty.js";
  23. import DataSource from "./DataSource.js";
  24. import EntityCluster from "./EntityCluster.js";
  25. import EntityCollection from "./EntityCollection.js";
  26. import PolygonGraphics from "./PolygonGraphics.js";
  27. import PolylineGraphics from "./PolylineGraphics.js";
  28. function defaultCrsFunction(coordinates) {
  29. return Cartesian3.fromDegrees(coordinates[0], coordinates[1], coordinates[2]);
  30. }
  31. const crsNames = {
  32. "urn:ogc:def:crs:OGC:1.3:CRS84": defaultCrsFunction,
  33. "EPSG:4326": defaultCrsFunction,
  34. "urn:ogc:def:crs:EPSG::4326": defaultCrsFunction,
  35. };
  36. const crsLinkHrefs = {};
  37. const crsLinkTypes = {};
  38. let defaultMarkerSize = 48;
  39. let defaultMarkerSymbol;
  40. let defaultMarkerColor = Color.ROYALBLUE;
  41. let defaultStroke = Color.YELLOW;
  42. let defaultStrokeWidth = 2;
  43. let defaultFill = Color.fromBytes(255, 255, 0, 100);
  44. let defaultClampToGround = false;
  45. const sizes = {
  46. small: 24,
  47. medium: 48,
  48. large: 64,
  49. };
  50. const simpleStyleIdentifiers = [
  51. "title",
  52. "description", //
  53. "marker-size",
  54. "marker-symbol",
  55. "marker-color",
  56. "stroke", //
  57. "stroke-opacity",
  58. "stroke-width",
  59. "fill",
  60. "fill-opacity",
  61. ];
  62. function defaultDescribe(properties, nameProperty) {
  63. let html = "";
  64. for (const key in properties) {
  65. if (properties.hasOwnProperty(key)) {
  66. if (key === nameProperty || simpleStyleIdentifiers.indexOf(key) !== -1) {
  67. continue;
  68. }
  69. const value = properties[key];
  70. if (defined(value)) {
  71. if (typeof value === "object") {
  72. html += `<tr><th>${key}</th><td>${defaultDescribe(value)}</td></tr>`;
  73. } else {
  74. html += `<tr><th>${key}</th><td>${value}</td></tr>`;
  75. }
  76. }
  77. }
  78. }
  79. if (html.length > 0) {
  80. html = `<table class="cesium-infoBox-defaultTable"><tbody>${html}</tbody></table>`;
  81. }
  82. return html;
  83. }
  84. function createDescriptionCallback(describe, properties, nameProperty) {
  85. let description;
  86. return function (time, result) {
  87. if (!defined(description)) {
  88. description = describe(properties, nameProperty);
  89. }
  90. return description;
  91. };
  92. }
  93. function defaultDescribeProperty(properties, nameProperty) {
  94. return new CallbackProperty(
  95. createDescriptionCallback(defaultDescribe, properties, nameProperty),
  96. true
  97. );
  98. }
  99. //GeoJSON specifies only the Feature object has a usable id property
  100. //But since "multi" geometries create multiple entity,
  101. //we can't use it for them either.
  102. function createObject(geoJson, entityCollection, describe) {
  103. let id = geoJson.id;
  104. if (!defined(id) || geoJson.type !== "Feature") {
  105. id = createGuid();
  106. } else {
  107. let i = 2;
  108. let finalId = id;
  109. while (defined(entityCollection.getById(finalId))) {
  110. finalId = `${id}_${i}`;
  111. i++;
  112. }
  113. id = finalId;
  114. }
  115. const entity = entityCollection.getOrCreateEntity(id);
  116. const properties = geoJson.properties;
  117. if (defined(properties)) {
  118. entity.properties = properties;
  119. let nameProperty;
  120. //Check for the simplestyle specified name first.
  121. const name = properties.title;
  122. if (defined(name)) {
  123. entity.name = name;
  124. nameProperty = "title";
  125. } else {
  126. //Else, find the name by selecting an appropriate property.
  127. //The name will be obtained based on this order:
  128. //1) The first case-insensitive property with the name 'title',
  129. //2) The first case-insensitive property with the name 'name',
  130. //3) The first property containing the word 'title'.
  131. //4) The first property containing the word 'name',
  132. let namePropertyPrecedence = Number.MAX_VALUE;
  133. for (const key in properties) {
  134. if (properties.hasOwnProperty(key) && properties[key]) {
  135. const lowerKey = key.toLowerCase();
  136. if (namePropertyPrecedence > 1 && lowerKey === "title") {
  137. namePropertyPrecedence = 1;
  138. nameProperty = key;
  139. break;
  140. } else if (namePropertyPrecedence > 2 && lowerKey === "name") {
  141. namePropertyPrecedence = 2;
  142. nameProperty = key;
  143. } else if (namePropertyPrecedence > 3 && /title/i.test(key)) {
  144. namePropertyPrecedence = 3;
  145. nameProperty = key;
  146. } else if (namePropertyPrecedence > 4 && /name/i.test(key)) {
  147. namePropertyPrecedence = 4;
  148. nameProperty = key;
  149. }
  150. }
  151. }
  152. if (defined(nameProperty)) {
  153. entity.name = properties[nameProperty];
  154. }
  155. }
  156. const description = properties.description;
  157. if (description !== null) {
  158. entity.description = !defined(description)
  159. ? describe(properties, nameProperty)
  160. : new ConstantProperty(description);
  161. }
  162. }
  163. return entity;
  164. }
  165. function coordinatesArrayToCartesianArray(coordinates, crsFunction) {
  166. const positions = new Array(coordinates.length);
  167. for (let i = 0; i < coordinates.length; i++) {
  168. positions[i] = crsFunction(coordinates[i]);
  169. }
  170. return positions;
  171. }
  172. const geoJsonObjectTypes = {
  173. Feature: processFeature,
  174. FeatureCollection: processFeatureCollection,
  175. GeometryCollection: processGeometryCollection,
  176. LineString: processLineString,
  177. MultiLineString: processMultiLineString,
  178. MultiPoint: processMultiPoint,
  179. MultiPolygon: processMultiPolygon,
  180. Point: processPoint,
  181. Polygon: processPolygon,
  182. Topology: processTopology,
  183. };
  184. const geometryTypes = {
  185. GeometryCollection: processGeometryCollection,
  186. LineString: processLineString,
  187. MultiLineString: processMultiLineString,
  188. MultiPoint: processMultiPoint,
  189. MultiPolygon: processMultiPolygon,
  190. Point: processPoint,
  191. Polygon: processPolygon,
  192. Topology: processTopology,
  193. };
  194. // GeoJSON processing functions
  195. function processFeature(dataSource, feature, notUsed, crsFunction, options) {
  196. if (feature.geometry === null) {
  197. //Null geometry is allowed, so just create an empty entity instance for it.
  198. createObject(feature, dataSource._entityCollection, options.describe);
  199. return;
  200. }
  201. if (!defined(feature.geometry)) {
  202. throw new RuntimeError("feature.geometry is required.");
  203. }
  204. const geometryType = feature.geometry.type;
  205. const geometryHandler = geometryTypes[geometryType];
  206. if (!defined(geometryHandler)) {
  207. throw new RuntimeError(`Unknown geometry type: ${geometryType}`);
  208. }
  209. geometryHandler(dataSource, feature, feature.geometry, crsFunction, options);
  210. }
  211. function processFeatureCollection(
  212. dataSource,
  213. featureCollection,
  214. notUsed,
  215. crsFunction,
  216. options
  217. ) {
  218. const features = featureCollection.features;
  219. for (let i = 0, len = features.length; i < len; i++) {
  220. processFeature(dataSource, features[i], undefined, crsFunction, options);
  221. }
  222. }
  223. function processGeometryCollection(
  224. dataSource,
  225. geoJson,
  226. geometryCollection,
  227. crsFunction,
  228. options
  229. ) {
  230. const geometries = geometryCollection.geometries;
  231. for (let i = 0, len = geometries.length; i < len; i++) {
  232. const geometry = geometries[i];
  233. const geometryType = geometry.type;
  234. const geometryHandler = geometryTypes[geometryType];
  235. if (!defined(geometryHandler)) {
  236. throw new RuntimeError(`Unknown geometry type: ${geometryType}`);
  237. }
  238. geometryHandler(dataSource, geoJson, geometry, crsFunction, options);
  239. }
  240. }
  241. function createPoint(dataSource, geoJson, crsFunction, coordinates, options) {
  242. let symbol = options.markerSymbol;
  243. let color = options.markerColor;
  244. let size = options.markerSize;
  245. const properties = geoJson.properties;
  246. if (defined(properties)) {
  247. const cssColor = properties["marker-color"];
  248. if (defined(cssColor)) {
  249. color = Color.fromCssColorString(cssColor);
  250. }
  251. size = defaultValue(sizes[properties["marker-size"]], size);
  252. const markerSymbol = properties["marker-symbol"];
  253. if (defined(markerSymbol)) {
  254. symbol = markerSymbol;
  255. }
  256. }
  257. let canvasOrPromise;
  258. if (defined(symbol)) {
  259. if (symbol.length === 1) {
  260. canvasOrPromise = dataSource._pinBuilder.fromText(
  261. symbol.toUpperCase(),
  262. color,
  263. size
  264. );
  265. } else {
  266. canvasOrPromise = dataSource._pinBuilder.fromMakiIconId(
  267. symbol,
  268. color,
  269. size
  270. );
  271. }
  272. } else {
  273. canvasOrPromise = dataSource._pinBuilder.fromColor(color, size);
  274. }
  275. const billboard = new BillboardGraphics();
  276. billboard.verticalOrigin = new ConstantProperty(VerticalOrigin.BOTTOM);
  277. // Clamp to ground if there isn't a height specified
  278. if (coordinates.length === 2 && options.clampToGround) {
  279. billboard.heightReference = HeightReference.CLAMP_TO_GROUND;
  280. }
  281. const entity = createObject(
  282. geoJson,
  283. dataSource._entityCollection,
  284. options.describe
  285. );
  286. entity.billboard = billboard;
  287. entity.position = new ConstantPositionProperty(crsFunction(coordinates));
  288. const promise = Promise.resolve(canvasOrPromise)
  289. .then(function (image) {
  290. billboard.image = new ConstantProperty(image);
  291. })
  292. .catch(function () {
  293. billboard.image = new ConstantProperty(
  294. dataSource._pinBuilder.fromColor(color, size)
  295. );
  296. });
  297. dataSource._promises.push(promise);
  298. }
  299. function processPoint(dataSource, geoJson, geometry, crsFunction, options) {
  300. createPoint(dataSource, geoJson, crsFunction, geometry.coordinates, options);
  301. }
  302. function processMultiPoint(
  303. dataSource,
  304. geoJson,
  305. geometry,
  306. crsFunction,
  307. options
  308. ) {
  309. const coordinates = geometry.coordinates;
  310. for (let i = 0; i < coordinates.length; i++) {
  311. createPoint(dataSource, geoJson, crsFunction, coordinates[i], options);
  312. }
  313. }
  314. function createLineString(
  315. dataSource,
  316. geoJson,
  317. crsFunction,
  318. coordinates,
  319. options
  320. ) {
  321. let material = options.strokeMaterialProperty;
  322. let widthProperty = options.strokeWidthProperty;
  323. const properties = geoJson.properties;
  324. if (defined(properties)) {
  325. const width = properties["stroke-width"];
  326. if (defined(width)) {
  327. widthProperty = new ConstantProperty(width);
  328. }
  329. let color;
  330. const stroke = properties.stroke;
  331. if (defined(stroke)) {
  332. color = Color.fromCssColorString(stroke);
  333. }
  334. const opacity = properties["stroke-opacity"];
  335. if (defined(opacity) && opacity !== 1.0) {
  336. if (!defined(color)) {
  337. color = material.color.getValue().clone();
  338. }
  339. color.alpha = opacity;
  340. }
  341. if (defined(color)) {
  342. material = new ColorMaterialProperty(color);
  343. }
  344. }
  345. const entity = createObject(
  346. geoJson,
  347. dataSource._entityCollection,
  348. options.describe
  349. );
  350. const polylineGraphics = new PolylineGraphics();
  351. entity.polyline = polylineGraphics;
  352. polylineGraphics.clampToGround = options.clampToGround;
  353. polylineGraphics.material = material;
  354. polylineGraphics.width = widthProperty;
  355. polylineGraphics.positions = new ConstantProperty(
  356. coordinatesArrayToCartesianArray(coordinates, crsFunction)
  357. );
  358. polylineGraphics.arcType = ArcType.RHUMB;
  359. }
  360. function processLineString(
  361. dataSource,
  362. geoJson,
  363. geometry,
  364. crsFunction,
  365. options
  366. ) {
  367. createLineString(
  368. dataSource,
  369. geoJson,
  370. crsFunction,
  371. geometry.coordinates,
  372. options
  373. );
  374. }
  375. function processMultiLineString(
  376. dataSource,
  377. geoJson,
  378. geometry,
  379. crsFunction,
  380. options
  381. ) {
  382. const lineStrings = geometry.coordinates;
  383. for (let i = 0; i < lineStrings.length; i++) {
  384. createLineString(dataSource, geoJson, crsFunction, lineStrings[i], options);
  385. }
  386. }
  387. function createPolygon(dataSource, geoJson, crsFunction, coordinates, options) {
  388. if (coordinates.length === 0 || coordinates[0].length === 0) {
  389. return;
  390. }
  391. let outlineColorProperty = options.strokeMaterialProperty.color;
  392. let material = options.fillMaterialProperty;
  393. let widthProperty = options.strokeWidthProperty;
  394. const properties = geoJson.properties;
  395. if (defined(properties)) {
  396. const width = properties["stroke-width"];
  397. if (defined(width)) {
  398. widthProperty = new ConstantProperty(width);
  399. }
  400. let color;
  401. const stroke = properties.stroke;
  402. if (defined(stroke)) {
  403. color = Color.fromCssColorString(stroke);
  404. }
  405. let opacity = properties["stroke-opacity"];
  406. if (defined(opacity) && opacity !== 1.0) {
  407. if (!defined(color)) {
  408. color = outlineColorProperty.getValue().clone();
  409. }
  410. color.alpha = opacity;
  411. }
  412. if (defined(color)) {
  413. outlineColorProperty = new ConstantProperty(color);
  414. }
  415. let fillColor;
  416. const fill = properties.fill;
  417. const materialColor = material.color.getValue();
  418. if (defined(fill)) {
  419. fillColor = Color.fromCssColorString(fill);
  420. fillColor.alpha = materialColor.alpha;
  421. }
  422. opacity = properties["fill-opacity"];
  423. if (defined(opacity) && opacity !== materialColor.alpha) {
  424. if (!defined(fillColor)) {
  425. fillColor = materialColor.clone();
  426. }
  427. fillColor.alpha = opacity;
  428. }
  429. if (defined(fillColor)) {
  430. material = new ColorMaterialProperty(fillColor);
  431. }
  432. }
  433. const polygon = new PolygonGraphics();
  434. polygon.outline = new ConstantProperty(true);
  435. polygon.outlineColor = outlineColorProperty;
  436. polygon.outlineWidth = widthProperty;
  437. polygon.material = material;
  438. polygon.arcType = ArcType.RHUMB;
  439. const holes = [];
  440. for (let i = 1, len = coordinates.length; i < len; i++) {
  441. holes.push(
  442. new PolygonHierarchy(
  443. coordinatesArrayToCartesianArray(coordinates[i], crsFunction)
  444. )
  445. );
  446. }
  447. const positions = coordinates[0];
  448. polygon.hierarchy = new ConstantProperty(
  449. new PolygonHierarchy(
  450. coordinatesArrayToCartesianArray(positions, crsFunction),
  451. holes
  452. )
  453. );
  454. if (positions[0].length > 2) {
  455. polygon.perPositionHeight = new ConstantProperty(true);
  456. } else if (!options.clampToGround) {
  457. polygon.height = 0;
  458. }
  459. const entity = createObject(
  460. geoJson,
  461. dataSource._entityCollection,
  462. options.describe
  463. );
  464. entity.polygon = polygon;
  465. }
  466. function processPolygon(dataSource, geoJson, geometry, crsFunction, options) {
  467. createPolygon(
  468. dataSource,
  469. geoJson,
  470. crsFunction,
  471. geometry.coordinates,
  472. options
  473. );
  474. }
  475. function processMultiPolygon(
  476. dataSource,
  477. geoJson,
  478. geometry,
  479. crsFunction,
  480. options
  481. ) {
  482. const polygons = geometry.coordinates;
  483. for (let i = 0; i < polygons.length; i++) {
  484. createPolygon(dataSource, geoJson, crsFunction, polygons[i], options);
  485. }
  486. }
  487. function processTopology(dataSource, geoJson, geometry, crsFunction, options) {
  488. for (const property in geometry.objects) {
  489. if (geometry.objects.hasOwnProperty(property)) {
  490. const feature = topojson.feature(geometry, geometry.objects[property]);
  491. const typeHandler = geoJsonObjectTypes[feature.type];
  492. typeHandler(dataSource, feature, feature, crsFunction, options);
  493. }
  494. }
  495. }
  496. /**
  497. * @typedef {object} GeoJsonDataSource.LoadOptions
  498. *
  499. * Initialization options for the <code>load</code> method.
  500. *
  501. * @property {string} [sourceUri] Overrides the url to use for resolving relative links.
  502. * @property {GeoJsonDataSource.describe} [describe=GeoJsonDataSource.defaultDescribeProperty] A function which returns a Property object (or just a string).
  503. * @property {number} [markerSize=GeoJsonDataSource.markerSize] The default size of the map pin created for each point, in pixels.
  504. * @property {string} [markerSymbol=GeoJsonDataSource.markerSymbol] The default symbol of the map pin created for each point.
  505. * @property {Color} [markerColor=GeoJsonDataSource.markerColor] The default color of the map pin created for each point.
  506. * @property {Color} [stroke=GeoJsonDataSource.stroke] The default color of polylines and polygon outlines.
  507. * @property {number} [strokeWidth=GeoJsonDataSource.strokeWidth] The default width of polylines and polygon outlines.
  508. * @property {Color} [fill=GeoJsonDataSource.fill] The default color for polygon interiors.
  509. * @property {boolean} [clampToGround=GeoJsonDataSource.clampToGround] true if we want the geometry features (polygons or linestrings) clamped to the ground.
  510. * @property {Credit|string} [credit] A credit for the data source, which is displayed on the canvas.
  511. */
  512. /**
  513. * A {@link DataSource} which processes both
  514. * {@link http://www.geojson.org/|GeoJSON} and {@link https://github.com/mbostock/topojson|TopoJSON} data.
  515. * {@link https://github.com/mapbox/simplestyle-spec|simplestyle-spec} properties will also be used if they
  516. * are present.
  517. *
  518. * @alias GeoJsonDataSource
  519. * @constructor
  520. *
  521. * @param {string} [name] The name of this data source. If undefined, a name will be taken from
  522. * the name of the GeoJSON file.
  523. *
  524. * @demo {@link https://sandcastle.cesium.com/index.html?src=GeoJSON%20and%20TopoJSON.html|Cesium Sandcastle GeoJSON and TopoJSON Demo}
  525. * @demo {@link https://sandcastle.cesium.com/index.html?src=GeoJSON%20simplestyle.html|Cesium Sandcastle GeoJSON simplestyle Demo}
  526. *
  527. * @example
  528. * const viewer = new Cesium.Viewer('cesiumContainer');
  529. * viewer.dataSources.add(Cesium.GeoJsonDataSource.load('../../SampleData/ne_10m_us_states.topojson', {
  530. * stroke: Cesium.Color.HOTPINK,
  531. * fill: Cesium.Color.PINK,
  532. * strokeWidth: 3,
  533. * markerSymbol: '?'
  534. * }));
  535. */
  536. function GeoJsonDataSource(name) {
  537. this._name = name;
  538. this._changed = new Event();
  539. this._error = new Event();
  540. this._isLoading = false;
  541. this._loading = new Event();
  542. this._entityCollection = new EntityCollection(this);
  543. this._promises = [];
  544. this._pinBuilder = new PinBuilder();
  545. this._entityCluster = new EntityCluster();
  546. this._credit = undefined;
  547. this._resourceCredits = [];
  548. }
  549. /**
  550. * Creates a Promise to a new instance loaded with the provided GeoJSON or TopoJSON data.
  551. *
  552. * @param {Resource|string|object} data A url, GeoJSON object, or TopoJSON object to be loaded.
  553. * @param {GeoJsonDataSource.LoadOptions} [options] An object specifying configuration options
  554. *
  555. * @returns {Promise<GeoJsonDataSource>} A promise that will resolve when the data is loaded.
  556. */
  557. GeoJsonDataSource.load = function (data, options) {
  558. return new GeoJsonDataSource().load(data, options);
  559. };
  560. Object.defineProperties(GeoJsonDataSource, {
  561. /**
  562. * Gets or sets the default size of the map pin created for each point, in pixels.
  563. * @memberof GeoJsonDataSource
  564. * @type {number}
  565. * @default 48
  566. */
  567. markerSize: {
  568. get: function () {
  569. return defaultMarkerSize;
  570. },
  571. set: function (value) {
  572. defaultMarkerSize = value;
  573. },
  574. },
  575. /**
  576. * Gets or sets the default symbol of the map pin created for each point.
  577. * This can be any valid {@link http://mapbox.com/maki/|Maki} identifier, any single character,
  578. * or blank if no symbol is to be used.
  579. * @memberof GeoJsonDataSource
  580. * @type {string}
  581. */
  582. markerSymbol: {
  583. get: function () {
  584. return defaultMarkerSymbol;
  585. },
  586. set: function (value) {
  587. defaultMarkerSymbol = value;
  588. },
  589. },
  590. /**
  591. * Gets or sets the default color of the map pin created for each point.
  592. * @memberof GeoJsonDataSource
  593. * @type {Color}
  594. * @default Color.ROYALBLUE
  595. */
  596. markerColor: {
  597. get: function () {
  598. return defaultMarkerColor;
  599. },
  600. set: function (value) {
  601. defaultMarkerColor = value;
  602. },
  603. },
  604. /**
  605. * Gets or sets the default color of polylines and polygon outlines.
  606. * @memberof GeoJsonDataSource
  607. * @type {Color}
  608. * @default Color.BLACK
  609. */
  610. stroke: {
  611. get: function () {
  612. return defaultStroke;
  613. },
  614. set: function (value) {
  615. defaultStroke = value;
  616. },
  617. },
  618. /**
  619. * Gets or sets the default width of polylines and polygon outlines.
  620. * @memberof GeoJsonDataSource
  621. * @type {number}
  622. * @default 2.0
  623. */
  624. strokeWidth: {
  625. get: function () {
  626. return defaultStrokeWidth;
  627. },
  628. set: function (value) {
  629. defaultStrokeWidth = value;
  630. },
  631. },
  632. /**
  633. * Gets or sets default color for polygon interiors.
  634. * @memberof GeoJsonDataSource
  635. * @type {Color}
  636. * @default Color.YELLOW
  637. */
  638. fill: {
  639. get: function () {
  640. return defaultFill;
  641. },
  642. set: function (value) {
  643. defaultFill = value;
  644. },
  645. },
  646. /**
  647. * Gets or sets default of whether to clamp to the ground.
  648. * @memberof GeoJsonDataSource
  649. * @type {boolean}
  650. * @default false
  651. */
  652. clampToGround: {
  653. get: function () {
  654. return defaultClampToGround;
  655. },
  656. set: function (value) {
  657. defaultClampToGround = value;
  658. },
  659. },
  660. /**
  661. * Gets an object that maps the name of a crs to a callback function which takes a GeoJSON coordinate
  662. * and transforms it into a WGS84 Earth-fixed Cartesian. Older versions of GeoJSON which
  663. * supported the EPSG type can be added to this list as well, by specifying the complete EPSG name,
  664. * for example 'EPSG:4326'.
  665. * @memberof GeoJsonDataSource
  666. * @type {object}
  667. */
  668. crsNames: {
  669. get: function () {
  670. return crsNames;
  671. },
  672. },
  673. /**
  674. * Gets an object that maps the href property of a crs link to a callback function
  675. * which takes the crs properties object and returns a Promise that resolves
  676. * to a function that takes a GeoJSON coordinate and transforms it into a WGS84 Earth-fixed Cartesian.
  677. * Items in this object take precedence over those defined in <code>crsLinkHrefs</code>, assuming
  678. * the link has a type specified.
  679. * @memberof GeoJsonDataSource
  680. * @type {object}
  681. */
  682. crsLinkHrefs: {
  683. get: function () {
  684. return crsLinkHrefs;
  685. },
  686. },
  687. /**
  688. * Gets an object that maps the type property of a crs link to a callback function
  689. * which takes the crs properties object and returns a Promise that resolves
  690. * to a function that takes a GeoJSON coordinate and transforms it into a WGS84 Earth-fixed Cartesian.
  691. * Items in <code>crsLinkHrefs</code> take precedence over this object.
  692. * @memberof GeoJsonDataSource
  693. * @type {object}
  694. */
  695. crsLinkTypes: {
  696. get: function () {
  697. return crsLinkTypes;
  698. },
  699. },
  700. });
  701. Object.defineProperties(GeoJsonDataSource.prototype, {
  702. /**
  703. * Gets or sets a human-readable name for this instance.
  704. * @memberof GeoJsonDataSource.prototype
  705. * @type {string}
  706. */
  707. name: {
  708. get: function () {
  709. return this._name;
  710. },
  711. set: function (value) {
  712. if (this._name !== value) {
  713. this._name = value;
  714. this._changed.raiseEvent(this);
  715. }
  716. },
  717. },
  718. /**
  719. * This DataSource only defines static data, therefore this property is always undefined.
  720. * @memberof GeoJsonDataSource.prototype
  721. * @type {DataSourceClock}
  722. */
  723. clock: {
  724. value: undefined,
  725. writable: false,
  726. },
  727. /**
  728. * Gets the collection of {@link Entity} instances.
  729. * @memberof GeoJsonDataSource.prototype
  730. * @type {EntityCollection}
  731. */
  732. entities: {
  733. get: function () {
  734. return this._entityCollection;
  735. },
  736. },
  737. /**
  738. * Gets a value indicating if the data source is currently loading data.
  739. * @memberof GeoJsonDataSource.prototype
  740. * @type {boolean}
  741. */
  742. isLoading: {
  743. get: function () {
  744. return this._isLoading;
  745. },
  746. },
  747. /**
  748. * Gets an event that will be raised when the underlying data changes.
  749. * @memberof GeoJsonDataSource.prototype
  750. * @type {Event}
  751. */
  752. changedEvent: {
  753. get: function () {
  754. return this._changed;
  755. },
  756. },
  757. /**
  758. * Gets an event that will be raised if an error is encountered during processing.
  759. * @memberof GeoJsonDataSource.prototype
  760. * @type {Event}
  761. */
  762. errorEvent: {
  763. get: function () {
  764. return this._error;
  765. },
  766. },
  767. /**
  768. * Gets an event that will be raised when the data source either starts or stops loading.
  769. * @memberof GeoJsonDataSource.prototype
  770. * @type {Event}
  771. */
  772. loadingEvent: {
  773. get: function () {
  774. return this._loading;
  775. },
  776. },
  777. /**
  778. * Gets whether or not this data source should be displayed.
  779. * @memberof GeoJsonDataSource.prototype
  780. * @type {boolean}
  781. */
  782. show: {
  783. get: function () {
  784. return this._entityCollection.show;
  785. },
  786. set: function (value) {
  787. this._entityCollection.show = value;
  788. },
  789. },
  790. /**
  791. * Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
  792. *
  793. * @memberof GeoJsonDataSource.prototype
  794. * @type {EntityCluster}
  795. */
  796. clustering: {
  797. get: function () {
  798. return this._entityCluster;
  799. },
  800. set: function (value) {
  801. //>>includeStart('debug', pragmas.debug);
  802. if (!defined(value)) {
  803. throw new DeveloperError("value must be defined.");
  804. }
  805. //>>includeEnd('debug');
  806. this._entityCluster = value;
  807. },
  808. },
  809. /**
  810. * Gets the credit that will be displayed for the data source
  811. * @memberof GeoJsonDataSource.prototype
  812. * @type {Credit}
  813. */
  814. credit: {
  815. get: function () {
  816. return this._credit;
  817. },
  818. },
  819. });
  820. /**
  821. * Asynchronously loads the provided GeoJSON or TopoJSON data, replacing any existing data.
  822. *
  823. * @param {Resource|string|object} data A url, GeoJSON object, or TopoJSON object to be loaded.
  824. * @param {GeoJsonDataSource.LoadOptions} [options] An object specifying configuration options
  825. *
  826. * @returns {Promise<GeoJsonDataSource>} a promise that will resolve when the GeoJSON is loaded.
  827. */
  828. GeoJsonDataSource.prototype.load = function (data, options) {
  829. return preload(this, data, options, true);
  830. };
  831. /**
  832. * Asynchronously loads the provided GeoJSON or TopoJSON data, without replacing any existing data.
  833. *
  834. * @param {Resource|string|object} data A url, GeoJSON object, or TopoJSON object to be loaded.
  835. * @param {GeoJsonDataSource.LoadOptions} [options] An object specifying configuration options
  836. *
  837. * @returns {Promise<GeoJsonDataSource>} a promise that will resolve when the GeoJSON is loaded.
  838. */
  839. GeoJsonDataSource.prototype.process = function (data, options) {
  840. return preload(this, data, options, false);
  841. };
  842. function preload(that, data, options, clear) {
  843. //>>includeStart('debug', pragmas.debug);
  844. if (!defined(data)) {
  845. throw new DeveloperError("data is required.");
  846. }
  847. //>>includeEnd('debug');
  848. DataSource.setLoading(that, true);
  849. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  850. // User specified credit
  851. let credit = options.credit;
  852. if (typeof credit === "string") {
  853. credit = new Credit(credit);
  854. }
  855. that._credit = credit;
  856. let promise = data;
  857. let sourceUri = options.sourceUri;
  858. if (typeof data === "string" || data instanceof Resource) {
  859. data = Resource.createIfNeeded(data);
  860. promise = data.fetchJson();
  861. sourceUri = defaultValue(sourceUri, data.getUrlComponent());
  862. // Add resource credits to our list of credits to display
  863. const resourceCredits = that._resourceCredits;
  864. const credits = data.credits;
  865. if (defined(credits)) {
  866. const length = credits.length;
  867. for (let i = 0; i < length; i++) {
  868. resourceCredits.push(credits[i]);
  869. }
  870. }
  871. }
  872. options = {
  873. describe: defaultValue(options.describe, defaultDescribeProperty),
  874. markerSize: defaultValue(options.markerSize, defaultMarkerSize),
  875. markerSymbol: defaultValue(options.markerSymbol, defaultMarkerSymbol),
  876. markerColor: defaultValue(options.markerColor, defaultMarkerColor),
  877. strokeWidthProperty: new ConstantProperty(
  878. defaultValue(options.strokeWidth, defaultStrokeWidth)
  879. ),
  880. strokeMaterialProperty: new ColorMaterialProperty(
  881. defaultValue(options.stroke, defaultStroke)
  882. ),
  883. fillMaterialProperty: new ColorMaterialProperty(
  884. defaultValue(options.fill, defaultFill)
  885. ),
  886. clampToGround: defaultValue(options.clampToGround, defaultClampToGround),
  887. };
  888. return Promise.resolve(promise)
  889. .then(function (geoJson) {
  890. return load(that, geoJson, options, sourceUri, clear);
  891. })
  892. .catch(function (error) {
  893. DataSource.setLoading(that, false);
  894. that._error.raiseEvent(that, error);
  895. throw error;
  896. });
  897. }
  898. /**
  899. * Updates the data source to the provided time. This function is optional and
  900. * is not required to be implemented. It is provided for data sources which
  901. * retrieve data based on the current animation time or scene state.
  902. * If implemented, update will be called by {@link DataSourceDisplay} once a frame.
  903. *
  904. * @param {JulianDate} time The simulation time.
  905. * @returns {boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
  906. */
  907. GeoJsonDataSource.prototype.update = function (time) {
  908. return true;
  909. };
  910. function load(that, geoJson, options, sourceUri, clear) {
  911. let name;
  912. if (defined(sourceUri)) {
  913. name = getFilenameFromUri(sourceUri);
  914. }
  915. if (defined(name) && that._name !== name) {
  916. that._name = name;
  917. that._changed.raiseEvent(that);
  918. }
  919. const typeHandler = geoJsonObjectTypes[geoJson.type];
  920. if (!defined(typeHandler)) {
  921. throw new RuntimeError(`Unsupported GeoJSON object type: ${geoJson.type}`);
  922. }
  923. //Check for a Coordinate Reference System.
  924. const crs = geoJson.crs;
  925. let crsFunction = crs !== null ? defaultCrsFunction : null;
  926. if (defined(crs)) {
  927. if (!defined(crs.properties)) {
  928. throw new RuntimeError("crs.properties is undefined.");
  929. }
  930. const properties = crs.properties;
  931. if (crs.type === "name") {
  932. crsFunction = crsNames[properties.name];
  933. if (!defined(crsFunction)) {
  934. throw new RuntimeError(`Unknown crs name: ${properties.name}`);
  935. }
  936. } else if (crs.type === "link") {
  937. let handler = crsLinkHrefs[properties.href];
  938. if (!defined(handler)) {
  939. handler = crsLinkTypes[properties.type];
  940. }
  941. if (!defined(handler)) {
  942. throw new RuntimeError(
  943. `Unable to resolve crs link: ${JSON.stringify(properties)}`
  944. );
  945. }
  946. crsFunction = handler(properties);
  947. } else if (crs.type === "EPSG") {
  948. crsFunction = crsNames[`EPSG:${properties.code}`];
  949. if (!defined(crsFunction)) {
  950. throw new RuntimeError(`Unknown crs EPSG code: ${properties.code}`);
  951. }
  952. } else {
  953. throw new RuntimeError(`Unknown crs type: ${crs.type}`);
  954. }
  955. }
  956. return Promise.resolve(crsFunction).then(function (crsFunction) {
  957. if (clear) {
  958. that._entityCollection.removeAll();
  959. }
  960. // null is a valid value for the crs, but means the entire load process becomes a no-op
  961. // because we can't assume anything about the coordinates.
  962. if (crsFunction !== null) {
  963. typeHandler(that, geoJson, geoJson, crsFunction, options);
  964. }
  965. return Promise.all(that._promises).then(function () {
  966. that._promises.length = 0;
  967. DataSource.setLoading(that, false);
  968. return that;
  969. });
  970. });
  971. }
  972. /**
  973. * This callback is displayed as part of the GeoJsonDataSource class.
  974. * @callback GeoJsonDataSource.describe
  975. * @param {object} properties The properties of the feature.
  976. * @param {string} nameProperty The property key that Cesium estimates to have the name of the feature.
  977. */
  978. export default GeoJsonDataSource;