Пример #1
0
function startTweens(leaflet) {
  if (leaflet._tweensAreRunning) {
    return;
  }

  var feature = leaflet.terria.selectedFeature;
  if (defined(feature) && defined(feature.position)) {
    var cartographic = Ellipsoid.WGS84.cartesianToCartographic(
      feature.position.getValue(leaflet.terria.clock.currentTime),
      cartographicScratch
    );
    leaflet._selectionIndicator.setLatLng([
      CesiumMath.toDegrees(cartographic.latitude),
      CesiumMath.toDegrees(cartographic.longitude)
    ]);
  }

  if (leaflet._tweens.length > 0) {
    leaflet._tweens.update();
  }

  if (
    leaflet._tweens.length !== 0 ||
    (defined(feature) && defined(feature.position))
  ) {
    cesiumRequestAnimationFrame(startTweens.bind(undefined, leaflet));
  }
}
var rectangleToLatLngBounds = function(rectangle) {
    var west = CesiumMath.toDegrees(rectangle.west);
    var south = CesiumMath.toDegrees(rectangle.south);
    var east = CesiumMath.toDegrees(rectangle.east);
    var north = CesiumMath.toDegrees(rectangle.north);
    return L.latLngBounds([south, west], [north, east]);
};
Пример #3
0
    cartographicToFields(coordinates, errorBar) {
        const latitude = CesiumMath.toDegrees(coordinates.latitude);
        const longitude = CesiumMath.toDegrees(coordinates.longitude);

        const zone = 1 + Math.floor((longitude + 180) / 6);

        if (this.useProjection) {
            const projection = this.proj4Projection + ' +zone=' + zone +
                (latitude < 0 ? ' +south' : '');

            const projPoint = proj4((this.proj4longlat), (projection),
                [longitude, latitude]);


            this.utmZone = zone + (latitude < 0.0 ? 'S' : 'N');
            this.north = projPoint[1].toFixed(2) + this.projectionUnits;
            this.east = projPoint[0].toFixed(2) + this.projectionUnit;
        }

        this.latitude = Math.abs(latitude).toFixed(3) +
            '°' + (latitude < 0.0 ? 'S' : 'N');
        this.longitude = Math.abs(longitude).toFixed(3) +
            '°' + (longitude < 0.0 ? 'W' : 'E');

        if (defined(coordinates.height)) {
            this.elevation = Math.round(coordinates.height) + (defined(errorBar) ? '±' +
                Math.round(errorBar) : '') + 'm';
        } else {
            this.elevation = undefined;
        }
    }
Пример #4
0
PointParameter.prototype.formatValueAsString = function(value) {
    if (!defined(value)) {
        return '-';
    }

    return Math.abs(CesiumMath.toDegrees(value.latitude)) + '°' + (value.latitude < 0 ? 'S ' : 'N ') +
           Math.abs(CesiumMath.toDegrees(value.longitude)) + '°' + (value.longitude < 0 ? 'W' : 'E');
};
Пример #5
0
/**
 * Adds a bounding box filter to the search query for elastic search. This simply modifies requestData and returns nothing.
 *
 * @param {object} requestData Request data to modify
 * @param {Rectangle} rectangle rectangle to source the bounding box from.
 */
function addBoundingBox(requestData, rectangle) {
    requestData["box"] = {
        minLat: CesiumMath.toDegrees(rectangle.south),
        maxLon: CesiumMath.toDegrees(rectangle.east),
        maxLat: CesiumMath.toDegrees(rectangle.north),
        minLon: CesiumMath.toDegrees(rectangle.west)
    };
}
Пример #6
0
CatalogItem.defaultSerializers.rectangle = function(catalogItem, json, propertyName) {
    if (defined(catalogItem.rectangle)) {
        json.rectangle = [
            CesiumMath.toDegrees(catalogItem.rectangle.west),
            CesiumMath.toDegrees(catalogItem.rectangle.south),
            CesiumMath.toDegrees(catalogItem.rectangle.east),
            CesiumMath.toDegrees(catalogItem.rectangle.north)
        ];
    }
};
Пример #7
0
function hierarchyToLatLngs(hierarchy) {
    // This function currently does not handle polygons with holes.

    var positions = Array.isArray(hierarchy) ? hierarchy : hierarchy.positions;
    var carts = Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
    var latlngs = [];
    for (var i = 0; i < carts.length; ++i) {
        latlngs.push(L.latLng(CesiumMath.toDegrees(carts[i].latitude), CesiumMath.toDegrees(carts[i].longitude)));
    }

    return latlngs;
}
Пример #8
0
Leaflet.prototype.computePositionOnScreen = function(position, result) {
    var cartographic = Ellipsoid.WGS84.cartesianToCartographic(position, cartographicScratch);
    var point = this.map.latLngToContainerPoint(L.latLng(CesiumMath.toDegrees(cartographic.latitude), CesiumMath.toDegrees(cartographic.longitude)));

    if (defined(result)) {
        result.x = point.x;
        result.y = point.y;
    } else {
        result = new Cartesian2(point.x, point.y);
    }
    return result;
};
Пример #9
0
function selectFeature(leaflet) {
    var feature = leaflet.terria.selectedFeature;

    leaflet._highlightFeature(feature);

    if (defined(feature) && defined(feature.position)) {
        var cartographic = Ellipsoid.WGS84.cartesianToCartographic(feature.position.getValue(leaflet.terria.clock.currentTime), cartographicScratch);
        leaflet._selectionIndicator.setLatLng([CesiumMath.toDegrees(cartographic.latitude), CesiumMath.toDegrees(cartographic.longitude)]);
        animateSelectionIndicatorAppear(leaflet);
    } else {
        animateSelectionIndicatorDepart(leaflet);
    }
}
        functionParameterToInput: function(catalogFunction, parameter, value) {
            var bboxMinCoord1, bboxMinCoord2, bboxMaxCoord1, bboxMaxCoord2, urn;
            // We only support CRS84 and EPSG:4326
            if (parameter.crs.indexOf('crs84') !== -1) {
                // CRS84 uses long, lat rather that lat, long order.
                bboxMinCoord1 = CesiumMath.toDegrees(value.west);
                bboxMinCoord2 = CesiumMath.toDegrees(value.south);
                bboxMaxCoord1 = CesiumMath.toDegrees(value.east);
                bboxMaxCoord2 = CesiumMath.toDegrees(value.north);
                // Comfortingly known as WGS 84 longitude-latitude according to Table 3 in OGC 07-092r1.
                urn = 'urn:ogc:def:crs:OGC:1.3:CRS84';

            } else {
                // The URN value urn:ogc:def:crs:EPSG:6.6:4326 shall mean the Coordinate Reference System (CRS) with code
                // 4326 specified in version 6.6 of the EPSG database available at http://www.epsg.org/. That CRS specifies
                // the axis order as Latitude followed by Longitude.
                // We don't know about other URN versions, so are going to return 6.6 regardless of what was requested.
                bboxMinCoord1 = CesiumMath.toDegrees(value.south);
                bboxMinCoord2 = CesiumMath.toDegrees(value.west);
                bboxMaxCoord1 = CesiumMath.toDegrees(value.north);
                bboxMaxCoord2 = CesiumMath.toDegrees(value.east);
                urn = 'urn:ogc:def:crs:EPSG:6.6:4326';
            }

            return {
                       inputType: 'BoundingBoxData',
                       inputValue: bboxMinCoord1 + ',' + bboxMinCoord2 + ',' + bboxMaxCoord1 + ',' + bboxMaxCoord2 + ',' + urn
                   };
        }
Пример #11
0
SharePopupViewModel.prototype._addViewSettings = function(initSources) {
    var cameraExtent = this.terria.currentViewer.getCurrentExtent();

    // Add an init source with the camera position.
    var initialCamera = {
        west: CesiumMath.toDegrees(cameraExtent.west),
        south: CesiumMath.toDegrees(cameraExtent.south),
        east: CesiumMath.toDegrees(cameraExtent.east),
        north: CesiumMath.toDegrees(cameraExtent.north)
    };

    if (defined(this.terria.cesium)) {
        var cesiumCamera = this.terria.cesium.scene.camera;
        initialCamera.position = cesiumCamera.positionWC;
        initialCamera.direction = cesiumCamera.directionWC;
        initialCamera.up = cesiumCamera.upWC;
    }

    var homeCamera = {
        west: CesiumMath.toDegrees(this.terria.homeView.rectangle.west),
        south: CesiumMath.toDegrees(this.terria.homeView.rectangle.south),
        east: CesiumMath.toDegrees(this.terria.homeView.rectangle.east),
        north: CesiumMath.toDegrees(this.terria.homeView.rectangle.north),
        position: this.terria.homeView.position,
        direction: this.terria.homeView.direction,
        up: this.terria.homeView.up
    };

    initSources.push({
        initialCamera: initialCamera,
        homeCamera: homeCamera,
        baseMapName: this.terria.baseMap.name,
        viewerMode: this.terria.leaflet ? '2d': '3d'
    });
};
Пример #12
0
PointParameter.prototype.formatValueAsString = function(value) {
  value = defaultValue(value, this.value);
  if (!defined(value)) {
    return "-";
  }

  return (
    Math.abs(CesiumMath.toDegrees(value.latitude)) +
    "°" +
    (value.latitude < 0 ? "S " : "N ") +
    Math.abs(CesiumMath.toDegrees(value.longitude)) +
    "°" +
    (value.longitude < 0 ? "W" : "E")
  );
};
Пример #13
0
    cartographicToFields(coordinates, errorBar) {
        const latitude = CesiumMath.toDegrees(coordinates.latitude);
        const longitude = CesiumMath.toDegrees(coordinates.longitude);

        if (this.useProjection) {
            var prettyProjection = prettifyProjection(longitude, latitude, this.proj4Projection, this.proj4longlat, this.projectionUnits);
            this.utmZone = prettyProjection.utmZone;
            this.north = prettyProjection.north;
            this.east = prettyProjection.east;
        }

        var prettyCoordinate = prettifyCoordinates(longitude, latitude, {height: coordinates.height, errorBar: errorBar});
        this.latitude = prettyCoordinate.latitude;
        this.longitude = prettyCoordinate.longitude;
        this.elevation =  prettyCoordinate.elevation;
    }
Пример #14
0
PointParameter.prototype.getGeoJsonFeature = function(value) {
    value = defaultValue(value, this.value);
    if (!defined(value) || value === '') {
        return undefined;
    }

    var coordinates = [
        CesiumMath.toDegrees(value.longitude),
        CesiumMath.toDegrees(value.latitude),
    ];

    if (defined(value.height)) {
        coordinates.push(value.height);
    }

    return {
        'type': 'Feature',
            'geometry': {
                'type': 'Point',
                'coordinates': coordinates
                }
            };
};
Пример #15
0
PointParameter.formatValueForUrl = function(value) {
    const coordinates = [
        CesiumMath.toDegrees(value.longitude),
        CesiumMath.toDegrees(value.latitude),
    ];

    if (defined(value.height)) {
        coordinates.push(value.height);
    }

    return JSON.stringify({
        'type': 'FeatureCollection',
        'features': [
            {
                'type': 'Feature',
                'geometry': {
                    'type': 'Point',
                    'coordinates': coordinates
                }
            }
        ]
    });
};
Пример #16
0
PointParameter.prototype.getGeoJsonFeature = function(value) {
  value = defaultValue(value, this.value);
  if (!defined(value) || value === "") {
    return undefined;
  }

  var coordinates = [
    CesiumMath.toDegrees(value.longitude),
    CesiumMath.toDegrees(value.latitude)
  ];

  if (defined(value.height)) {
    coordinates.push(value.height);
  }

  return {
    type: "Feature",
    geometry: {
      type: "Point",
      coordinates: coordinates
    }
  };
};
Пример #17
0
SharePopupViewModel.prototype._addFeaturePicking = function(initSources) {
    if (defined(this.terria.pickedFeatures) && this.terria.pickedFeatures.features.length > 0) {
        var positionInRadians = Ellipsoid.WGS84.cartesianToCartographic(this.terria.pickedFeatures.pickPosition);

        var pickedFeatures = {
            providerCoords: this.terria.pickedFeatures.providerCoords,
            pickCoords: {
                lat: CesiumMath.toDegrees(positionInRadians.latitude),
                lng: CesiumMath.toDegrees(positionInRadians.longitude),
                height: positionInRadians.height
            }
        };

        if (defined(this.terria.selectedFeature)) {
            // Sometimes features have stable ids and sometimes they're randomly generated every time, so include both
            // id and name as a fallback.
            pickedFeatures.current = {
                name: this.terria.selectedFeature.name,
                hash: hashEntity(this.terria.selectedFeature, this.terria.clock)
            };
        }

        // Remember the ids of vector features only, the raster ones we can reconstruct from providerCoords.
        pickedFeatures.entities = this.terria.pickedFeatures.features.filter(function(feature) {
            return !defined(feature.imageryLayer);
        }).map(function(entity) {
            return {
                name: entity.name,
                hash: hashEntity(entity, this.terria.clock)
            };
        }.bind(this));

        initSources.push({
            pickedFeatures: pickedFeatures
        });
    }
};
BingMapsSearchProviderViewModel.prototype.search = function(searchText) {
  if (!defined(searchText) || /^\s*$/.test(searchText)) {
    this.isSearching = false;
    this.searchResults.removeAll();
    return;
  }

  this.isSearching = true;
  this.searchResults.removeAll();
  this.searchMessage = undefined;

  this.terria.analytics.logEvent("search", "bing", searchText);

  // If there is already a search in progress, cancel it.
  if (defined(this._geocodeInProgress)) {
    this._geocodeInProgress.cancel = true;
    this._geocodeInProgress = undefined;
  }

  var longitudeDegrees;
  var latitudeDegrees;

  if (defined(this.terria.cesium)) {
    var scene = this.terria.cesium.scene;
    var cameraPosition = scene.camera.positionWC;
    var cameraPositionCartographic = Ellipsoid.WGS84.cartesianToCartographic(
      cameraPosition
    );
    longitudeDegrees = CesiumMath.toDegrees(
      cameraPositionCartographic.longitude
    );
    latitudeDegrees = CesiumMath.toDegrees(cameraPositionCartographic.latitude);
  } else if (defined(this.terria.leaflet)) {
    var center = this.terria.leaflet.map.getCenter();
    longitudeDegrees = center.lng;
    latitudeDegrees = center.lat;
  }

  var promise = loadJsonp(
    new Resource({
      url:
        this.url +
        "REST/v1/Locations?culture=" +
        this.culture +
        "&userLocation=" +
        latitudeDegrees +
        "," +
        longitudeDegrees,
      queryParameters: {
        query: searchText,
        key: this.key
      }
    }),
    "jsonp"
  );

  var that = this;
  var geocodeInProgress = (this._geocodeInProgress = promise
    .then(function(result) {
      if (geocodeInProgress.cancel) {
        return;
      }
      that.isSearching = false;

      if (result.resourceSets.length === 0) {
        that.searchMessage = "Sorry, no locations match your search query.";
        return;
      }

      var resourceSet = result.resourceSets[0];
      if (resourceSet.resources.length === 0) {
        that.searchMessage = "Sorry, no locations match your search query.";
        return;
      }

      var primaryCountryLocations = [];
      var otherLocations = [];

      // Locations in the primary country go on top, locations elsewhere go undernearth and we add
      // the country name to them.
      for (var i = 0; i < resourceSet.resources.length; ++i) {
        var resource = resourceSet.resources[i];

        var name = resource.name;
        if (!defined(name)) {
          continue;
        }

        var list = primaryCountryLocations;
        var isImportant = true;

        var country = resource.address
          ? resource.address.countryRegion
          : undefined;
        if (defined(that.primaryCountry) && country !== that.primaryCountry) {
          // Add this location to the list of other locations.
          list = otherLocations;
          isImportant = false;

          // Add the country to the name, if it's not already there.
          if (
            defined(country) &&
            name.lastIndexOf(country) !== name.length - country.length
          ) {
            name += ", " + country;
          }
        }

        list.push(
          new SearchResultViewModel({
            name: name,
            isImportant: isImportant,
            clickAction: createZoomToFunction(that, resource),
            location: {
              latitude: resource.point.coordinates[0],
              longitude: resource.point.coordinates[1]
            }
          })
        );
      }

      that.searchResults.push.apply(
        that.searchResults,
        primaryCountryLocations
      );
      that.searchResults.push.apply(that.searchResults, otherLocations);

      if (that.searchResults.length === 0) {
        that.searchMessage = "Sorry, no locations match your search query.";
      }
    })
    .otherwise(function() {
      if (geocodeInProgress.cancel) {
        return;
      }

      that.isSearching = false;
      that.searchMessage =
        "An error occurred while searching.  Please check your internet connection or try again later.";
    }));

  return geocodeInProgress;
};
NominatimSearchProviderViewModel.prototype.search = function(searchText) {
  if (!defined(searchText) || /^\s*$/.test(searchText)) {
    this.isSearching = false;
    this.searchResults.removeAll();
    return;
  }

  this.isSearching = true;
  this.searchResults.removeAll();
  this.searchMessage = undefined;

  this.terria.analytics.logEvent("search", "nominatim", searchText);

  // If there is already a search in progress, cancel it.
  if (defined(this._geocodeInProgress)) {
    this._geocodeInProgress.cancel = true;
    this._geocodeInProgress = undefined;
  }

  var bboxStr = "";

  if (defined(this.terria.cesium)) {
    var viewer = this.terria.cesium.viewer;
    var posUL = viewer.camera.pickEllipsoid(
      new Cartesian2(0, 0),
      Ellipsoid.WGS84
    );
    var posLR = viewer.camera.pickEllipsoid(
      new Cartesian2(viewer.canvas.width, viewer.canvas.height),
      Ellipsoid.WGS84
    );
    if (defined(posUL) && defined(posLR)) {
      posUL = Ellipsoid.WGS84.cartesianToCartographic(posUL);
      posLR = Ellipsoid.WGS84.cartesianToCartographic(posLR);
      bboxStr =
        "&viewbox=" +
        CesiumMath.toDegrees(posUL.longitude) +
        "," +
        CesiumMath.toDegrees(posUL.latitude) +
        "," +
        CesiumMath.toDegrees(posLR.longitude) +
        "," +
        CesiumMath.toDegrees(posLR.latitude);
    } else {
      bboxStr = "";
    }
  } else if (defined(this.terria.leaflet)) {
    var bbox = this.terria.leaflet.map.getBounds();
    bboxStr =
      "&viewbox=" +
      bbox.getWest() +
      "," +
      bbox.getNorth() +
      "," +
      bbox.getEast() +
      "," +
      bbox.getSouth();
  }
  var promiseBounded = loadJson(
    this.url +
      "search?q=" +
      searchText +
      bboxStr +
      "&bounded=1&format=json" +
      this.countryCodes +
      "&limit=" +
      this.limitBounded
  );
  var promiseOthers = loadJson(
    this.url +
      "search?q=" +
      searchText +
      "&format=json" +
      this.countryCodes +
      "&limit=" +
      this.limitOthers
  );

  var that = this;
  var geocodeInProgress = (this._geocodeInProgress = {
    cancel: false
  });

  return when
    .all([promiseBounded, promiseOthers])
    .then(function(result) {
      if (geocodeInProgress.cancel) {
        return;
      }
      that.isSearching = false;

      if (result.length === 0) {
        return;
      }

      var locations = [];

      // Locations in the bounded query go on top, locations elsewhere go undernearth
      var findDbl = function(elts, id) {
        return elts.filter(function(elt) {
          return elt.id === id;
        })[0];
      };

      for (var i = 0; i < result.length; ++i) {
        for (var j = 0; j < result[i].length; ++j) {
          var resource = result[i][j];

          var name = resource.display_name;
          if (!defined(name)) {
            continue;
          }

          if (!findDbl(locations, resource.place_id)) {
            locations.push(
              new SearchResultViewModel({
                id: resource.place_id,
                name: name,
                isImportant: true,
                clickAction: createZoomToFunction(that, resource)
              })
            );
          }
        }
      }

      that.searchResults.push.apply(that.searchResults, locations);

      if (that.searchResults.length === 0) {
        that.searchMessage = "Sorry, no locations match your search query.";
      }
    })
    .otherwise(function() {
      if (geocodeInProgress.cancel) {
        return;
      }

      that.isSearching = false;
      that.searchMessage =
        "An error occurred while searching.  Please check your internet connection or try again later.";
    });
};
Пример #20
0
// WebCoverageServiceCaller.prototype.launch = function () {
function launch(wmsCatalogItem, bbox) {
  // // At the moment just grab the screen extent
  // // Calculate view extent in degrees
  // const bbox = wmsCatalogItem.terria.currentViewer.getCurrentExtent();

  bbox.west = CesiumMath.toDegrees(bbox.west);
  bbox.south = CesiumMath.toDegrees(bbox.south);
  bbox.east = CesiumMath.toDegrees(bbox.east);
  bbox.north = CesiumMath.toDegrees(bbox.north);

  const query = {
    service: "WCS",
    request: "GetCoverage",
    version: "1.0.0",
    format: "GeoTIFF",
    crs: "EPSG:4326",
    width: 1024,
    height: Math.round((1024 * bbox.height) / bbox.width),
    coverage: wmsCatalogItem.linkedWcsCoverage,
    bbox: `${bbox.west},${bbox.south},${bbox.east},${bbox.north}`
  };

  if (defined(wmsCatalogItem.discreteTime)) {
    query.time = wmsCatalogItem.discreteTime.toISOString();
  }

  const style = getStyle(wmsCatalogItem);
  if (defined(style)) {
    query.styles = style;
  }

  var uri = new URI(wmsCatalogItem.linkedWcsUrl).query(query);

  var url = proxyCatalogItemUrl(wmsCatalogItem, uri.toString(), "1d");

  var now = new Date();
  var timestamp = sprintf(
    "%04d-%02d-%02dT%02d:%02d:%02d",
    now.getFullYear(),
    now.getMonth() + 1,
    now.getDate(),
    now.getHours(),
    now.getMinutes(),
    now.getSeconds()
  );

  const asyncResult = new ResultPendingCatalogItem(wmsCatalogItem.terria);
  asyncResult.name = wmsCatalogItem.name + " " + timestamp;
  asyncResult.description =
    "This is the result of exporting data from " +
    wmsCatalogItem.name +
    " service at " +
    timestamp +
    " with the input parameters below.";

  const parametersForInfo = [
    { name: "Bounding box", value: query.bbox },
    { name: "Format", value: query.format }
  ];
  const inputsSection =
    '<table class="cesium-infoBox-defaultTable">' +
    parametersForInfo.reduce(function(previousValue, parameter) {
      return (
        previousValue +
        "<tr>" +
        '<td style="vertical-align: middle">' +
        parameter.name +
        "</td>" +
        "<td>" +
        parameter.value +
        "</td>" +
        "</tr>"
      );
    }, "") +
    "</table>";

  asyncResult.info.push({
    name: "Inputs",
    content: inputsSection
  });

  const promise = loadBlob(url)
    .then(blob => {
      if (blob.type.indexOf("xml") !== -1) {
        // Geoserver errors -_-
        wmsCatalogItem.terria.error.raiseEvent(
          new TerriaError({
            sender: wmsCatalogItem,
            title: "Data export failed",
            message: "The Web Coverage Service failed"
          })
        );
        // Could fetch error details from XML to show to user
        asyncResult.isEnabled = false;
        return;
      }

      FileSaver.saveAs(blob, `${wmsCatalogItem.name} clip.tiff`);

      asyncResult.isEnabled = false;
    })
    .otherwise(error => {
      wmsCatalogItem.terria.error.raiseEvent(
        new TerriaError({
          sender: wmsCatalogItem,
          title: "Data export failed",
          message: `The Web Coverage Service failed: ${error}`
        })
      );
      asyncResult.isEnabled = false;
    });

  asyncResult.loadPromise = promise;
  asyncResult.isEnabled = true;
}
Пример #21
0
function positionToLatLng(position) {
    var cartographic = Ellipsoid.WGS84.cartesianToCartographic(position, cartographicScratch);
    return L.latLng(CesiumMath.toDegrees(cartographic.latitude), CesiumMath.toDegrees(cartographic.longitude));
}
Пример #22
0
LeafletGeomVisualizer.prototype._updateLabel = function(entity, time, entityHash, entityDetails) {
    var labelGraphics = entity._label;
    var featureGroup = this._featureGroup;
    var position, marker;

    var details = entityDetails.label;
    if (!defined(details)) {
        details = entityDetails.label = {
            layer: undefined
        };
    }

    var geomLayer = details.layer;

    var show = entity.isAvailable(time) && Property.getValueOrDefault(labelGraphics._show, time, true);
    if (show) {
        position = Property.getValueOrUndefined(entity._position, time);
        show = defined(position);
    }
    if (!show) {
        cleanLabel(entity, featureGroup, entityDetails);
        return;
    }

    var cart = Ellipsoid.WGS84.cartesianToCartographic(position);
    var latlng = L.latLng( CesiumMath.toDegrees(cart.latitude), CesiumMath.toDegrees(cart.longitude) );
    var text = Property.getValueOrDefault(labelGraphics._text, time, undefined);
    var font = Property.getValueOrDefault(labelGraphics._font, time, undefined);
    var scale = Property.getValueOrDefault(labelGraphics._scale, time, 1.0);
    var fillColor = Property.getValueOrDefault(labelGraphics._fillColor, time, defaultColor);
    var verticalOrigin = Property.getValueOrDefault(labelGraphics._verticalOrigin, time, 0);
    var horizontalOrigin = Property.getValueOrDefault(labelGraphics._horizontalOrigin, time, 0);
    var pixelOffset = Property.getValueOrDefault(labelGraphics._pixelOffset, time, Cartesian2.ZERO);

    var iconOptions = {
        text: text,
        font: font,
        color: fillColor.toCssColorString(),
        scale: scale,
        horizontalOrigin: horizontalOrigin,  //value: left, center, right
        verticalOrigin: verticalOrigin      //value: bottom, center, top
    };

    var redrawLabel = false;
    if (!defined(geomLayer)) {
        var markerOptions = {icon: L.icon({iconUrl: tmpImage})};
        marker = L.marker(latlng, markerOptions);
        marker.on('click', featureClicked.bind(undefined, this, entity));
        marker.on('mousedown', featureMousedown.bind(undefined, this, entity));
        featureGroup.addLayer(marker);
        details.layer = marker;
        redrawLabel = true;
    } else {
        marker = geomLayer;
        if (!marker._latlng.equals(latlng)) {
            marker.setLatLng(latlng);
        }
        for (var prop in iconOptions) {
            if (iconOptions[prop] !== marker.options.icon.options[prop]) {
                redrawLabel = true;
                break;
            }
        }
    }

    if (redrawLabel) {
        var drawBillboard = function(image, dataurl) {
            iconOptions.iconUrl = dataurl || image;
            if (!defined(iconOptions.iconSize)) {
                iconOptions.iconSize = [image.width * scale, image.height * scale];
            }
            var w = iconOptions.iconSize[0], h = iconOptions.iconSize[1];
            var xOff = (w/2)*(1-horizontalOrigin) - pixelOffset.x;
            var yOff = (h/2)*(1+verticalOrigin) - pixelOffset.y;
            iconOptions.iconAnchor = [xOff, yOff];
            marker.setIcon(L.icon(iconOptions));
        };

        var canvas = writeTextToCanvas(text, {fillColor: fillColor, font: font});
        var imageUrl = canvas.toDataURL();

        var img = new Image();
        img.onload = function() {
            drawBillboard(img, imageUrl);
        };
        img.src = imageUrl;
    }
};
Пример #23
0
LeafletGeomVisualizer.prototype._updatePolyline = function(entity, time, entityHash, entityDetails) {
    var polylineGraphics = entity._polyline;
    var featureGroup = this._featureGroup;
    var positions, polyline;

    var details = entityDetails.polyline;
    if (!defined(details)) {
        details = entityDetails.polyline = {
            layer: undefined
        };
    }

    var geomLayer = details.layer;

    var show = entity.isAvailable(time) && Property.getValueOrDefault(polylineGraphics._show, time, true);
    if (show) {
        positions = Property.getValueOrUndefined(polylineGraphics._positions, time);
        show = defined(positions);
    }
    if (!show) {
        cleanPolyline(entity, featureGroup, entityDetails);
        return;
    }

    var carts = Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
    var latlngs = [];
    for (var p = 0; p < carts.length; p++) {
        latlngs.push(L.latLng( CesiumMath.toDegrees(carts[p].latitude), CesiumMath.toDegrees(carts[p].longitude)));
    }

    var color;
    var width;
    if (polylineGraphics._material instanceof PolylineGlowMaterialProperty) {
        color = defaultColor;
        width = defaultWidth;
    } else {
        color = Property.getValueOrDefault(polylineGraphics._material.color, time, defaultColor);
        width = Property.getValueOrDefault(polylineGraphics._width, time, defaultWidth);
    }

    var polylineOptions = {
        color: color.toCssColorString(),
        weight: width,
        opacity: color.alpha
    };

    if (!defined(geomLayer)) {
        if (latlngs.length > 0) {
            polyline = L.polyline(latlngs, polylineOptions);
            polyline.on('click', featureClicked.bind(undefined, this, entity));
            polyline.on('mousedown', featureMousedown.bind(undefined, this, entity));
            featureGroup.addLayer(polyline);
            details.layer = polyline;
        }
    } else {
        polyline = geomLayer;
        var curLatLngs = polyline.getLatLngs();
        var bPosChange = (latlngs.length !== curLatLngs.length);
        for (var i = 0; i < curLatLngs.length && !bPosChange; i++) {
            if (!curLatLngs[i].equals(latlngs[i])) {
                bPosChange = true;
            }
        }
        if (bPosChange) {
            polyline.setLatLngs(latlngs);
        }
        for (var prop in polylineOptions) {
            if (polylineOptions[prop] !== polyline.options[prop]) {
                polyline.setStyle(polylineOptions);
                break;
            }
        }
    }
};
var FeatureInfoPanelSectionViewModel = function(featureInfoPanelViewModel, feature, catalogItem) {
    this.terria = featureInfoPanelViewModel.terria;
    this.featureInfoPanelViewModel = featureInfoPanelViewModel;
    this._clockSubscription = undefined;
    this.feature = feature;
    this.template = undefined;
    this.partials = undefined;
    this.formats = undefined;
    this.name = undefined;

    var template = defined(catalogItem) ? catalogItem.featureInfoTemplate : undefined;
    var nameTemplate;
    if (defined(template)) {
        // template may be a string, eg. '<div>{{{Foo}}} Hello {{name}}</div>'.
        if (typeof template === 'string') {
            this.template = template;
        } else {
            // Or, template may be an object with 'name', 'template', 'formats', and/or 'partials' keys.
            // Eg. {name: '{{Bar}}', template: '<div>test {{>foobar}}</div>', partials: {foobar: '<b>{{Foo}}</b>'} }
            this.template = template.template;
            this.partials = template.partials;
            this.formats = template.formats;
            nameTemplate = template.name;
        }
    }

    var data = propertyValues(feature.properties, this.formats, this.terria.clock);

    if (defined(data)) {
        var position = this.terria.pickedFeatures && this.terria.pickedFeatures.pickPosition;

        if (defined(position)) {
            var latLngInRadians = Ellipsoid.WGS84.cartesianToCartographic(position);
            data.terria = {
                coords: {
                    latitude: CesiumMath.toDegrees(latLngInRadians.latitude),
                    longitude: CesiumMath.toDegrees(latLngInRadians.longitude)
                }
            };
        }
    }

    if (nameTemplate) {
        this.name = Mustache.render(nameTemplate, data);
    } else {
        this.name = feature.name ? feature.name : '';
    }

    this._updateContent(data);

    this.catalogItemName = defined(catalogItem) ? catalogItem.name : '';
    configureHtmlUpdater(this);

    this.svgArrowDown = svgArrowDown;
    this.svgArrowRight = svgArrowRight;
    this.svgDownload = svgDownload;

    /** Whether the raw data table should be shown */
    this.rawDataVisible = false; // raw data should be hidden on init unless there's no template

    /** What links are available for data download. Generally JSON and CSV are available, but only JSON is available
     * if the data can't be represented as a CSV. */
    if (defined(data) && Object.keys(data).length) {
        delete data.terria; // don't want this wrecking the CSV

        this.dataDownloads = [
            {
                href: makeDataUri('csv', generateCsvData(data)),
                ext: 'csv',
                name: 'CSV'
            },
            {
                href: makeDataUri('json', JSON.stringify(data)),
                ext: 'json',
                name: 'JSON'
            }
        ].filter(function(download) {
            return defined(download.href);
        });
    } else {
        this.dataDownloads = [];
    }

    /** Whether other download options (the dropdown below the first option) should be visible */
    this.downloadOptionsVisible = false;
    /** The position of the download options dropdown - as this needs to cover the edge of a potentially scrolling modal,
     * it is set to position: fixed and its position is changed to match that of its parent whenever it's opened.
     */
    this.downloadDropdownPosition = undefined;
    this._resetDownloadDropdownPosition();

    /** {@see CAN_USE_DATA_URI_IN_HREF} - made settable for testing */
    this.canUseDataUriInHref = CAN_USE_DATA_URI_IN_HREF;

    knockout.track(this, ['name', 'templatedInfo', 'rawData', 'catalogItemName', 'rawDataVisible', 'downloadOptionsVisible', 'downloadDropdownPosition']);

    // Use a white background when displaying complete HTML documents rather than just snippets.
    knockout.defineProperty(this, 'useWhiteBackground', {
        get: function() {
            return htmlTagRegex.test(this.rawData);
        }
    });
};
Пример #25
0
      compare: function(actual, expected) {
        var result = {};
        result.pass = true;
        result.message = "";

        if (!defined(actual.orientation)) {
          result.pass = false;
          result.message += "Expected " + actual + " to contain .orientation. ";
        }
        if (!defined(expected.orientation)) {
          result.pass = false;
          result.message +=
            "Expected " + expected + " to contain .orientation. ";
        }

        if (result.pass) {
          if (!defined(actual.orientation.roll)) {
            result.pass = false;
            result.message +=
              "Expected " + actual + " to contain .orientation.roll. ";
          }
          if (!defined(actual.orientation.pitch)) {
            result.pass = false;
            result.message +=
              "Expected " + actual + " to contain .orientation.pitch. ";
          }
          if (!defined(actual.orientation.heading)) {
            result.pass = false;
            result.message +=
              "Expected " + actual + " to contain .orientation.heading. ";
          }

          if (!defined(expected.orientation.roll)) {
            result.pass = false;
            result.message +=
              "Expected " + expected + " to contain .orientation.roll. ";
          }
          if (!defined(expected.orientation.pitch)) {
            result.pass = false;
            result.message +=
              "Expected " + expected + " to contain .orientation.pitch. ";
          }
          if (!defined(expected.orientation.heading)) {
            result.pass = false;
            result.message +=
              "Expected " + expected + " to contain .orientation.heading. ";
          }
        }

        if (result.pass) {
          for (let i = 0; i < 3; i++) {
            let expectedValue;
            let actualValue;

            switch (i) {
              case 0:
                expectedValue = expected.orientation.roll;
                actualValue = actual.orientation.roll;
                break;
              case 1:
                expectedValue = expected.orientation.pitch;
                actualValue = actual.orientation.pitch;
                break;
              case 2:
                expectedValue = expected.orientation.heading;
                actualValue = actual.orientation.heading;
                break;
            }

            if (!similarRadians(actualValue, expectedValue, 0.001)) {
              result.pass = false;
              const difference = CesiumMath.negativePiToPi(
                expectedValue - actualValue
              );
              result.message +=
                "Expected roll value " +
                actualValue +
                " to be " +
                expectedValue +
                " (difference was " +
                difference +
                " radians, " +
                CesiumMath.toDegrees(difference) +
                " degrees). ";
            }
          }
        }

        return result;
      }
Пример #26
0
function formatAsLatitudeCommaLongitude(value) {
  const longitude = CesiumMath.toDegrees(value.longitude);
  const latitude = CesiumMath.toDegrees(value.latitude);
  return `${latitude},${longitude}`;
}