Skip to content

reearth.layers

The reearth.layers namespace provides a set of methods to manage and manipulate layers within a reearth scene, allowing plugin developers to add, find, modify, or delete layers programmatically.

Properties

layers

This property provides a list of all layers currently exists in the reearth scene, allowing plugin developers to access and manipulate the layers as needed. The property returns an array of LazyLayer objects, each representing a distinct layer within the scene.

Syntax

reearth.layers.layers: LazyLayer[];

Return Value

Type LazyLayer[]

An array of LazyLayer objects, each representing a distinct layer within the scene.

overridden

This is an optional property that provides a layer in the reearth scene whose properties are overridden. This method allows users to confirm how the layer is overridden. The flexibility offered by this method is crucial for scenarios where layer properties need to be adjusted in response to user interactions, application state changes, or external data updates.

Syntax

reearth.layers.overriden: OverriddenLayer[];

Return Value

Type Omit<Layer, "type" | "children">

A type that excludes type and children from the Layer type definition.

Example

// Check if there are any overridden properties defined
if (reearth.layers.overridden) {
console.log("Overridden properties are defined.");
// Iterate through the overridden properties and log each one
Object.entries(reearth.layers.overridden).forEach(([layerId, props]) => {
console.log(`Layer ID: ${layerId}, Overridden Properties:`, props);
});
} else {
console.log("No overridden properties are defined.");
}

selected

This represents the currently selected layer within a reearth project. It is an optional property that holds a ComputedLayer object if a layer is selected, or it may be undefined if no layer is currently selected. This property provides an easy way to access details about the selected layer directly, facilitating operations or interactions that depend on the user’s selection, such as querying specific layer data, modifying properties, or displaying additional information in UI components.

Syntax

reearth.layers.selected?: computedLayer;

Return Value

Type ComputedLayer

A layer obtained after all processing is completed, containing both original and processed geographic data with applied & evaluated styles and states.

Example

// Check if there is a selected layer and log its details
if (reearth.layers.selected) {
console.log("Selected Layer ID:", reearth.layers.selected.id);
console.log("Selected Layer Title:", reearth.layers.selected.layer?.title);
} else {
console.log("No layer is currently selected.");
}

selectedFeature

This represents the currently selected feature within a reearth project. It is an optional property that holds a feature object if a feature is selected, or it may be undefined if no feature is currently selected. This property provides an easy way to access details about the selected feature directly, facilitating operations or interactions that depend on the user’s selection, such as querying specific feature data or displaying additional information in plugin extensions.

Syntax

reearth.layers.selectedFeature?: computedFeature;

Return Value

Type ComputedFeature

A single geographic feature (point, line, polygon, etc.) with all its final evaluated properties and styles applied.

Example

// Check if there is a selected feature and log its details
if (reearth.layers.selectedFeature) {
console.log("Selected Feature ID:", reearth.layers.selectedFeature.id);
} else {
console.log("No Feature is currently selected.");
}

Methods

add

This method is used to add a new layer to the reearth scene. This method is essential for dynamically enhancing the scene with additional content layers, which can include elements such as imagery, data representations, or interactive widgets. The method takes a Layer object as its primary argument, which defines the characteristics and properties of the layer being added.

Syntax

reearth.layers.add: (layer: Layer) => string | undefined;

Parameters

layer

Type: Layer

An object that includes all the data and metadata necessary to create and manage a layer. This object defines the characteristics and properties of the layer being added to the scene.

Return Value

Type string | undefined

The method returns the unique identifier id of the newly added layer if the operation is successful, providing a reference that can be used for further operations or queries. If the operation fails, it returns undefined.

Example

const newLayerId = reearth.layers.add({
type: "simple",
data: {
type: "geojson",
value: {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: {},
geometry: {
coordinates: [139.97422779688281, 35.74642872517698],
type: "Point",
},
},
],
},
},
// marker property is required to indicate that the layer needs a marker appearance
marker: {},
});
if (newLayerId) {
console.log("Layer added successfully with ID:", newLayerId);
} else {
console.log("Failed to add layer.");
}

find

This method enables efficient searching for layers within the Reearth scene by applying a custom search function. It is helpful for identifying specific layers that meet dynamically defined criteria, such as particular attributes, properties, or conditions. The method accepts a callback function that evaluates each layer, returning true for layers that satisfy the specified conditions. This approach allows for precise operations or analyses on targeted parts of the scene, enhancing flexibility and control in layer management.

Syntax

reearth.layers.find: (
fn: (layer: Layer, index: number) => boolean,
) => Layer | undefined

Parameters

fn

Type: (layer: Layer, index: number) => boolean

A callback function used to evaluate each layer within the scene. The function receives three arguments:

  • layer: Layer: An object that includes all the data of the layer.
  • index: number: The index of the current layer.

Return Value

Type Layer | undefined

Returns the first Layer object that satisfies the provided testing function. If no layer meets the criteria, the function returns undefined

Example

//1. Define a search function to find the first visible layer
const searchFunction = (layer, index) => {
return layer.isVisible === true;
};
// Use the find method to locate the first visible layer
const foundLayer = reearth.layers.find(searchFunction);
// Log the result or handle the case where no layer is found
if (foundLayer) {
console.log(`Found visible layer with ID: ${foundLayer.id}`);
} else {
console.log("No visible layer found.");
}
//2. Search for the first layer that is a 3D Tiles with the title "Re:Earth" and assign it to a variable.
reearth.layers.find(
(layer) => layer.data.type === "3dtiles" && layer.title === "Re:Earth"
);

findAll

This method performs a comprehensive search through all layers in a project to find and return an array of layers that match a specified condition. This method takes a callback function that is applied to each layer in the project.

Syntax

reearth.layers.findAll: (layer: Layer, index: number) => boolean) => Layer[]

Parameters

layer

Type Layer

An object that includes all the data and metadata necessary to create and manage a layer.

index

Type number

The index of the current layer within its level of the hierarchy.

Return Value

Type Layer[]

Returns an array of Layer objects that satisfy the conditions specified by the callback function. If no layers meet the criteria, it returns an empty array.

Example

//1. Define a search function to find all layers with a specific visibility setting
const searchVisibleLayers = (layer) => layer.isVisible;
// Use the findAll method to get all visible layers
const visibleLayers = reearth.layers.findAll(searchVisibleLayers);
// Output the IDs of the found layers
console.log(
"Visible layers found:",
visibleLayers.map((layer) => layer.id)
);
//2. Filter out layers where the type is "GeoJSON" and the title is exactly "sample".
let filteredLayers = reearth.layers.findAll(
(layer) => layer.data.type === "geojson" && layer.title === "sample"
);
// Log the array of filtered layers to the console. This array contains all layers that meet the specified conditions.
console.log("filteredLayers: ", filteredLayers);

findById

This method is designed to retrieve a specific layer object based on its unique identifier (ID). This method is essential for directly accessing a layer when its ID is known, allowing for efficient and precise operations such as editing properties, toggling visibility, or analyzing layer-specific data. It simplifies the process of interacting with individual layers by providing a direct path to them without the need to search or iterate through the entire layer hierarchy. This method takes a single string parameter, which is the ID of the layer you want to find.

Syntax

reearth.layers.findById: (layerId: string) => Layer | undefined;

Parameters

layerId

Type string

The unique identifier of the layer that is being searched for within the scene.

Return Value

Type Layer | undefined

Returns the Layer object if a layer with the specified ID is found. If no layer matches the provided ID, it returns undefined.

Example

// Define the layer ID you are searching for
const targetLayerId = "01j1rx8xhxsk2wdydew3m8hr6q";
// Attempt to find the layer by its ID
const layer = reearth.layers.findById(targetLayerId);
// Check if the layer was found and log the result or handle it accordingly
if (layer) {
console.log(`Layer found: ${layer.title}`);
} else {
console.log("No layer found with the specified ID:", targetLayerId);
}

findByIds

This method allows for the retrieval of multiple layers from the reearth scene simultaneously based on an array of layer IDs. This method is particularly useful for applications that need to interact with or manipulate several specific layers at once, such as batch updating properties, applying effects, or managing group visibility. This method accepts a spread of string arguments, each representing the ID of a layer, and returns an array where each element corresponds to a Layer object or undefined.

Syntax

reearth.layers.findByIds: (...layerIds: string[]) => (Layer | undefined)[];

Parameters

...layerIds

Type ...string[]

An array of layer ids, each representing the unique identifier of a layer to be retrieved. This allows for flexible input of one or multiple IDs.

When use it we should spread the array as multiple arguments.

Return Value

Type (Layer | undefined)[]

Returns an array containing Layer objects or undefined for each input ID, depending on whether the layer with that ID exists in the scene. Each position in the returned array corresponds directly to the position of the ID in the input list, maintaining order consistency. If a layer with a given ID does not exist, the method returns undefined at that position in the array.

Example

// Define an array of layer IDs to be searched
const layerIds = ["01j1rx8xhxsk2wdydew3m8hr6q", "01j90ed9m6bxagb6bvfg4sk49q"];
// Retrieve the layers by their IDs
const layers = reearth.layers.findByIds(...layerIds);
// Process the results, handling both found and not found cases
layers?.forEach((layer, index) => {
if (layer) {
console.log(`Layer found: ID = ${layer.id}, Title = ${layer.title}`);
} else {
console.log(`No layer found for ID: ${layerIds[index]}`);
}
});

findFeatureById

This method provides a way to retrieve a feature associated with the feature ID. This function accepts the ID of a layer and the ID of a feature and returns a Feature objects that match the provided layer ID and Feature ID.

Syntax

reearth.layers.findFeatureById: (layerId: string, featureId: string) => Feature | undefined;

Parameters

layerId

Type string

The unique identifier of the layer that is being searched for within the scene.

featureId

Type string

The unique identifier of the feature in the layer

Return Value

Type Feature | undefined

Returns a Feature object if a feature with the specified ID is found in the specified layer. If no feature matches the provided ID, it returns undefined.

Example

// Define the layer ID and feature ID you are searching for
const targetLayerId = "01j90ed9m6bxagb6bvfg4sk49q";
const targetFeatureId = "6167fcb5-9564-4c8e-a4d3-d0b419f54ec6";
// Attempt to find the layer by its ID
const feature = reearth.layers.findFeatureById(targetLayerId, targetFeatureId);
// Check if the feature was found and log the result or handle it accordingly
if (feature) {
console.log(`feature found: ${feature.type}`);
} else {
console.log("No feature found with the specified ID:", targetFeatureId);
}

findFeaturesByIds

This is designed to retrieve all features that are labeled with one or more specified feature IDs. This function accepts one single layer ID and the IDs of features, and returns an array of Feature objects that match the provided layer ID and Feature ID.

Syntax

reearth.layers.findFeaturesByIds: (layerId: string, featureId: string[]) => Feature[] | undefined;

Parameters

layerId

Type string

The unique identifier of the layer that is being searched for within the scene.

featureId

Type string[]

The unique identifier of features in the layer. This allows for flexible input of one or multiple IDs.

Return Value

Type (Feature[] | underined)

Returns an array of Feature objects that have feature IDs found in the specified layer. If no features match the provided IDs, it returns undefined.

Example

// Define an array of layer IDs to be searched
const layerId = "01j90ed9m6bxagb6bvfg4sk49q";
const featureIds = [
"6167fcb5-9564-4c8e-a4d3-d0b419f54ec6",
"abae3164-f8b3-42bb-b194-0379ecc4c653",
];
// Retrieve the layers by their IDs
const features = reearth.layers.findFeaturesByIds(layerId, featureIds);
// Process the results, handling both found and not found cases
features.forEach((feature, index) => {
if (feature) {
console.log(`Feature found: ID = ${feature.id}, Type = ${feature.type}`);
} else {
console.log(`No Feature found for ID: ${feature[index]}`);
}
});

hide

This method is designed to hide one or more layers based on array of layer IDs provided. This function accepts a spread of string arguments, each representing the unique identifier (ID) of a layer. When invoked, this method sets the visibility of each specified layer to false, effectively hiding them from view in the project. This is particularly useful for managing the display of layers dynamically, allowing developers to control which elements are visible to the end user at any given time based on specific conditions or interactions.

Syntax

reearth.layers.hide : (...layerIds: string[]) => void

Parameters

...layerIds

Type ...string[]

A spread of string parameters, where each string is the ID of a layer that needs to be hidden.

Return Value

Type None (void)

The method does not require any input parameters and performs its operation without returning a value.

Example

// Define the IDs of layers to be hidden
const layerIdsToHide = [
"01j1rx8xhxsk2wdydew3m8hr6q",
"01j90ed9m6bxagb6bvfg4sk49q",
];
// Hide the specified layers in the Reearth scene
reearth.layers.hide(...layerIdsToHide);

show

This method is used to set the visibility of specified layers within the reearth scene to true. This function allows users to programmatically control which layers are visible to the user, making it a crucial tool for managing the display of various data sets, features, or graphical elements on the map or scene. It is particularly useful in scenarios where layers need to be dynamically shown or hidden based on user interactions, application states, or specific conditions.

Syntax

reearth.layers.show: (...layerId: string[]) => void;

Parameters

...layerIds

Type ...string[]

A spread of string parameters, where each string is the ID of a layer that needs to be made visible.

Return Value

Type None (void)

The method does not require any input parameters and performs its operation without returning a value.

Example

// Define the IDs of layers to be shown
const layerIdsToShow = [
"01j1rx8xhxsk2wdydew3m8hr6q",
"01j90ed9m6bxagb6bvfg4sk49q",
];
// Show the specified layers in the Reearth scene
reearth.layers.show(...layerIdsToShow);

delete

This method is used to delete specified layers within the reearth scene. This function removes only temporary layers added by the Plugin API. The method takes the ID of the layer as its primary argument.

Syntax

reearth.layers.delete: (...layerId: string[]) => void;

Parameters

...layerIds

Type ...string[]

A spread of string parameters, where each string is the ID of a layer that needs to be made visible.

Return Value

Type None (void)

The method does not require any input parameters and performs its operation without returning a value.

Example

// Define the IDs of layers to be deleted
const layerIdsToDelete = [
"ed5cade3-4049-4626-a4c6-4e84baaef987",
"0cdc12f8-4096-4a3c-84fa-0cc984130559",
];
// Show the specified layers in the Reearth scene
reearth.layers.delete(...layerIdsToDelete);

override

This method dynamically overrides properties for a designated layer identified by its ID. This function can modify the layer properties. The method allows for modifying layer properties on-the-fly, such as visibility, color, or any custom attributes that might have been defined in the layer’s structure. This dynamic manipulation is essential for responsive applications where layer attributes need to change in response to user interactions, data updates, or other application logic, without permanently altering the original layer configuration. This function takes two parameters: the ID of the layer and the partial layer object.

Syntax

reearth.layers.override: (layerId: string, properties: Partial<Layer>) => void;

Parameters

layerId

Type string

The unique identifier of the layer whose property is to be overridden.

properties

Type Partial<Layer>

It represents an object that can optionally include any properties from the Layer type.

Return Value

Type None (void)

The method does not require any input parameters and performs its operation without returning a value.

Example

// add a sample layer
const sampleLayer = {
type: "simple",
data: {
type: "geojson",
value: {
type: "Feature",
geometry: {
type: "Point",
coordinates: [139.6917, 35.6895],
},
},
},
marker: {
style: "image",
imageSize: 1,
imageColor: "blue",
},
};
const layerId = reearth.layers.add(sampleLayer);
// Example to modify the style
// We should hav a big red marker instead of a small blue one
reearth.layers.override(layerId, {
marker: {
imageSize: 5,
imageColor: "red",
},
});

select

This method is used to programmatically select a specific layer within the reearth scene.

Syntax

reearth.layers.select: (layerId?: string) => void;

Parameters

layerId

Type string

The unique identifier of the layer to be selected.

Return Value

Type None (void)

The method does not require any input parameters and performs its operation without returning a value.

Example

// Select a layer by ID
reearth.layers.select("01j1rx8xhxsk2wdydew3m8hr6q");

selectFeature

This method is used to programmatically select a specific feature within the reearth scene. This function is essential for highlighting or focusing on a particular feature, potentially triggering additional UI elements or actions, such as displaying an infobox or other contextual information.

Syntax

reearth.layers.selectFeature: (layerId?: string, featureId?: string) => void;

Parameters

layerId

Type string

The unique identifier of the layer to be selected.

featureId

Type string

The unique identifier of the feature in the layer

Return Value

Type None (void)

The method does not require any input parameters and performs its operation without returning a value.

Example

// Layer ID and feature ID to be selected
const layerId = "01j90ed9m6bxagb6bvfg4sk49q";
const featureId = "6167fcb5-9564-4c8e-a4d3-d0b419f54ec6";
// Select the layer
reearth.layers.selectFeature(layerId, featureId);

selectFeatures

This method is used to programmatically select specific features within the reearth scene. This function is essential for highlighting or focusing on a particular feature, potentially triggering additional UI elements or actions, such as displaying an infobox or other contextual information.

Syntax

reearth.layers.selectFeatures: (targets: { layerId?: string; featureId?: string[] }[]) => void;

Parameters

targets

Type { layerId?: string; featureId?: string[] }[]

  • layerId: string: The unique identifier of the layer to be selected.
  • featureId: string[]: An array of string parameters, where each string is the ID of a feature

Return Value

Type None (void)

The method does not require any input parameters and performs its operation without returning a value.

Example

// add a sample layer
const chiyodaLayerId = reearth.layers.add({
type: "simple",
data: {
type: "3dtiles",
url: "https://assets.cms.plateau.reearth.io/assets/ca/ee4cb0-9ce4-4f6c-bca1-9c7623e84cb1/13100_tokyo23-ku_2022_3dtiles_1_1_op_bldg_13101_chiyoda-ku_lod2_no_texture/tileset.json",
},
["3dtiles"]: {
selectedFeatureColor: "red",
},
});
const chuoLayerId = reearth.layers.add({
type: "simple",
data: {
type: "3dtiles",
url: "https://assets.cms.plateau.reearth.io/assets/4a/30f295-cd07-46b0-b0ab-4a4b1b3af06b/13100_tokyo23-ku_2022_3dtiles_1_1_op_bldg_13102_chuo-ku_lod2_no_texture/tileset.json",
},
["3dtiles"]: {
selectedFeatureColor: "red",
},
});
// NOTE: After 3dtiles been loaded, we can use this to select features
// Select features by layer IDs and feature IDs
reearth.layers.selectFeatures([
{
layerId: chiyodaLayerId,
featureId: [
"f9f2275bcf13a9674ba81473bc129ed6",
"b9a4fd90ca6112eccd43bfffd4aeb2fe",
],
},
{
layerId: chuoLayerId,
featureId: [
"acf77feceabce515700a47021bfe63dc",
"4dcf088a80f1eaaf73b1f356f7446298",
],
},
]);

Events

select

This event is triggered when a layer is selected within the reearth scene. It provides a way to listen for layer selection events and respond to them with custom actions or behaviors.

Syntax

reearth.layers.on('select', (selection: LayerSelection) => void)

Parameters

selection

Type LayerSelection:[layerId: string | undefined, featureId: string | undefined]

  • layerId: string | undefined: The unique identifier of the selected layer.
  • featureId: string | undefined: The unique identifier of the selected feature.

Example

const layerId = reearth.layers.add({
type: "simple",
data: {
type: "geojson",
value: {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: {},
geometry: {
coordinates: [139.97422779688281, 35.74642872517698],
type: "Point",
},
},
],
},
},
marker: {},
});
reearth.camera.lookAt({
lat: 35.74642872517698,
lng: 139.97422779688281,
height: 1000,
});
reearth.layers.on("select", (layerId, featureId) => {
console.log(
`Layer selection: Layer ID: ${layerId}, Feature ID: ${featureId}`
);
});

References

Layer Type

An object that includes all the data and metadata necessary to create and manage a layer.

type Layer = {
id: string; // A unique identifier for the layer.
title?: string;
visible?: boolean; // Flag indicating whether the layer is visible by default. Default is true
infobox?: Infobox<IBP>; // An infobox that can display additional interactive or informational content
type: "simple";
data?: {
type:
| "geojson"
| "3dtiles"
| "osm-buildings"
| "google-photorealistic"
| "czml"
| "csv"
| "wms"
| "mvt"
| "kml"
| "gpx"
| "shapefile"
| "gtfs"
| "gml"
| "georss"
| "gltf"
| "tiles"
| "tms"
| "heatMap";
url?: string; // URL of data source
value?: any;
layers?: string | string[];
jsonProperties?: string[];
isSketchLayer?: boolean;
updateInterval?: number; // milliseconds
parameters?: Record<string, any>;
idProperty?: string;
time?: {
property?: string;
interval?: number; // milliseconds
updateClockOnLoad?: boolean;
};
csv?: {
idColumn?: string | number;
latColumn?: string | number;
lngColumn?: string | number;
heightColumn?: string | number;
noHeader?: boolean;
disableTypeConversion?: boolean;
};
geojson?: {
useAsResource?: boolean;
};
};
properties?: any;
defines?: Record<string, string>;
events?: Events;
layerStyleId?: string;
marker?: MarkerAppearance;
polyline?: PolylineAppearance;
polygon?: PolygonAppearance;
model?: ModelAppearance;
"3dtiles"?: Cesium3DTilesAppearance;
};

LazyLayer Type

A lightweight representation of a layer.

type LazyLayer = Readonly<Layer> & {
computed?: Readonly<ComputedLayer>;
isTempLayer?: boolean;
pluginId?: string;
extensionId?: string;
property?: any;
propertyId?: string;
isVisible?: boolean;
};

ComputedLayer Type

A layer obtained after all processing is completed, containing both original and processed geographic data with applied & evaluated styles and states.

type ComputedLayer = {
id: string;
status: "fetching" | "ready";
layer: Layer;
originalFeatures: Feature[];
features: ComputedFeature[];
properties?: any;
};

Layer Appearance Types

Properties for each layer type.

type MarkerAppearance = {
show?: boolean;
height?: number;
heightReference?: "none" | "clamp" | "relative";
style?: "none" | "point" | "image";
pointSize?: number;
pointColor?: string;
pointOutlineColor?: string;
pointOutlineWidth?: number;
image?: string;
imageSize?: number;
imageSizeInMeters?: boolean;
imageHorizontalOrigin?: "left" | "center" | "right";
imageVerticalOrigin?: "top" | "center" | "baseline" | "bottom";
imageColor?: string;
imageCrop?: "none" | "rounded" | "circle";
imageShadow?: boolean;
imageShadowColor?: string;
imageShadowBlur?: number;
imageShadowPositionX?: number;
imageShadowPositionY?: number;
label?: boolean;
labelText?: string;
labelPosition?:
| "left"
| "right"
| "top"
| "bottom"
| "lefttop"
| "leftbottom"
| "righttop"
| "rightbottom";
labelTypography?: {
fontFamily?: string;
fontSize?: number;
fontWeight?: number;
color?: string;
italic?: boolean;
underline?: boolean;
};
labelBackground?: boolean;
labelBackgroundColor?: string;
labelBackgroundPaddingHorizontal?: number;
labelBackgroundPaddingVertical?: number;
extrude?: boolean;
near?: number; //The unit is meter
far?: number; //The unit is meter
hideIndicator?: boolean;
selectedFeatureColor?: string; // This doesn't support expression
};

Feature Type

An object that includes all the data and metadata necessary to create and manage a feature.

type Feature = {
type: "feature" | "computedFeature";
id: string; // feature ID
geometry?: Geometry;
interval?: [start: Date, end?: Date];
properties?: any;
// Map engine specific information.
metaData?: {
description?: string;
};
range?: DataRange;
};

ComputedFeature Type

A single geographic feature (point, line, polygon, etc.) with all its final evaluated properties and styles applied.

type ComputedFeature = {
type: "computedFeature";
id: string; // feature ID
geometry?: Geometry;
interval?: [start: Date, end?: Date];
properties?: any;
// Map engine specific information.
metaData?: {
description?: string;
};
range?: DataRange;
// AppearanceTypes
marker?: MarkerAppearance;
polyline?: PolylineAppearance;
polygon?: PolygonAppearance;
model?: ModelAppearance;
"3dtiles"?: Cesium3DTilesAppearance;
};