function getRectangleFromLayer(layer) {
    var egbb = layer.EX_GeographicBoundingBox; // required in WMS 1.3.0
    if (defined(egbb)) {
        return Rectangle.fromDegrees(egbb.westBoundLongitude, egbb.southBoundLatitude, egbb.eastBoundLongitude, egbb.northBoundLatitude);
    } else {
        var llbb = layer.LatLonBoundingBox; // required in WMS 1.0.0 through 1.1.1
        if (defined(llbb)) {
            return Rectangle.fromDegrees(llbb.minx, llbb.miny, llbb.maxx, llbb.maxy);
        }
    }
    return undefined;
}
Beispiel #2
0
CatalogItem.defaultUpdaters.rectangle = function(catalogItem, json, propertyName) {
    if (defined(json.rectangle)) {
        catalogItem.rectangle = Rectangle.fromDegrees(json.rectangle[0], json.rectangle[1], json.rectangle[2], json.rectangle[3]);
    } else {
        catalogItem.rectangle = Rectangle.MAX_VALUE;
    }
};
function getRectangleFromLayer(thisLayerJson) {
  var extent = thisLayerJson.extent;
  if (
    defined(extent) &&
    extent.spatialReference &&
    extent.spatialReference.wkid
  ) {
    var wkid = "EPSG:" + extent.spatialReference.wkid;
    if (!defined(proj4definitions[wkid])) {
      return undefined;
    }

    var source = new proj4.Proj(proj4definitions[wkid]);
    var dest = new proj4.Proj("EPSG:4326");

    var p = proj4(source, dest, [extent.xmin, extent.ymin]);

    var west = p[0];
    var south = p[1];

    p = proj4(source, dest, [extent.xmax, extent.ymax]);

    var east = p[0];
    var north = p[1];

    return Rectangle.fromDegrees(west, south, east, north);
  }

  return undefined;
}
Beispiel #4
0
        it('can deserialize rectangle plus position/direction/up', function() {
            var view = CameraView.fromJson({
                west: 45,
                south: -20,
                east: 55,
                north: -10,
                position: {
                    x: 10000000,
                    y: 10.0,
                    z: 20.0
                },
                direction: {
                    x: -1.0,
                    y: 0.1,
                    z: 0.2
                },
                up: {
                    x: 0.0,
                    y: 1.0,
                    z: 0.1
                }
            });

            expect(view.rectangle).toEqual(Rectangle.fromDegrees(45, -20, 55, -10));
            expect(view.position).toEqual(new Cartesian3(10000000, 10, 20));
            expect(view.direction).toEqual(new Cartesian3(-1.0, 0.1, 0.2));
            expect(view.up).toEqual(new Cartesian3(0.0, 1.0, 0.1));
        });
Beispiel #5
0
Leaflet.prototype.getCurrentExtent = function() {
  var bounds = this.map.getBounds();
  return Rectangle.fromDegrees(
    bounds.getWest(),
    bounds.getSouth(),
    bounds.getEast(),
    bounds.getNorth()
  );
};
    it('can be round-tripped with serializeToJson and updateFromJson', function() {
        wmsItem.name = 'Name';
        wmsItem.id = 'Id';
        // wmsItem.description = 'Description';
        wmsItem.rectangle = Rectangle.fromDegrees(-10, 10, -20, 20);
        wmsItem.legendUrl = new LegendUrl('http://legend.com', 'image/png');
        wmsItem.dataUrlType = 'wfs';
        wmsItem.dataUrl = 'http://my.wfs.com/wfs';
        wmsItem.dataCustodian = 'Data Custodian';
        wmsItem.metadataUrl = 'http://my.metadata.com';
        wmsItem.url = 'http://my.wms.com';
        wmsItem.layers = 'mylayer';
        wmsItem.parameters = {
            custom: true,
            awesome: 'maybe'
        };
        wmsItem.getFeatureInfoFormats = [];
        wmsItem.intervals = new TimeIntervalCollection([
            new TimeInterval({
                start: JulianDate.fromIso8601('2013-08-01T15:00:00Z'),
                stop: JulianDate.fromIso8601('2013-08-01T18:00:00Z')
            }),
            new TimeInterval({
                start: JulianDate.fromIso8601('2013-09-01T11:00:00Z'),
                stop: JulianDate.fromIso8601('2013-09-03T13:00:00Z')
            })
        ]);
        // This initialTime is before any interval, so internally it will be changed to the first start date.
        wmsItem.initialTimeSource = '2012-01-01T12:00:00Z';

        var json = wmsItem.serializeToJson();

        var reconstructed = new WebMapServiceCatalogItem(terria);
        reconstructed.updateFromJson(json);

        // We'll check for these later in toEqual but this makes it a bit easier to see what's different.
        expect(reconstructed.name).toBe(wmsItem.name);
        // We do not serialize the description, to keep the serialization shorter.
        // expect(reconstructed.description).toBe(wmsItem.description);
        expect(reconstructed.rectangle).toEqual(wmsItem.rectangle);
        expect(reconstructed.legendUrl).toEqual(wmsItem.legendUrl);
        expect(reconstructed.legendUrls).toEqual(wmsItem.legendUrls);
        expect(reconstructed.dataUrlType).toBe(wmsItem.dataUrlType);
        expect(reconstructed.dataUrl).toBe(wmsItem.dataUrl);
        expect(reconstructed.dataCustodian).toBe(wmsItem.dataCustodian);
        expect(reconstructed.metadataUrl).toBe(wmsItem.metadataUrl);
        expect(reconstructed.url).toBe(wmsItem.url);
        expect(reconstructed.layers).toBe(wmsItem.layers);
        expect(reconstructed.parameters).toBe(wmsItem.parameters);
        expect(reconstructed.getFeatureInfoFormats).toEqual(wmsItem.getFeatureInfoFormats);
        // Do not compare time, because on some systems the second could have ticked over between getting the two times.
        var initialTimeSource = reconstructed.initialTimeSource.substr(0, 10);
        expect(initialTimeSource).toEqual('2013-08-01');
        // We do not serialize the intervals, to keep the serialization shorter.
        // expect(reconstructed.intervals.length).toEqual(wmsItem.intervals.length);
    });
Beispiel #7
0
        it('can deserialize rectangle alone', function() {
            var view = CameraView.fromJson({
                west: 45,
                south: -20,
                east: 55,
                north: -10
            });

            expect(view.rectangle).toEqual(Rectangle.fromDegrees(45, -20, 55, -10));
        });
Beispiel #8
0
function getGeoJsonExtent(geoJson) {
    var testGeometry = geoJson;
    if(defined(geoJson.type) && geoJson.type === 'Topology') {
        testGeometry = topoJsonToFeaturesArray(geoJson);
    }

    var ext = {west:180, east:-180, south:90, north: -90};
    filterValue(testGeometry, 'coordinates', function(obj, prop) { getExtent(obj[prop], ext); });
    return Rectangle.fromDegrees(ext.west, ext.south, ext.east, ext.north);
}
Beispiel #9
0
CameraView.fromJson = function(json) {
  if (defined(json.lookAt)) {
    var targetPosition = Cartographic.fromDegrees(
      json.lookAt.targetLongitude,
      json.lookAt.targetLatitude,
      json.lookAt.targetHeight
    );
    var headingPitchRange = new HeadingPitchRange(
      CesiumMath.toRadians(json.lookAt.heading),
      CesiumMath.toRadians(json.lookAt.pitch),
      json.lookAt.range
    );
    return CameraView.fromLookAt(targetPosition, headingPitchRange);
  } else if (defined(json.positionHeadingPitchRoll)) {
    var cameraPosition = Cartographic.fromDegrees(
      json.positionHeadingPitchRoll.cameraLongitude,
      json.positionHeadingPitchRoll.cameraLatitude,
      json.positionHeadingPitchRoll.cameraHeight
    );
    return CameraView.fromPositionHeadingPitchRoll(
      cameraPosition,
      CesiumMath.toRadians(json.positionHeadingPitchRoll.heading),
      CesiumMath.toRadians(json.positionHeadingPitchRoll.pitch),
      CesiumMath.toRadians(json.positionHeadingPitchRoll.roll)
    );
  } else if (
    defined(json.position) &&
    defined(json.direction) &&
    defined(json.up)
  ) {
    return new CameraView(
      Rectangle.fromDegrees(json.west, json.south, json.east, json.north),
      new Cartesian3(json.position.x, json.position.y, json.position.z),
      new Cartesian3(json.direction.x, json.direction.y, json.direction.z),
      new Cartesian3(json.up.x, json.up.y, json.up.z)
    );
  } else {
    return new CameraView(
      Rectangle.fromDegrees(json.west, json.south, json.east, json.north)
    );
  }
};
// Set the features (entities) on this data source, using tableColumn to provide values and tableStyle + legendHelper.tableColumnStyle for styling.
// Set the extent based on those entities.
function updateEntitiesAndExtent(dataSource) {
    var tableStructure = dataSource._tableStructure;
    var legendHelper = dataSource._legendHelper;
    var tableColumn = legendHelper.tableColumn;
    var tableStyle = legendHelper.tableStyle;
    var tableColumnStyle = legendHelper.tableColumnStyle;
    var longitudeColumn = tableStructure.columnsByType[VarType.LON][0];
    var latitudeColumn = tableStructure.columnsByType[VarType.LAT][0];
    if (defined(longitudeColumn) && defined(latitudeColumn)) {
        // remove existing entities first
        dataSource._entityCollection.removeAll();

        var heightColumn = tableStructure.columnsByType[VarType.ALT][0];
        var timeColumn = tableStructure.activeTimeColumn;

        var rowObjects = tableStructure.toRowObjects();
        var fallbackNameField = chooseFallbackNameField(tableStructure.getColumnNames());
        var rowDescriptions = tableStructure.toRowDescriptions(tableStyle && tableStyle.featureInfoFields);

        for (var i = 0; i < rowObjects.length; i++) {
            if (!definedNotNull(latitudeColumn.values[i]) || !definedNotNull(longitudeColumn.values[i])) {
                console.log('Missing lat/lon on row ' + i);
                continue;
            }
            var rowObject = rowObjects[i];
            var objectId = createGuid();
            var entity = new Entity({
                id: objectId,
                name: rowObject.title || rowObject[fallbackNameField] || defaultEntityName
            });
            entity.description = rowDescriptions[i];
            entity.position = Cartesian3.fromDegrees(
                longitudeColumn.values[i],
                latitudeColumn.values[i],
                defined(heightColumn) ? heightColumn.values[i] : undefined
            );
            setEntityProperties(entity, rowObject);

            var value = defined(tableColumn) ? tableColumn.indicesOrValues[i] : undefined;
            var color = legendHelper.getColorFromValue(value);
            var scale = legendHelper.getScaleFromValue(value);
            entity.availability = timeColumn && timeColumn.availabilities && timeColumn.availabilities[i];
            var show = calculateShow(entity.availability);
            addPointToEntity(entity, tableColumnStyle, scale, color, show);
            dataSource._entityCollection.add(entity);
        }

        dataSource._extent = Rectangle.fromDegrees(
            longitudeColumn.minimumValue, latitudeColumn.minimumValue, longitudeColumn.maximumValue, latitudeColumn.maximumValue
        );
    }
}
 it('can update from json', function() {
     item.updateFromJson({
         name: 'Name',
         description: 'Description',
         rectangle: [-10, 10, -20, 20],
         url: 'http://foo.bar'
     });
     expect(item.name).toBe('Name');
     expect(item.description).toBe('Description');
     expect(item.rectangle).toEqual(Rectangle.fromDegrees(-10, 10, -20, 20));
     expect(item.type).toBe('sos');
     expect(item.url.indexOf('http://foo.bar')).toBe(0);
 });
function createZoomToFunction(viewModel, resource) {
  var bbox = resource.bbox;
  var south = bbox[0];
  var west = bbox[1];
  var north = bbox[2];
  var east = bbox[3];

  var rectangle = Rectangle.fromDegrees(west, south, east, north);

  return function() {
    var terria = viewModel.terria;
    terria.currentViewer.zoomTo(rectangle, viewModel.flightDurationSeconds);
  };
}
 it("can update from json", function() {
   item.updateFromJson({
     name: "Name",
     description: "Description",
     rectangle: [-10, 10, -20, 20],
     url: "http://foo.bar",
     datasetId: "foo"
   });
   expect(item.name).toBe("Name");
   expect(item.description).toBe("Description");
   expect(item.rectangle).toEqual(Rectangle.fromDegrees(-10, 10, -20, 20));
   expect(item.type).toBe("abs-itt");
   expect(item.url.indexOf("http://foo.bar")).toBe(0);
   expect(item.datasetId).toBe("foo");
 });
function getRectangleFromLayer(thisLayerJson) {
    var extent = thisLayerJson.extent;
    if (defined(extent) && extent.spatialReference && extent.spatialReference.wkid) {
        var wkid = extent.spatialReference.wkid;
        if (wkid === 4326 || wkid === 4283) {
            return Rectangle.fromDegrees(extent.xmin, extent.ymin, extent.xmax, extent.ymax);
        } else if (wkid === 3857 || wkid === 900913 || wkid === 102100 || wkid === 102113) {
            var projection = new WebMercatorProjection();
            var sw = projection.unproject(new Cartesian3(Math.max(extent.xmin, -Ellipsoid.WGS84.maximumRadius * Math.PI), Math.max(extent.ymin, -Ellipsoid.WGS84.maximumRadius * Math.PI), 0.0));
            var ne = projection.unproject(new Cartesian3(Math.min(extent.xmax, Ellipsoid.WGS84.maximumRadius * Math.PI), Math.min(extent.ymax, Ellipsoid.WGS84.maximumRadius * Math.PI), 0.0));
            return new Rectangle(Math.max(sw.longitude, -Math.PI), Math.max(sw.latitude, -WebMercatorProjection.MaximumLatitude), Math.min(ne.longitude, Math.PI), Math.min(ne.latitude, WebMercatorProjection.MaximumLatitude));
        }
    }

    return undefined;
}
function createZoomToFunction(viewModel, resource) {
    // Server does not return information of a bounding box, just a location.
    // bboxSize is used to expand a point
    var bboxSize = 0.2;
    var locLat = resource.location.split(',')[0];
    var locLng = resource.location.split(',')[1];
    var south = parseFloat(locLat) + bboxSize / 2;
    var west = parseFloat(locLng) - bboxSize / 2;
    var north = parseFloat(locLat) - bboxSize / 2;
    var east = parseFloat(locLng) + bboxSize / 2;
    var rectangle = Rectangle.fromDegrees(west, south, east, north);

    return function() {
        var terria = viewModel.terria;
        terria.currentViewer.zoomTo(rectangle, viewModel.flightDurationSeconds);
    };
}
function createDataSource(mapServiceGroup, layer, dataCustodian) {
    var result = new ArcGisMapServerCatalogItem(mapServiceGroup.terria);

    result.name = layer.name;
    result.description = defined(layer.description) && layer.description.length > 0 ? layer.description : mapServiceGroup.description;
    result.dataCustodian = dataCustodian;
    result.url = mapServiceGroup.url;
    result.dataUrl = mapServiceGroup.url;
    result.dataUrlType = 'direct';
    result.layers = layer.id.toString();
    result.maximumScale = layer.maxScale;

    result.description = '';

    var groupHasDescription = defined(mapServiceGroup.description) && mapServiceGroup.description.length > 0;
    var layerHasDescription = defined(layer.description) && layer.description.length > 0;

    if (groupHasDescription) {
        result.description += mapServiceGroup.description;
    }

    if (groupHasDescription && layerHasDescription) {
        result.description += '<br/>';
    }

    if (layerHasDescription) {
        result.description += layer.description;
    }

    var extent = layer.extent;
    if (defined(extent) && extent.spatialReference && extent.spatialReference.wkid) {
        var wkid = extent.spatialReference.wkid;
        if (wkid === 4326 || wkid === 4283) {
            result.rectangle = Rectangle.fromDegrees(extent.xmin, extent.ymin, extent.xmax, extent.ymax);
        } else if (wkid === 3857 || wkid === 900913 || wkid === 102100) {
            var projection = new WebMercatorProjection();
            var sw = projection.unproject(new Cartesian3(extent.xmin, extent.ymin, 0.0));
            var ne = projection.unproject(new Cartesian3(extent.xmax, extent.ymax, 0.0));
            result.rectangle = new Rectangle(sw.longitude, sw.latitude, ne.longitude, ne.latitude);
        }
    }

    return result;
}
function wgs84BoundingBoxToRectangle(boundingBox) {
    if (!defined(boundingBox)) {
        return Rectangle.MAX_VALUE;
    }

    var lowerCorner = boundingBox.LowerCorner;
    var upperCorner = boundingBox.UpperCorner;
    if (!defined(lowerCorner) || !defined(upperCorner)) {
        return Rectangle.MAX_VALUE;
    }

    var lowerCoordinates = lowerCorner.split(' ');
    var upperCoordinates = upperCorner.split(' ');
    if (lowerCoordinates.length !== 2 || upperCoordinates.length !== 2) {
        return Rectangle.MAX_VALUE;
    }

    return Rectangle.fromDegrees(lowerCoordinates[0], lowerCoordinates[1], upperCoordinates[0], upperCoordinates[1]);
}
function getRectangleFromLayer(layer) {
    // Unfortunately, WMTS 1.0 doesn't require WGS84BoundingBox (or any bounding box) to be specified.
    var bbox = layer.WGS84BoundingBox;
    if (!defined(bbox)) {
        return undefined;
    }

    var ll = bbox.LowerCorner;
    var ur = bbox.UpperCorner;

    if (!defined(ll) || !defined(ur)) {
        return undefined;
    }

    var llParts = ll.split(' ');
    var urParts = ur.split(' ');
    if (llParts.length !== 2 || urParts.length !== 2) {
        return undefined;
    }

    return Rectangle.fromDegrees(llParts[0], llParts[1], urParts[0], urParts[1]);
}
    it('can be round-tripped with serializeToJson and updateFromJson', function() {
        wmsItem.name = 'Name';
        wmsItem.id = 'Id';
        wmsItem.description = 'Description';
        wmsItem.rectangle = Rectangle.fromDegrees(-10, 10, -20, 20);
        wmsItem.legendUrl = new LegendUrl('http://legend.com', 'image/png');
        wmsItem.dataUrlType = 'wfs';
        wmsItem.dataUrl = 'http://my.wfs.com/wfs';
        wmsItem.dataCustodian = 'Data Custodian';
        wmsItem.metadataUrl = 'http://my.metadata.com';
        wmsItem.url = 'http://my.wms.com';
        wmsItem.layers = 'mylayer';
        wmsItem.parameters = {
            custom: true,
            awesome: 'maybe'
        };
        wmsItem.getFeatureInfoFormats = [];

        var json = wmsItem.serializeToJson();

        var reconstructed = new WebMapServiceCatalogItem(terria);
        reconstructed.updateFromJson(json);

        // We'll check for these later in toEqual but this makes it a bit easier to see what's different.
        expect(reconstructed.name).toBe(wmsItem.name);
        expect(reconstructed.description).toBe(wmsItem.description);
        expect(reconstructed.rectangle).toEqual(wmsItem.rectangle);
        expect(reconstructed.legendUrl).toEqual(wmsItem.legendUrl);
        expect(reconstructed.legendUrls).toEqual(wmsItem.legendUrls);
        expect(reconstructed.dataUrlType).toBe(wmsItem.dataUrlType);
        expect(reconstructed.dataUrl).toBe(wmsItem.dataUrl);
        expect(reconstructed.dataCustodian).toBe(wmsItem.dataCustodian);
        expect(reconstructed.metadataUrl).toBe(wmsItem.metadataUrl);
        expect(reconstructed.url).toBe(wmsItem.url);
        expect(reconstructed.layers).toBe(wmsItem.layers);
        expect(reconstructed.parameters).toBe(wmsItem.parameters);
        expect(reconstructed.getFeatureInfoFormats).toEqual(wmsItem.getFeatureInfoFormats);
    });
    it('can update from json', function() {
        wmsItem.updateFromJson({
            name: 'Name',
            description: 'Description',
            rectangle: [-10, 10, -20, 20],
            legendUrl: 'http://legend.com',
            dataUrlType: 'wfs',
            dataUrl: 'http://my.wfs.com/wfs',
            dataCustodian: 'Data Custodian',
            getCapabilitiesUrl: 'http://my.metadata.com',
            url: 'http://my.wms.com',
            layers: 'mylayer',
            parameters: {
                custom: true,
                awesome: 'maybe'
            },
            tilingScheme: new WebMercatorTilingScheme(),
            getFeatureInfoFormats: []
        });

        expect(wmsItem.name).toBe('Name');
        expect(wmsItem.description).toBe('Description');
        expect(wmsItem.rectangle).toEqual(Rectangle.fromDegrees(-10, 10, -20, 20));
        expect(wmsItem.legendUrl).toEqual(new LegendUrl('http://legend.com'));
        expect(wmsItem.dataUrlType).toBe('wfs');
        expect(wmsItem.dataUrl.indexOf('http://my.wfs.com/wfs')).toBe(0);
        expect(wmsItem.dataCustodian).toBe('Data Custodian');
        expect(wmsItem.getCapabilitiesUrl).toBe('http://my.metadata.com');
        expect(wmsItem.url).toBe('http://my.wms.com');
        expect(wmsItem.layers).toBe('mylayer');
        expect(wmsItem.parameters).toEqual({
            custom: true,
            awesome: 'maybe'
        });
        expect(wmsItem.tilingScheme instanceof WebMercatorTilingScheme).toBe(true);
        expect(wmsItem.getFeatureInfoFormats).toEqual([]);
    });
Beispiel #21
0
 map.on("dragboxend", function(e) {
   var mapInteractionModeStack = that.terria.mapInteractionModeStack;
   if (
     defined(mapInteractionModeStack) &&
     mapInteractionModeStack.length > 0
   ) {
     if (
       mapInteractionModeStack[mapInteractionModeStack.length - 1]
         .drawRectangle &&
       defined(e.dragBoxBounds)
     ) {
       var b = e.dragBoxBounds;
       mapInteractionModeStack[
         mapInteractionModeStack.length - 1
       ].pickedFeatures = Rectangle.fromDegrees(
         b.getWest(),
         b.getSouth(),
         b.getEast(),
         b.getNorth()
       );
     }
   }
   that._dragboxcompleted = true;
 });
// Set the features (entities) on this data source, using tableColumn to provide values and tableStyle + legendHelper.tableColumnStyle for styling.
// Set the extent based on those entities.
function updateEntitiesAndExtent(dataSource) {
    var tableStructure = dataSource._tableStructure;
    var legendHelper = dataSource._legendHelper;
    var tableStyle = legendHelper.tableStyle;
    var specialColumns = {
        longitude: tableStructure.columnsByType[VarType.LON][0],
        latitude: tableStructure.columnsByType[VarType.LAT][0],
        height: tableStructure.columnsByType[VarType.ALT][0],
        time: tableStructure.activeTimeColumn,
        value: legendHelper.tableColumn
    };
    if (defined(specialColumns.longitude) && defined(specialColumns.latitude)) {
        var rowObjects = tableStructure.toStringAndNumberRowObjects();
        var rowDescriptions = tableStructure.toRowDescriptions(tableStyle && tableStyle.featureInfoFields);
        dataSource._rowObjects = rowObjects;
        dataSource._rowDescriptions = rowDescriptions;
        var entities = dataSource._entityCollection;
        entities.suspendEvents();
        if (defined(specialColumns.time) && defined(tableStructure.idColumnNames)
                && tableStructure.idColumnNames.length > 0) {
            setOneFeaturePerId(dataSource, tableStructure, specialColumns);
            dataSource._hasFeaturePerRow = false;
        } else {
            setOneFeaturePerRow(dataSource, tableStructure, specialColumns);
            dataSource._hasFeaturePerRow = true;
        }
        entities.resumeEvents();

        dataSource._extent = Rectangle.fromDegrees(
            specialColumns.longitude.minimumValue,
            specialColumns.latitude.minimumValue,
            specialColumns.longitude.maximumValue,
            specialColumns.latitude.maximumValue
        );
    }
}
CkanCatalogItem.createCatalogItemFromResource = function(options) {
    if (defined(options.allowGroups)) {
        deprecationWarning('allowGroups', 'allowGroups is deprecated. Please use allowWmsGroups and/or allowWfsGroups instead.');
    }
    var resource = options.resource;
    var itemData = options.itemData;
    var extras = options.extras;
    var parent = options.parent;

    if (resource.__filtered) {
        return;
    }

    if (!defined(extras)) {
        extras = {};
        if (defined(itemData.extras)) {
            for (var idx = 0; idx < itemData.extras.length; idx++) {
                extras[itemData.extras[idx].key] = itemData.extras[idx].value;
            }
        }
    }

    var formats = [
        // Format Regex, Catalog Item, (optional) URL regex
        [options.wmsResourceFormat, WebMapServiceCatalogItem],
        [options.wfsResourceFormat, WebFeatureServiceCatalogItem],
        [options.esriMapServerResourceFormat, ArcGisMapServerCatalogItem, /MapServer/],
        [options.esriFeatureServerResourceFormat, ArcGisFeatureServerCatalogItem, /FeatureServer/],
        [options.kmlResourceFormat, KmlCatalogItem],
        [options.geoJsonResourceFormat, GeoJsonCatalogItem],
        [options.czmlResourceFormat, CzmlCatalogItem],
        [options.csvResourceFormat, CsvCatalogItem]
    ].filter(function(format) {
        return defined(format[0]);
    });

    var baseUrl = resource.wms_url;
    if (!defined(baseUrl)) {
        baseUrl = resource.url;
        if (!defined(baseUrl)) {
            return undefined;
        }
    }

    var matchingFormats = formats.filter(function(format) {
        // Matching formats must match the format regex,
        // and also the URL regex if it exists.
        return resource.format.match(format[0]) &&
               (!defined(format[2]) || baseUrl.match(format[2]));
    });
    if (matchingFormats.length === 0) {
        return undefined;
    }

    var isWms = matchingFormats[0][1] === WebMapServiceCatalogItem;
    var isWfs = matchingFormats[0][1] === WebFeatureServiceCatalogItem;

    // Extract the layer name from the URL.
    var uri = new URI(baseUrl);
    var params = uri.search(true);

    // Remove the query portion of the WMS URL.
    var url = baseUrl;

    var newItem;
    if (isWms || isWfs) {
        var layerName = resource.wms_layer || params.LAYERS || params.layers || params.typeName;
        if (defined(layerName)) {
            newItem = isWms ? new WebMapServiceCatalogItem(options.terria) : new WebFeatureServiceCatalogItem(options.terria);
            newItem.layers = layerName;
        } else {
            if (isWms && (options.allowWmsGroups || options.allowGroups)) {  // allowGroups is deprecated.
                newItem = new WebMapServiceCatalogGroup(options.terria);
            } else if (isWfs && options.allowWfsGroups) {
                newItem = new WebFeatureServiceCatalogGroup(options.terria);
            } else {
                return undefined;
            }
        }
        uri.search('');
        url = uri.toString();
    } else {
        newItem = new matchingFormats[0][1](options.terria);
    }
    if (!newItem) {
        return undefined;
    }

    if (options.useResourceName) {
        newItem.name = resource.name;
    } else {
        newItem.name = itemData.title;
    }


    if (itemData.notes) {
        newItem.info.push({
            name: 'Dataset Description',
            content: itemData.notes
        });

        // Prevent a description - often the same one - from also coming from the WMS server.
        newItem.info.push({
            name: 'Data Description',
            content: ''
        });
    }

    if (defined(resource.description)) {
        newItem.info.push({
            name: 'Resource Description',
            content: resource.description
        });
    }

    if (defined(itemData.license_url)) {
        newItem.info.push({
            name: 'Licence',
            content: '[' + (itemData.license_title || itemData.license_url) + '](' + itemData.license_url + ')'
        });
    } else if (defined(itemData.license_title)) {
        newItem.info.push({
            name: 'Licence',
            content: itemData.license_title
        });
    }

    newItem.url = url;

    var bboxString = itemData.geo_coverage || extras.geo_coverage;
    if (defined(bboxString)) {
        var parts = bboxString.split(',');
        if (parts.length === 4) {
            newItem.rectangle = Rectangle.fromDegrees(parts[0], parts[1], parts[2], parts[3]);
        }
    }
    newItem.dataUrl = new URI(options.ckanBaseUrl).segment('dataset').segment(itemData.name).toString();
    newItem.dataUrlType = 'direct';

    if (defined(options.dataCustodian)) {
        newItem.dataCustodian = options.dataCustodian;
    } else if (itemData.organization && itemData.organization.title) {
        newItem.dataCustodian = itemData.organization.description || itemData.organization.title;
    }

    if (typeof(options.itemProperties) === 'object') {
        newItem.updateFromJson(options.itemProperties);
    }

    if (defined(parent)) {
        newItem.id = parent.uniqueId + '/' + resource.id;
    }

    return newItem;
};
Beispiel #24
0
 it("can zoom to only if rectangle is defined", function() {
   expect(item.canZoomTo).toBe(false);
   // When a rectangle is defined, it can be zoomed-to.
   item.rectangle = Rectangle.fromDegrees(1, 2, 3, 4);
   expect(item.canZoomTo).toBe(true);
 });
Beispiel #25
0
function populateGroupFromResults(ckanGroup, json) {
    var items = json.result.results;
    for (var itemIndex = 0; itemIndex < items.length; ++itemIndex) {
        var item = items[itemIndex];

        if (ckanGroup.blacklist && ckanGroup.blacklist[item.title]) {
            console.log('Provider Feedback: Filtering out ' + item.title + ' (' + item.name + ') because it is blacklisted.');
            continue;
        }

        var textDescription = '';

        if (item.notes) {
            textDescription = item.notes;
        }

        if (item.license_url && (item.notes === null || item.notes.indexOf('[Licence]') === -1)) {
            textDescription += '\n\n[Licence](' + item.license_url + ')';
        }

        var extras = {};
        if (defined(item.extras)) {
            for (var idx = 0; idx < item.extras.length; idx++) {
                extras[item.extras[idx].key] = item.extras[idx].value;
            }
        }

        var dataUrl = extras.data_url;
        var dataUrlType = extras.data_url_type;

        var rectangle;
        var bboxString = item.geo_coverage || extras.geo_coverage;
        if (defined(bboxString)) {
            var parts = bboxString.split(',');
            if (parts.length === 4) {
                rectangle = Rectangle.fromDegrees(parts[0], parts[1], parts[2], parts[3]);
            }
        }

        var dataGovCkan = (ckanGroup.url === 'http://www.data.gov.au');  //data.gov.au hack

        // Currently, we support WMS and Esri REST layers.
        var resources = item.resources;
        for (var resourceIndex = 0; resourceIndex < resources.length; ++resourceIndex) {
            var resource = resources[resourceIndex];
                //TODO: make the resource types a parameter in the init file
            if (resource.__filtered) {
                continue;
            }

            var isWms;
            if (dataGovCkan) {
                if (resource.format.match(jsonFormatRegex)) {
                    isWms = true;
                } else if (resource.format.match(kmlFormatRegex)) {
                    isWms = false;
                } else {
                    continue;
                }
            }
            else {
                if (resource.format.match(wmsFormatRegex)) {
                    isWms = true;
                } else if (resource.format.match(esriRestFormatRegex) || resource.format.match(kmlFormatRegex)) {
                    isWms = false;
                } else {
                    continue;
                }
            }

            var baseUrl = resource.wms_url;
            if (!defined(baseUrl)) {
                baseUrl = resource.url;
                if (!defined(baseUrl)) {
                    continue;
                }
            }

            // Extract the layer name from the URL.
            var uri = new URI(baseUrl);
            var params = uri.search(true);
            var layerName = params.LAYERS || params.layers || params.typeName;

            if (isWms && !defined(layerName)) {
                continue;
            }

            // Remove the query portion of the WMS URL.
            var url = baseUrl;
            if (isWms) {
                uri.search('');
                url = uri.toString();

                if (dataGovCkan) {
                    url = url.replace('wfs', 'wms');  //data.gov.au hack
                }
            }

            var newItem;
            if (isWms) {
                if (!ckanGroup.includeWms) {
                    continue;
                }
                newItem = new WebMapServiceCatalogItem(ckanGroup.terria);
            } else if (resource.format.match(esriRestFormatRegex)) {
                if (!ckanGroup.includeEsriMapServer) {
                    continue;
                }
                newItem = new ArcGisMapServerCatalogItem(ckanGroup.terria);
            } else if (resource.format.match(kmlFormatRegex)) {
                if (!ckanGroup.includeKml) {
                    continue;
                }
                newItem = new KmlCatalogItem(ckanGroup.terria);
            } else {
                continue;
            }

            if (ckanGroup.useResourceName) {
                newItem.name = resource.name;
            } else {
                newItem.name = item.title;
            }

            newItem.info.push({
                name: 'Dataset Description',
                content: textDescription
            });

            if (defined(resource.description)) {
                newItem.info.push({
                    name: 'Resource Description',
                    content: resource.description
                });
            }

            newItem.url = url;
            newItem.rectangle = rectangle;
            newItem.dataUrl = dataUrl;
            newItem.dataUrlType = dataUrlType;

            if (isWms) {
                newItem.layers = layerName;
                //This should be deprecated and done on a server by server basis when feasible
                newItem.parameters = ckanGroup.wmsParameters;
            }

            if (defined(ckanGroup.dataCustodian)) {
                newItem.dataCustodian = ckanGroup.dataCustodian;
            } else if (item.organization && item.organization.title) {
                newItem.dataCustodian = item.organization.description || item.organization.title;
            }

            var groups;
            if (ckanGroup.groupBy === 'group') {
                groups = item.groups;
            } else if (ckanGroup.groupBy === 'organization') {
                groups = [item.organization];
            }

            if (defined(groups) && groups.length > 0) {
                for (var groupIndex = 0; groupIndex < groups.length; ++groupIndex) {
                    var group = groups[groupIndex];
                    var groupName = group.display_name || group.title;
                    if (groupName.indexOf(',') !== -1) {
                        groupName = groupName.substring(0, groupName.indexOf(','));
                    }

                    if (ckanGroup.blacklist && ckanGroup.blacklist[groupName]) {
                        continue;
                    }

                    var existingGroup = ckanGroup.findFirstItemByName(groupName);
                    if (!defined(existingGroup)) {
                        existingGroup = new CatalogGroup(ckanGroup.terria);
                        existingGroup.name = groupName;
                        ckanGroup.add(existingGroup);
                    }

                    existingGroup.add(newItem);
                }
            } else {
                ckanGroup.add(newItem);
            }
        }
    }

    function compareNames(a, b) {
        var aName = a.name.toLowerCase();
        var bName = b.name.toLowerCase();
        if (aName < bName) {
            return -1;
        } else if (aName > bName) {
            return 1;
        } else {
            return 0;
        }
    }

    ckanGroup.items.sort(compareNames);

    for (var i = 0; i < ckanGroup.items.length; ++i) {
        if (defined(ckanGroup.items[i].items)) {
            ckanGroup.items[i].items.sort(compareNames);
        }
    }
}
Beispiel #26
0
"use strict";

var when = require("terriajs-cesium/Source/ThirdParty/when");
var Rectangle = require("terriajs-cesium/Source/Core/Rectangle");
var loadWithXhr = require("../../lib/Core/loadWithXhr");

var GnafApi = require("../../lib/Models/GnafApi");
var CorsProxy = require("../../lib/Core/CorsProxy");
var CustomMatchers = require("../Utility/CustomMatchers");

var UNPROXIED_URL = "http://example.com";
var PROXIED_URL = "http://proxy/example.com";
var SEARCH_TERM = "bananas";
var ANOTHER_SEARCH_TERM = "papayas";
// Rectangle is west, south, east, north
var RECTANGLE = Rectangle.fromDegrees(1, 2, 3, 4);

describe("GnafApi", function() {
  var gnafApi, loadDeferredFirst, loadDeferredSecond, corsProxy;

  beforeEach(function() {
    jasmine.addMatchers(CustomMatchers);
    var loadDeferredCount = 1;

    loadDeferredFirst = when.defer();
    loadDeferredSecond = when.defer();

    spyOn(loadWithXhr, "load").and.callFake(function(
      url,
      responseType,
      method,
Beispiel #27
0
CkanCatalogItem.createCatalogItemFromResource = function(options) {
  var resource = options.resource;
  var itemData = options.itemData;
  var extras = options.extras;
  var parent = options.parent;

  if (resource.__filtered) {
    return;
  }

  if (!defined(extras)) {
    extras = {};
    if (defined(itemData.extras)) {
      for (var idx = 0; idx < itemData.extras.length; idx++) {
        extras[itemData.extras[idx].key] = itemData.extras[idx].value;
      }
    }
  }

  var formats = [
    // Format Regex, Catalog Item, (optional) URL regex
    [options.wmsResourceFormat, WebMapServiceCatalogItem],
    [options.wfsResourceFormat, WebFeatureServiceCatalogItem],
    [
      options.esriMapServerResourceFormat,
      ArcGisMapServerCatalogItem,
      /MapServer/
    ],
    [
      options.esriFeatureServerResourceFormat,
      ArcGisFeatureServerCatalogItem,
      /FeatureServer/
    ],
    [options.kmlResourceFormat, KmlCatalogItem, undefined, /\.zip$/],
    [options.geoJsonResourceFormat, GeoJsonCatalogItem],
    [options.czmlResourceFormat, CzmlCatalogItem],
    [options.csvResourceFormat, CsvCatalogItem]
  ].filter(function(format) {
    return defined(format[0]);
  });

  var baseUrl = resource.wms_url;
  if (!defined(baseUrl)) {
    baseUrl = resource.url;
    if (!defined(baseUrl)) {
      return undefined;
    }
  }

  var matchingFormats = formats.filter(function(format) {
    // Matching formats must match the format regex,
    // and also the URL regex if it exists and not the URL exclusion regex if it exists.
    return (
      resource.format.match(format[0]) &&
      (!defined(format[2]) || baseUrl.match(format[2])) &&
      (!defined(format[3]) || !baseUrl.match(format[3]))
    );
  });
  if (matchingFormats.length === 0) {
    return undefined;
  }

  var isWms = matchingFormats[0][1] === WebMapServiceCatalogItem;
  var isWfs = matchingFormats[0][1] === WebFeatureServiceCatalogItem;

  // Extract the layer name from the URL.
  var uri = new URI(baseUrl);
  var params = uri.search(true);

  // Remove the query portion of the WMS URL.
  var url = baseUrl;

  var newItem;
  if (isWms || isWfs) {
    var layerName =
      resource.wms_layer || params.LAYERS || params.layers || params.typeName;
    if (defined(layerName)) {
      newItem = isWms
        ? new WebMapServiceCatalogItem(options.terria)
        : new WebFeatureServiceCatalogItem(options.terria);
      newItem.layers = layerName;
    } else {
      if (isWms && options.allowWmsGroups) {
        newItem = new WebMapServiceCatalogGroup(options.terria);
      } else if (isWfs && options.allowWfsGroups) {
        newItem = new WebFeatureServiceCatalogGroup(options.terria);
      } else {
        return undefined;
      }
    }
    uri.search("");
    url = uri.toString();
  } else {
    newItem = new matchingFormats[0][1](options.terria);
  }
  if (!newItem) {
    return undefined;
  }

  if (options.useResourceName) {
    newItem.name = resource.name;
  } else {
    newItem.name = itemData.title;
  }

  if (itemData.notes) {
    newItem.info.push({
      name: "Dataset Description",
      content: itemData.notes
    });

    // Prevent a description - often the same one - from also coming from the WMS server.
    newItem.info.push({
      name: "Data Description",
      content: ""
    });
  }

  if (defined(resource.description)) {
    newItem.info.push({
      name: "Resource Description",
      content: resource.description
    });
  }

  if (defined(itemData.license_url)) {
    newItem.info.push({
      name: "Licence",
      content:
        "[" +
        (itemData.license_title || itemData.license_url) +
        "](" +
        itemData.license_url +
        ")"
    });
  } else if (defined(itemData.license_title)) {
    newItem.info.push({
      name: "Licence",
      content: itemData.license_title
    });
  }

  if (defined(itemData.author)) {
    newItem.info.push({
      name: "Author",
      content: itemData.author
    });
  }

  if (defined(itemData.contact_point)) {
    newItem.info.push({
      name: "Contact",
      content: itemData.contact_point
    });
  }

  // If the date string is of format 'dddd-dd-dd*' extract the first part, otherwise we retain the entire date string.
  function prettifyDate(date) {
    if (date.match(/^\d\d\d\d-\d\d-\d\d.*/)) {
      return date.substr(0, 10);
    } else {
      return date;
    }
  }

  if (defined(itemData.metadata_created)) {
    newItem.info.push({
      name: "Created",
      content: prettifyDate(itemData.metadata_created)
    });
  }

  if (defined(itemData.metadata_modified)) {
    newItem.info.push({
      name: "Modified",
      content: prettifyDate(itemData.metadata_modified)
    });
  }

  if (defined(itemData.update_freq)) {
    newItem.info.push({
      name: "Update Frequency",
      content: itemData.update_freq
    });
  }

  newItem.url = url;

  var bboxString = itemData.geo_coverage || extras.geo_coverage;
  if (defined(bboxString)) {
    var parts = bboxString.split(",");
    if (parts.length === 4) {
      newItem.rectangle = Rectangle.fromDegrees(
        parts[0],
        parts[1],
        parts[2],
        parts[3]
      );
    }
  }
  newItem.dataUrl = new URI(options.ckanBaseUrl)
    .segment("dataset")
    .segment(itemData.name)
    .toString();
  newItem.dataUrlType = "direct";

  if (defined(options.dataCustodian)) {
    newItem.dataCustodian = options.dataCustodian;
  } else if (itemData.organization && itemData.organization.title) {
    newItem.dataCustodian =
      itemData.organization.description || itemData.organization.title;
  }

  if (typeof options.itemProperties === "object") {
    newItem.updateFromJson(options.itemProperties);
  }

  if (defined(parent)) {
    newItem.id = parent.uniqueId + "/" + resource.id;
  }

  return newItem;
};