Example #1
0
function setDefaultIdColumns(item, tableStructure) {
    // This just checks there is a time column - not that it's one we would actually activate.
    // Would be better to do the full check.
    // Note we check if === undefined explicitly so the user can set to null to prevent this default.
    if (item.idColumns === undefined && !defined(tableStructure.idColumnNames) &&
        defined(tableStructure.columnsByType[VarType.TIME].length > 0) &&
        tableStructure.getColumnNames().indexOf(DEFAULT_ID_COLUMN) >= 0) {
        item.idColumns = [DEFAULT_ID_COLUMN];
        tableStructure.idColumnNames = item.idColumns;
    }
}
Example #2
0
 get: function() {
     if (defined(this.tableStructure) && defined(this.tableStructure.activeTimeColumn) && defined(this.tableStructure.activeTimeColumn.timeIntervals)) {
         return this.tableStructure.activeTimeColumn.timeIntervals.reduce(function(intervals, interval) {
             if (defined(interval)) {
                 intervals.addInterval(interval);
             }
             return intervals;
         }, new TimeIntervalCollection());
     }
     return undefined;
 }
 get : function() {
     if (defined(this._legendUrl)) {
         return this._legendUrl;
     }
     if (!defined(this.url)) {
         return undefined;
     }
     var layer = this.layers.split(',')[0];
     return new LegendUrl(cleanUrl(this.url) +
         '?service=WMS&version=1.3.0&request=GetLegendGraphic&format=image/png&layer=' + layer, 'image/png');
 },
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;
}
Example #5
0
CsvCatalogItem.prototype._hide = function() {
    if (defined(this._dataSource)) {
        var dataSources = this.terria.dataSources;
        if (!dataSources.contains(this._dataSource)) {
            throw new DeveloperError('This data source is not shown.');
        }
        dataSources.remove(this._dataSource, false);
    }
    if (defined(this._regionMapping)) {
        this._regionMapping.hide();
    }
};
Example #6
0
CsvCatalogItem.prototype._show = function() {
    if (defined(this._dataSource)) {
        var dataSources = this.terria.dataSources;
        if (dataSources.contains(this._dataSource)) {
            throw new DeveloperError('This data source is already shown.');
        }
        dataSources.add(this._dataSource);
    }
    if (defined(this._regionMapping)) {
        this._regionMapping.show();
    }
};
Example #7
0
function svgElement(legend, element, attributes, className, innerText) {
    var ele = document.createElementNS(legend._svgns, element);
    Object.keys(attributes).forEach(function(att) {
        ele.setAttribute(att, attributes[att]);
    });
    if (defined(innerText)) {
        ele.textContent = innerText;
    }
    if (defined(className)) {
        ele.setAttribute('class', className);
    }
    return ele;
}
Example #8
0
    var cleanup = runLater(function() {
        // Set this again just in case a vector pick came through and reset it to the vector's position.
        var newPickLocation = Ellipsoid.WGS84.cartographicToCartesian(pickedLocation);
        var mapInteractionModeStack = leaflet.terria.mapInteractionModeStack;
        if (defined(mapInteractionModeStack) && mapInteractionModeStack.length > 0) {
            mapInteractionModeStack[mapInteractionModeStack.length - 1].pickedFeatures.pickPosition = newPickLocation;
        } else if (defined(leaflet.terria.pickedFeatures)) {
            leaflet.terria.pickedFeatures.pickPosition = newPickLocation;
        }

        // Unset this so that the next click will start building features from scratch.
        leaflet._pickedFeatures = undefined;
    });
Example #9
0
 get: function() {
     // can override the extent using this.rectangle, otherwise falls back the datasource's extent (with a small margin).
     if (defined(this._rectangle)) {
         return this._rectangle;
     }
     var rect;
     if (defined(this._dataSource)) {
         rect = this._dataSource.extent;
     } else if (defined(this._regionMapping)) {
         rect = this._regionMapping.extent;
     }
     return addMarginToRectangle(rect, 0.08);
 },
Example #10
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);
    }
}
Example #11
0
 legend.items.forEach(function(item, i) {
     var y = itemY(legend, i);
     if (defined(item.titleAbove)) {
         drawLabel(y, item.titleAbove);
         drawTick(y);
     }
     if (defined(item.title)) {
         drawLabel(y + legend.itemHeight / 2, item.title);
     }
     if (defined(item.titleBelow)) {
         drawLabel(y + legend.itemHeight, item.titleBelow);
         drawTick(y + legend.itemHeight);
     }
 });
Example #12
0
Leaflet.prototype.lowerToBottom = function(item) {
    if (defined(item.items)) {
        for (var i = item.items.length - 1; i >= 0; --i) {
            var subItem = item.items[i];
            this.lowerToBottom(subItem);  // recursive
        }
    }

    if (!defined(item._imageryLayer)) {
        return;
    }

    item._imageryLayer.setZIndex(0);
};
Example #13
0
        viewModel._closeOnInteraction = function(e) {
            var isClickOutside = true;
            if (defined(e) && defined(viewModel._domNodes)) {
                var element = e.target;
                while (isClickOutside && element) {
                    isClickOutside = viewModel._domNodes.indexOf(element) < 0 && (!defined(element.className) || !defined(element.className.indexOf) || element.className.indexOf('menu-bar-item') < 0);
                    element = element.parentNode;
                }
            }

            if (isClickOutside) {
                viewModel.close();
            }
        };
        get: function() {
            if (defined(this._getCapabilitiesUrl)) {
                return this._getCapabilitiesUrl;
            }

            if (defined(this.metadataUrl)) {
                return this.metadataUrl;
            }

            if (!defined(this.url)) {
                return undefined;
            }

            return cleanUrl(this.url) + '?service=WMS&version=1.3.0&request=GetCapabilities';
        },
function updateInfoSection(item, overwrite, sectionName, sectionValue) {
  if (!defined(sectionValue) || sectionValue.length === 0) {
    return;
  }

  var section = item.findInfoSection(sectionName);
  if (!defined(section)) {
    item.info.push({
      name: sectionName,
      content: sectionValue
    });
  } else if (overwrite) {
    section.content = sectionValue;
  }
}
function getInheritableProperty(layer, name, appendValues) {
    var value = [];
    while (defined(layer)) {
        if (defined(layer[name])) {
            if (appendValues) {
                value = value.concat((layer[name] instanceof Array) ? layer[name] : [layer[name]]);
            } else {
                return layer[name];
            }
        }
        layer = layer._parent;
    }

    return value.length > 0 ? value : undefined;
}
WebMapServiceCatalogItem.prototype._load = function() {
    var that = this;
    var promises = [];

    if (!defined(this._rawMetadata)) {
        promises.push(loadXML(proxyCatalogItemUrl(this, this.getCapabilitiesUrl)).then(function(xml) {
            var metadata = capabilitiesXmlToJson(xml);
            that.updateFromCapabilities(metadata, false);
        }));
    }

    // Query WMS for wfs or wcs URL if no dataUrl is present
    if (!defined(this.dataUrl)) {
        var describeLayersURL = cleanUrl(this.url) + '?service=WMS&version=1.1.1&sld_version=1.1.0&request=DescribeLayer&layers=' + encodeURIComponent(this.layers);

        promises.push(loadXML(proxyCatalogItemUrl(this, describeLayersURL)).then(function(xml) {
            var json = xml2json(xml);
            // LayerDescription could be an array. If so, only use the first element
            var LayerDescription = (json.LayerDescription instanceof Array) ? json.LayerDescription[0] : json.LayerDescription;
            if (defined(LayerDescription) && defined(LayerDescription.owsURL) && defined(LayerDescription.owsType)) {
                switch (LayerDescription.owsType.toLowerCase()) {
                    case 'wfs':
                        if (defined(LayerDescription.Query) && defined(LayerDescription.Query.typeName)) {
                            that.dataUrl = cleanUrl(LayerDescription.owsURL) + '?service=WFS&version=1.1.0&request=GetFeature&typeName=' + LayerDescription.Query.typeName + '&srsName=EPSG%3A4326&maxFeatures=1000';
                            that.dataUrlType = 'wfs-complete';
                        }
                        else {
                            that.dataUrl = cleanUrl(LayerDescription.owsURL);
                            that.dataUrlType = 'wfs';
                        }
                        break;
                    case 'wcs':
                        if (defined(LayerDescription.Query) && defined(LayerDescription.Query.typeName)) {
                            that.dataUrl = cleanUrl(LayerDescription.owsURL) + '?service=WCS&version=1.1.1&request=DescribeCoverage&identifiers=' + LayerDescription.Query.typeName;
                            that.dataUrlType = 'wcs-complete';
                        }
                        else {
                            that.dataUrl = cleanUrl(LayerDescription.owsURL);
                            that.dataUrlType = 'wcs';
                        }
                        break;
                }
            }
        }).otherwise(function(err) { })); // Catch potential XML error - doesn't matter if URL can't be retrieved
    }

    return when.all(promises);
};
Example #18
0
TableDataSource.prototype.describe = function(properties) {
    var html = '<table class="cesium-infoBox-defaultTable">';
    for ( var key in properties) {
        if (properties.hasOwnProperty(key)) {
            var value = properties[key];
            if (defined(value)) {
                    //see if we should skip this in the details - starts with __
                if (key.substring(0, 2) === '__') {
                    continue;
                }
                if (value instanceof JulianDate) {
//                    value = JulianDate.toIso8601(value, 0);
                    value = JulianDate.toDate(value).toDateString();
                }
                if (typeof value === 'object') {
                    html += '<tr><td>' + key + '</td><td>' + this.describe(value) + '</td></tr>';
                } else {
                    html += '<tr><td>' + key + '</td><td>' + value + '</td></tr>';
                }
            }
        }
    }
    html += '</table>';
    return html;
};
Example #19
0
 get: function() {
     if (defined(this._tableStructure)) {
         return [this._tableStructure];
     } else {
         return [];
     }
 }
Example #20
0
TableCatalogItem.prototype._show = function() {
    if (defined(this._dataSource)) {
        var dataSources = this.terria.dataSources;
        if (dataSources.contains(this._dataSource)) {
            if(console && console.log){
                console.log(new Error('This data source is already shown.'));
            }
            return;
        }
        dataSources.add(this._dataSource);
    }
    if (defined(this._regionMapping)) {
        this._regionMapping.show();
    }
    addToChartableItemsIfNotMappable(this);
};
Example #21
0
 yAxisElementsElements.nodes().forEach(yAxisElement => {
     const yAxisD3 = d3Select(yAxisElement);
     const theseUnits = yAxisElement.__data__;
     const thisYScale = scales.y[theseUnits || Scales.unknownUnits];
     // Only show the horizontal grid lines for the main y-axis, or it gets too confusing.
     const tickSizeInner = (thisYScale === mainYScale && defined(state.grid) && state.grid.y) ? -size.width : 3;
     let yTickValues;
     if (state.mini) {
         yTickValues = thisYScale.domain();
     } else {
         const numYTicks = state.mini ? 2 : Math.min(6, Math.floor(size.plotHeight / 30) + 1);
         yTickValues = Scales.truncatedTickValues(thisYScale, numYTicks);
     }
     yAxis
         .tickValues(yTickValues)
         .tickSizeInner(tickSizeInner)
         .scale(thisYScale);
     yAxisD3
         .transition(t)
         .style('opacity', hasData ? 1 : 1e-6)
         .select('.ticks')
             .call(yAxis);
     let colorKeyHtml = '';
     if (allUnits.length > 1) {
         const unitColors = data.filter(line=>(line.units === theseUnits)).map(line=>line.color);
         unitColors.forEach((color, index)=>{
             const y = -1 - index * 4;
             colorKeyHtml += '<path d="M-30 ' + y + ' h 30" style="stroke:' + color + '"/>';
         });
     }
     yAxisD3.select('.colors').html(colorKeyHtml);
     yAxisD3.select('.units-label').text(theseUnits || '');
     yAxisD3.select('.units-label-shadow').text(theseUnits || '');
 });
Example #22
0
RegionProviderList.prototype.getRegionDetails = function(variableNames, preferedRegionVariableName, preferedRegionType) {
    var results = [];
    // If preferedRegionVariableName is in variableNames (which it must be to be meaningful; if undefined, it won't be), remove it first.
    var index = variableNames.indexOf(preferedRegionVariableName);
    if (index >= 0) {
        variableNames = variableNames.slice(); // clone it so we don't potentially confuse the caller.
        variableNames.splice(index, 1);
        if (!defined(preferedRegionType)) {
            // If no type is provided, simply put this back in the front of the array, to prioritize it.
            variableNames.unshift(preferedRegionVariableName);
        } else {
            // If a type is provided, handle it specially.
            var regionProvider = this.getRegionProvider(preferedRegionType);
            results.push({
                regionProvider: regionProvider,
                variableName: preferedRegionVariableName,
                disambigVariableName: regionProvider.findDisambigVariable(variableNames)
            });
        }
    }
    // Figure out the region variable and type based on aliases.
    for (var i = 0; i < this.regionProviders.length; i++) {
        var rv = this.regionProviders[i].findRegionVariable(variableNames);
        if (rv) {
            results.push({
                regionProvider: this.regionProviders[i],
                variableName: rv,
                disambigVariableName: this.regionProviders[i].findDisambigVariable(variableNames)
            });
        }
    }
    return results;
};
Example #23
0
CorsProxy.prototype.shouldUseProxy = function(url) {
    if (!defined(url)) {
        // eg. no url may be passed if all data is embedded
        return false;
    }

    var uri = new URI(url);
    var host = uri.host();

    if (host === '') {
        // do not proxy local files
        return false;
    }

    if (!this.isOpenProxy && !hostInDomains(host, this.proxyDomains)) {
        // we're not willing to proxy for this host
        return false;
    }
    if (this.alwaysUseProxy) {
        return true;
    }

    if (this.pageIsHttps && uri.protocol() === 'http') {
        // if we're accessing an http resource from an https page, always proxy in order to avoid a mixed content error.
        return true;
    }

    if (hostInDomains(host, this.corsDomains)) {
        // we don't need to proxy for this host, because it supports CORS
        return false;
    }

    // we are ok with proxying for this host and we need to
    return true;
};
Example #24
0
TableDataSource.prototype.setColorGradient = function (colorMap) {
    if (colorMap === undefined) {
        return;
    }
    
    this.colorMap = colorMap;

    var canvas = document.createElement("canvas");
    if (!defined(canvas)) {
        return;
    }
    var w = canvas.width = 64;
    var h = canvas.height = 256;
    var ctx = canvas.getContext('2d');
    
    // Create Linear Gradient
    var grad = this.colorMap;
    var linGrad = ctx.createLinearGradient(0,0,0,h);
    if (grad.length === 1) {
        this._colorByValue = false;
        linGrad.addColorStop(0.0, grad[0].color);
        linGrad.addColorStop(1.0, grad[0].color);
    } 
    else {
        for (var i = 0; i < grad.length; i++) {
            linGrad.addColorStop(grad[i].offset, grad[i].color);
        }
    }
    ctx.fillStyle = linGrad;
    ctx.fillRect(0,0,w,h);

    this.dataImage = ctx.getImageData(0, 0, 1, 256);
};
Example #25
0
TableCatalogItem.prototype._enable = function(layerIndex) {
    if (defined(this._regionMapping)) {
        this._regionMapping.enable(layerIndex);
    }
    addToChartableItemsIfNotMappable(this);
    this.terria.currentViewer.updateItemForSplitter(this);
};
 json.layers.forEach(function(l) {
   if (noDataRegex.test(l.layerName) || labelsRegex.test(l.layerName)) {
     return;
   }
   if (
     defined(this.layers) &&
     layers.indexOf(String(l.layerId)) < 0 &&
     layers.indexOf(l.layerName.toLowerCase()) < 0
   ) {
     return;
   }
   options.title = replaceUnderscores(l.layerName);
   l.legend.forEach(function(leg) {
     if (shownLegends[leg.label + leg.imageData]) {
       // Hide truly duplicate layers.
       return;
     }
     shownLegends[leg.label + leg.imageData] = true;
     var title = leg.label !== "" ? leg.label : l.layerName;
     itemPromises.push(
       loadImage(
         replaceUnderscores(title),
         "data:" + leg.contentType + ";base64," + leg.imageData
       )
     );
   }, this);
 }, this);
    get: function() {
      if (defined(this._metadataUrl)) {
        return this._metadataUrl;
      }

      return cleanUrl(this.url);
    },
function createWfsDataSource(wfsGroup, featureType, supportsJsonGetFeature, dataCustodian) {
    var result = new WebFeatureServiceCatalogItem(wfsGroup.terria);

    result.name = featureType.Title;
    result.description = defined(featureType.Abstract) && featureType.Abstract.length > 0 ? featureType.Abstract : wfsGroup.description;
    result.dataCustodian = dataCustodian;
    result.url = wfsGroup.url;
    result.typeNames = featureType.Name;

    result.description = '';

    var wfsGroupHasDescription = defined(wfsGroup.description) && wfsGroup.description.length > 0;
    var layerHasAbstract = defined(featureType.Abstract) && featureType.Abstract.length > 0;

    if (wfsGroupHasDescription) {
        result.description += wfsGroup.description;
    }

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

    if (layerHasAbstract) {
        result.description += featureType.Abstract;
    }

    result.requestGeoJson = supportsJsonGetFeature;
    result.requestGml = true;

    var boundingBoxes = featureType.WGS84BoundingBox;

    var rectangle;
    if (boundingBoxes instanceof Array) {
        rectangle = wgs84BoundingBoxToRectangle(boundingBoxes[0]);
        for (var i = 1; i < boundingBoxes.length; ++i) {
            rectangle = unionRectangles(rectangle, wgs84BoundingBoxToRectangle(boundingBoxes[i]));
        }
    } else if (defined(boundingBoxes)) {
        rectangle = wgs84BoundingBoxToRectangle(boundingBoxes);
    } else {
        rectangle = Rectangle.MAX_VALUE;
    }

    result.rectangle = rectangle;

    return result;
}
/**
 * Format the number using the locale format.
 * When Intl is not available (includes Safari), applies commas to separate thousands, eg. 912345.6789 => '912,345.6789'.
 * Nulls are returned as an empty string, not 0.
 *
 * @param {Number} number The number to format.
 * @param {Object} [options] A subset of the options of Javascript's Intl NumberFormat,
 *        https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString .
 *        Note we default useGrouping to false (not true) and maximumFractionDigits to 20 (not 3).
 * @param {Boolean} [options.useGrouping] A flag for whether to separate thousands. Defaults to false.
 * @param {Integer} [options.minimumFractionDigits] Minimum number of decimal places. Defaults to 0.
 * @param {Integer} [options.maximumFractionDigits] Maximum number of decimal places. Defaults to 20.
 * @param {String}  [options.style] Pass 'percent' to format 0.83 as 83%.
 */
function formatNumberForLocale(number, options) {
  if (!defined(number)) {
    return "";
  }
  if (isNaN(number)) {
    return number;
  }
  options = defaultValue(options, {});
  options.useGrouping = defaultValue(options.useGrouping, false);
  options.maximumFractionDigits = defaultValue(
    options.maximumFractionDigits,
    20
  );
  options.minimumFractionDigits = defaultValue(
    options.minimumFractionDigits,
    0
  );
  // if (toLocaleStringSupportsOptions()) {
  //     return formatWithIntl(number, options);
  // }
  var suffix = "";
  if (options.style === "percent") {
    number = number * 100;
    suffix = "%";
  }
  var str = number.toString();
  var frac = "";

  function setStrAndFracToFixedDecimalPlaces(number, numberOfDecimalPlaces) {
    str = (+number).toFixed(numberOfDecimalPlaces);
    var decimalIndex = str.indexOf(".");
    frac = "";
    if (decimalIndex !== -1) {
      frac = decimalPoint + str.substring(decimalIndex + 1);
      str = str.substring(0, decimalIndex);
    }
  }

  var idx = str.indexOf(".");
  if (idx !== -1) {
    frac = decimalPoint + str.substring(idx + 1);
    // Ideally we could have just done number.toFixed(options.maximumFractionDigits),
    // but toFixed uses exactly that number of digits. So we only use it if the number of decimal places > maximum.
    if (frac.length > options.maximumFractionDigits + 1) {
      setStrAndFracToFixedDecimalPlaces(number, options.maximumFractionDigits);
    } else if (frac.length < options.minimumFractionDigits + 1) {
      setStrAndFracToFixedDecimalPlaces(number, options.minimumFractionDigits);
    } else {
      str = str.substring(0, idx);
    }
  } else if (options.minimumFractionDigits > 0) {
    // We need to show an integer with the minimum number of decimal places.
    setStrAndFracToFixedDecimalPlaces(number, options.minimumFractionDigits);
  }
  if (str.length < 5 || !options.useGrouping) {
    return str + frac + suffix;
  }
  return str.replace(/\B(?=(\d{3})+(?!\d))/g, separator) + frac + suffix;
}
Example #30
0
/**
 * Given a concept object with name and possibly items properties, return its human-readable version.
 * @private
 * @param  {Object} conceptNameMap An object whose keys are the concept.names, eg. "ANCP".
 *         Values may be Strings (eg. "Ancestry"), or
 *         a 'code map' (eg. "MEASURE" : {"Persons": "Sex", "85 years and over": "Age", "*": "Measure"}.
 * @param  {AbsConcept} concept An object with a name property and, if a codemap is to be used, an items array of objects with a name property.
 *         In that case, it finds the first of those names to appear as a key in the code map. The value of this property is returned. (Phew!)
 * @return {String} Human-readable concept name.
 */
function getHumanReadableConceptName(conceptNameMap, concept) {
  if (!defined(conceptNameMap[concept.name])) {
    return concept.name; // Default to the name given in the file.
  }
  if (typeof conceptNameMap[concept.name] === "string") {
    return conceptNameMap[concept.name];
  } else {
    var codeMap = conceptNameMap[concept.name];
    for (var j = 0; j < concept.items.length; j++) {
      if (defined(codeMap[concept.items[j].name])) {
        return codeMap[concept.items[j].name];
      }
    }
    // Use the wildcard, if defined, or else fall back to the name in the file.
    return codeMap["*"] || concept.name;
  }
}