### Initialize and Configure Globe.gl
Source: https://github.com/vasturiano/globe.gl/blob/master/example/countries-population/index.html
Initializes a new Globe instance, sets the base map, configures the initial camera view, and styles the country polygons. Use this for basic globe setup and visual customization.
```javascript
const world = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-dark.jpg')
.pointOfView({ altitude: 4 }, 5000)
.polygonCapColor(feat => 'rgba(200, 0, 0, 0.6)')
.polygonSideColor(() => 'rgba(0, 100, 0, 0.05)')
.polygonLabel(({ properties: d }) => ` ${d.ADMIN} (${d.ISO_A2}) Population: ${Math.round(+d.POP_EST / 1e4) / 1e2}M `);
```
--------------------------------
### Set Background Color
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Set the background color of the globe. This method can be used to get or set the color.
```javascript
backgroundColor([str])
```
--------------------------------
### Initialize and Configure Globe.gl
Source: https://github.com/vasturiano/globe.gl/blob/master/example/airline-routes/us-international-outbound.html
Sets up the Globe instance, configures its visual properties like the globe image, camera perspective, and arc/point styling. Use this to define the base appearance and interaction of the globe.
```javascript
import { csvParseRows } from 'https://esm.sh/d3-dsv'; import indexBy from 'https://esm.sh/index-array-by'; const COUNTRY = 'United States'; const OPACITY = 0.22; const myGlobe = new Globe(document.getElementById('globeViz')) .globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg') .pointOfView({ lat: 39.6, lng: -98.5, altitude: 2 }) .arcLabel(d =>
`${d.airline}: ${d.srcIata} → ${d.dstIata}
`) .arcStartLat(d => +d.srcAirport.lat) .arcStartLng(d => +d.srcAirport.lng) .arcEndLat(d => +d.dstAirport.lat) .arcEndLng(d => +d.dstAirport.lng) .arcDashLength(0.25) .arcDashGap(1) .arcDashInitialGap(() => Math.random()) .arcDashAnimateTime(4000) .arcColor(d =>
[
`rgba(0, 255, 0, ${OPACITY})
`,
`rgba(255, 0, 0, ${OPACITY})
`
]
) .arcsTransitionDuration(0) .pointColor(() => 'orange') .pointAltitude(0) .pointRadius(0.02) .pointsMerge(true);
```
--------------------------------
### Initialize Globe with Country Data and GDP Coloring
Source: https://github.com/vasturiano/globe.gl/blob/master/example/choropleth-countries/index.html
Sets up the Globe instance, loads country data, and applies a color scale based on GDP per capita. Includes hover effects for interactivity. Ensure the 'earth-night.jpg' and 'night-sky.png' are accessible.
```javascript
import { scaleSequentialSqrt } from 'https://esm.sh/d3-scale';
import { interpolateYlOrRd } from 'https://esm.sh/d3-scale-chromatic';
const colorScale = scaleSequentialSqrt(interpolateYlOrRd);
// GDP per capita (avoiding countries with small pop)
const getVal = feat => feat.properties.GDP_MD_EST / Math.max(1e5, feat.properties.POP_EST);
fetch('../datasets/ne_110m_admin_0_countries.geojson')
.then(res => res.json())
.then(countries => {
const maxVal = Math.max(...countries.features.map(getVal));
colorScale.domain([0, maxVal]);
const world = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.backgroundImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/night-sky.png')
.lineHoverPrecision(0)
.polygonsData(countries.features.filter(d => d.properties.ISO_A2 !== 'AQ'))
.polygonAltitude(0.06)
.polygonCapColor(feat => colorScale(getVal(feat)))
.polygonSideColor(() => 'rgba(0, 100, 0, 0.15)')
.polygonStrokeColor(() => '#111')
.polygonLabel(({ properties: d }) =>
` ${d.ADMIN} (${d.ISO_A2}): GDP: ${d.GDP_MD_EST} M$ Population: ${d.POP_EST} `
)
.onPolygonHover(hoverD => world
.polygonAltitude(d => d === hoverD ? 0.12 : 0.06)
.polygonCapColor(d => d === hoverD ? 'steelblue' : colorScale(getVal(d)))
)
.polygonsTransitionDuration(300);
});
```
--------------------------------
### Set Globe Offset
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Position the globe within the canvas by setting an offset from the center. This method can be used to get or set the offset.
```javascript
globeOffset(["[px, px]"])
```
--------------------------------
### Set Custom Globe Material
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Assign a custom Three.js material to the globe for advanced styling. Refer to the provided example for advanced customization techniques.
```javascript
globeMaterial([material])
```
--------------------------------
### Emit Arc and Rings on Globe Click
Source: https://github.com/vasturiano/globe.gl/blob/master/example/emit-arcs-on-click/index.html
Handles clicks on the globe to emit arcs and rings. It adds and removes arcs after a specified flight time and adds/removes rings at the start and end points.
```javascript
let prevCoords = { lat: 0, lng: 0 }; function emitArc({ lat: endLat, lng: endLng }) { const { lat: startLat, lng: startLng } = prevCoords; setTimeout(() => { prevCoords = { lat: endLat, lng: endLng }}, FLIGHT_TIME); // add and remove arc after 1 cycle const arc = { startLat, startLng, endLat, endLng }; globe.arcsData([...globe.arcsData(), arc]); setTimeout(() => globe.arcsData(globe.arcsData().filter(d => d !== arc)), FLIGHT_TIME * 2); // add and remove start rings const srcRing = { lat: startLat, lng: startLng }; globe.ringsData([...globe.ringsData(), srcRing]); setTimeout(() => globe.ringsData(globe.ringsData().filter(r => r !== srcRing)), FLIGHT_TIME * ARC_REL_LEN); // add and remove target rings setTimeout(() => { const targetRing = { lat: endLat, lng: endLng }; globe.ringsData([...globe.ringsData(), targetRing]); setTimeout(() => globe.ringsData(globe.ringsData().filter(r => r !== targetRing)), FLIGHT_TIME * ARC_REL_LEN); }, FLIGHT_TIME); }
```
--------------------------------
### Globe.gl Initialization
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Learn how to initialize a new Globe instance with optional configuration options.
```APIDOC
## Globe.gl Initialization
### Description
Initializes a new Globe instance, optionally configuring its rendering and behavior.
### Method
`new Globe(domElement, configOptions)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
#### `domElement`
- **domElement** (HTMLElement) - Required - The DOM element where the globe canvas will be rendered.
#### `configOptions`
- **rendererConfig** (object) - Optional - Configuration parameters to pass to the [ThreeJS WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer) constructor. Defaults to `{ antialias: true, alpha: true }`.
- **waitForGlobeReady** (boolean) - Optional - Whether to wait until the globe wrapping or background image has been fully loaded before rendering the globe or any of the data layers. Defaults to `true`.
- **animateIn** (boolean) - Optional - Whether to animate the globe initialization, by scaling and rotating the globe into its initial position. Defaults to `true`.
### Request Example
```javascript
const myGlobe = new Globe(myDOMElement, {
waitForGlobeReady: false,
animateIn: false
});
```
### Response
None (returns the Globe instance)
```
--------------------------------
### Initialize and Configure Globe.gl
Source: https://github.com/vasturiano/globe.gl/blob/master/example/airline-routes/highlight-links.html
Initializes the globe visualization and sets up various properties for arcs and points. Includes hover effects for arcs.
```javascript
import { csvParseRows } from 'https://esm.sh/d3-dsv';
import indexBy from 'https://esm.sh/index-array-by';
const COUNTRY = 'Portugal';
const MAP_CENTER = { lat: 37.6, lng: -16.6, altitude: 0.4 };
const OPACITY = 0.3;
const myGlobe = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.arcLabel(d => `${d.airline}: ${d.srcIata} → ${d.dstIata}`)
.arcStartLat(d => d.srcAirport.lat)
.arcStartLng(d => d.srcAirport.lng)
.arcEndLat(d => d.dstAirport.lat)
.arcEndLng(d => d.dstAirport.lng)
.arcColor(d => [`rgba(0, 255, 0, ${OPACITY})`, `rgba(255, 0, 0, ${OPACITY})`])
.arcDashLength(0.4)
.arcDashGap(0.2)
.arcDashAnimateTime(1500)
.onArcHover(hoverArc => myGlobe
.arcColor(d => {
const op = !hoverArc ? OPACITY : d === hoverArc ? 0.9 : OPACITY / 4;
return [`rgba(0, 255, 0, ${op})`, `rgba(255, 0, 0, ${op})`];
}))
.pointColor(() => 'orange')
.pointAltitude(0)
.pointRadius(0.04)
.pointsMerge(true);
```
--------------------------------
### Initialize and Configure Globe.gl
Source: https://github.com/vasturiano/globe.gl/blob/master/example/world-population/index.html
Sets up the Globe instance with various visual properties like globe, bump, and background images. It configures hexbinning for point data, including altitude, resolution, color mapping, and merging. Pointer interactions are disabled for performance.
```javascript
import { csvParse } from 'https://esm.sh/d3-dsv';
import { scaleSequentialSqrt } from 'https://esm.sh/d3-scale';
import { interpolateYlOrRd } from 'https://esm.sh/d3-scale-chromatic';
const weightColor = scaleSequentialSqrt(interpolateYlOrRd)
.domain([0, 1e7]);
const world = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.bumpImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-topology.png')
.backgroundImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/night-sky.png')
.hexBinPointWeight('pop')
.hexAltitude(d => d.sumWeight * 6e-8)
.hexBinResolution(4)
.hexTopColor(d => weightColor(d.sumWeight))
.hexSideColor(d => weightColor(d.sumWeight))
.hexBinMerge(true)
.enablePointerInteraction(false);
```
--------------------------------
### Initialize Globe and Solar Time
Source: https://github.com/vasturiano/globe.gl/blob/master/example/solar-terminator/index.html
Sets up the Globe instance, configures tile data for solar position, and initializes the time animation. Requires the 'three' and 'solar-calculator' libraries.
```javascript
import { MeshLambertMaterial } from 'https://esm.sh/three';
import * as solar from 'https://esm.sh/solar-calculator';
const VELOCITY = 9; // minutes per frame
const sunPosAt = dt => {
const day = new Date(+dt).setUTCHours(0, 0, 0, 0);
const t = solar.century(dt);
const longitude = (day - dt) / 864e5 * 360 - 180;
return [longitude - solar.equationOfTime(t) / 4, solar.declination(t)];
};
let dt = +new Date();
const solarTile = {
pos: sunPosAt(dt)
};
const timeEl = document.getElementById('time');
const world = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-dark.jpg')
.tilesData([solarTile])
.tileLng(d => d.pos[0])
.tileLat(d => d.pos[1])
.tileAltitude(0.005)
.tileWidth(180)
.tileHeight(180)
.tileUseGlobeProjection(false)
.tileMaterial(() => new MeshLambertMaterial({
color: '#ffff00',
opacity: 0.3,
transparent: true
}))
.tilesTransitionDuration(0);
// animate time of day
requestAnimationFrame(() => (
function animate() {
dt += VELOCITY * 60 * 1000;
solarTile.pos = sunPosAt(dt);
world.tilesData([solarTile]);
timeEl.textContent = new Date(dt).toLocaleString();
requestAnimationFrame(animate);
}
)());
```
--------------------------------
### Initialize Globe and Load Satellite Data
Source: https://github.com/vasturiano/globe.gl/blob/master/example/satellites/index.html
Sets up the Globe.gl instance, configures particle visualization, and fetches TLE data from a remote source. Requires the satellite.js library.
```javascript
import * as satellite from 'https://esm.sh/satellite.js';
const EARTH_RADIUS_KM = 6371; // km
const TIME_STEP = 3 * 1000; // per frame
const timeLogger = document.getElementById('time-log');
const world = new Globe(document.getElementById('chart'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-blue-marble.jpg')
.particleLat('lat')
.particleLng('lng')
.particleAltitude('alt')
.particlesColor(() => 'palegreen');
setTimeout(() => world.pointOfView({ altitude: 3.5 }));
fetch('../datasets/space-track-leo.txt').then(r => r.text()).then(rawData => {
const tleData = rawData.replace(/\r/g, '')
.split(/\n(?=[^12])/)
.filter(d => d)
.map(tle => tle.split('\n'));
const satData = tleData.map(([name, ...tle]) => ({
satrec: satellite.twoline2satrec(...tle),
name: name.trim().replace(/^0 /, '')
})) // exclude those that can't be propagated
.filter(d => !!satellite.propagate(d.satrec, new Date())?.position);
```
--------------------------------
### Initialize Globe and Configure Paths
Source: https://github.com/vasturiano/globe.gl/blob/master/example/random-paths/index.html
Initializes a new Globe instance and configures its visual properties, including background and topology images, path data, color, dash length, gap, and animation time. Paths are configured to be visible after a delay.
```javascript
const globe = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-dark.jpg')
.bumpImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-topology.png')
.pathsData(gData)
.pathColor(() => ['rgba(0,0,255,0.6)', 'rgba(255,0,0,0.6)'])
.pathDashLength(0.01)
.pathDashGap(0.004)
.pathDashAnimateTime(100000);
```
```javascript
setTimeout(() => {
globe
.pathPointAlt(pnt => pnt[2]) // set altitude accessor
.pathTransitionDuration(4000);
}, 6000);
```
--------------------------------
### Initialize Globe and Fetch Data
Source: https://github.com/vasturiano/globe.gl/blob/master/example/earthquakes/index.html
Sets up the Globe.gl instance, configures earthquake data mapping, and fetches data from a GeoJSON feed. Requires the Globe.gl library and D3.js for color scaling.
```javascript
import { scaleLinear } from 'https://esm.sh/d3-scale';
const weightColor = scaleLinear()
.domain([0, 60])
.range(['lightblue', 'darkred'])
.clamp(true);
const myGlobe = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.hexBinPointLat(d => d.geometry.coordinates[1])
.hexBinPointLng(d => d.geometry.coordinates[0])
.hexBinPointWeight(d => d.properties.mag)
.hexAltitude(({ sumWeight }) => sumWeight * 0.0025)
.hexTopColor(d => weightColor(d.sumWeight))
.hexSideColor(d => weightColor(d.sumWeight))
.hexLabel(d => ` ${d.points.length} earthquakes in the past month:
${d.points.slice().sort((a, b) => b.properties.mag - a.properties.mag).map(d => d.properties.title).join('
')}
`);
fetch('//earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson')
.then(res => res.json())
.then(equakes => {
myGlobe.hexBinPointsData(equakes.features);
});
```
--------------------------------
### Initialize Globe.gl with Custom Tile Source
Source: https://github.com/vasturiano/globe.gl/blob/master/example/tile-engine/index.html
Instantiate a new Globe object and configure it to use a custom tile source URL. Ensure the target element exists in the DOM.
```javascript
body { margin: 0; }
new Globe(document.getElementById('globeViz'))
.globeTileEngineUrl((x, y, l) => `https://tile.openstreetmap.org/${l}/${x}/${y}.png`);
```
--------------------------------
### Initialize and Configure Globe
Source: https://github.com/vasturiano/globe.gl/blob/master/example/emit-arcs-on-click/index.html
Sets up the globe visualization with an Earth image, defines arc and ring properties, and configures transition durations.
```javascript
const ARC_REL_LEN = 0.4; // relative to whole arc const FLIGHT_TIME = 1000; const NUM_RINGS = 3; const RINGS_MAX_R = 5; // deg const RING_PROPAGATION_SPEED = 5; // deg/sec const globe = new Globe(document.getElementById('globeViz')) .globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg') .arcColor(() => 'darkOrange') .onGlobeClick(emitArc) .arcDashLength(ARC_REL_LEN) .arcDashGap(2) .arcDashInitialGap(1) .arcDashAnimateTime(FLIGHT_TIME) .arcsTransitionDuration(0) .ringColor(() => t => `rgba(255,100,50,${1-t})`) .ringMaxRadius(RINGS_MAX_R) .ringPropagationSpeed(RING_PROPAGATION_SPEED) .ringRepeatPeriod(FLIGHT_TIME * ARC_REL_LEN / NUM_RINGS);
```
--------------------------------
### Initialize Globe and Add Animated Spheres
Source: https://github.com/vasturiano/globe.gl/blob/master/example/custom-layer/index.html
Initializes a globe visualization with custom spherical data points that are animated to move across the globe. Requires Three.js and the globe.gl library.
```javascript
import * as THREE from 'https://esm.sh/three';
// Gen random data
const N = 300;
const gData = [...Array(N).keys()].map(() => ({
lat: (Math.random() - 0.5) * 180,
lng: (Math.random() - 0.5) * 360,
alt: Math.random() * 0.8 + 0.1,
radius: Math.random() * 5,
color: ['red', 'white', 'blue', 'green'][Math.round(Math.random() * 3)]
}));
const world = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-blue-marble.jpg')
.bumpImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-topology.png')
.pointOfView({ altitude: 3.5 })
.customLayerData(gData)
.customThreeObject(d => new THREE.Mesh(
new THREE.SphereGeometry(d.radius),
new THREE.MeshLambertMaterial({ color: d.color })
))
.customThreeObjectUpdate((obj, d) => {
Object.assign(obj.position, world.getCoords(d.lat, d.lng, d.alt));
});
(function moveSpheres() {
gData.forEach(d => d.lat += 0.2);
world.customLayerData(world.customLayerData());
requestAnimationFrame(moveSpheres);
})();
```
--------------------------------
### Initialize Globe and Load Cable Data
Source: https://github.com/vasturiano/globe.gl/blob/master/example/submarine-cables/index.html
Initializes the Globe.gl instance with various image layers and then fetches submarine cable data from a remote API. Configure the globe with image URLs for the globe, topology, and background.
```javascript
const globe = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-dark.jpg')
.bumpImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-topology.png')
.backgroundImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/night-sky.png');
fetch('//http-proxy.vastur.com?url=https://www.submarinecablemap.com/api/v3/cable/cable-geo.json')
.then(r => r.json())
.then(cablesGeo => {
let cablePaths = [];
cablesGeo.features.forEach(({ geometry, properties }) => {
geometry.coordinates.forEach(coords => cablePaths.push({ coords, properties }));
});
globe
.pathsData(cablePaths)
.pathPoints('coords')
.pathPointLat(p => p[1])
.pathPointLng(p => p[0])
.pathColor(path => path.properties.color)
.pathLabel(path => path.properties.name)
.pathDashLength(0.1)
.pathDashGap(0.008)
.pathDashAnimateTime(12000);
});
```
--------------------------------
### Initialize and Configure Globe.gl for Moon
Source: https://github.com/vasturiano/globe.gl/blob/master/example/moon-landing-sites/index.html
Sets up the Globe.gl instance with moon-specific textures, graticules, and label configurations. Use this to create a 3D representation of the moon with landing site data.
```javascript
import { scaleOrdinal } from 'https://esm.sh/d3-scale';
const colorScale = scaleOrdinal(['orangered', 'mediumblue', 'darkgreen', 'yellow']);
const labelsTopOrientation = new Set(['Apollo 12', 'Luna 2', 'Luna 20', 'Luna 21', 'Luna 24', 'LCROSS Probe']); // avoid label collisions
const moon = new Globe(document.getElementById('globeViz'))
.globeImageUrl('./lunar_surface.jpg')
.bumpImageUrl('./lunar_bumpmap.jpg')
.backgroundImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/night-sky.png')
.showGraticules(true)
.showAtmosphere(false) // moon has no atmosphere
.labelText('label')
.labelSize(1.7)
.labelDotRadius(0.4)
.labelDotOrientation(d => labelsTopOrientation.has(d.label) ? 'top' : 'bottom')
.labelColor(d => colorScale(d.agency))
.labelLabel(d => `
${d.label}
${d.agency} - ${d.program} Program
Landing on ${new Date(d.date).toLocaleDateString()}
`)
.onLabelClick(d => window.open(d.url, '_blank'));
```
--------------------------------
### Initialize Globe and Display Volcano Heatmap
Source: https://github.com/vasturiano/globe.gl/blob/master/example/volcanoes-heatmap/index.html
Initializes a Globe instance, sets the globe image, configures heatmap properties based on volcano data (latitude, longitude, elevation), and fetches data from a JSON file to render the heatmap.
```javascript
const world = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-blue-marble.jpg')
.heatmapPointLat('lat')
.heatmapPointLng('lon')
.heatmapPointWeight(d => d.elevation * 5e-5)
.heatmapTopAltitude(0.2)
.heatmapBandwidth(1.35)
.heatmapColorSaturation(3.2)
.enablePointerInteraction(false);
fetch('../datasets/world_volcanoes.json').then(res => res.json()).then(volcanoes => {
world.heatmapsData([volcanoes])
});
```
--------------------------------
### Initialize and Configure Globe with Rings
Source: https://github.com/vasturiano/globe.gl/blob/master/example/earth-shield/index.html
Initializes a Globe instance with an Earth night map and configures a shield ring. Ensure the 'globeViz' element exists in your HTML.
```javascript
const shieldRing = { lat: 90, lng: 0 };
const globe = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.ringsData([
shieldRing
])
.ringAltitude(0.25)
.ringColor(() => 'lightblue')
.ringMaxRadius(180)
.ringPropagationSpeed(20)
.ringRepeatPeriod(200);
```
--------------------------------
### Initialize Globe and Load World Data
Source: https://github.com/vasturiano/globe.gl/blob/master/example/hollow-globe/index.html
Initializes a globe instance and fetches world land data. The data is then processed using TopoJSON and rendered as polygons on the globe with a specified material.
```javascript
body { margin: 0; }
import { MeshLambertMaterial, DoubleSide } from 'https://esm.sh/three'; import * as topojson from 'https://esm.sh/topojson-client'; const world = new Globe(document.getElementById('globeViz')) .backgroundColor('rgba(0,0,0,0)') .showGlobe(false) .showAtmosphere(false);
fetch('//cdn.jsdelivr.net/npm/world-atlas/land-110m.json').then(res => res.json())
.then(landTopo => {
world .polygonsData(topojson.feature(landTopo, landTopo.objects.land).features)
.polygonCapMaterial(new MeshLambertMaterial({ color: 'darkslategrey', side: DoubleSide }))
.polygonSideColor(() => 'rgba(0,0,0,0)');
});
```
--------------------------------
### Initialize Globe with HTML Elements
Source: https://github.com/vasturiano/globe.gl/blob/master/example/html-markers/index.html
Initializes a new Globe instance and configures it to display HTML elements as markers. Requires an HTML element with id 'globeViz' to render the globe. The `htmlElement` function defines how each marker is rendered, and `htmlElementVisibilityModifier` controls their visibility.
```javascript
const markerSvg = ``; // Gen random data const N = 30; const gData = [...Array(N).keys()].map(() => ({ lat: (Math.random() - 0.5) * 180, lng: (Math.random() - 0.5) * 360, size: 7 + Math.random() * 30, color: ['red', 'white', 'blue', 'green'][Math.round(Math.random() * 3)] })); new Globe(document.getElementById('globeViz')) .globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-dark.jpg') .htmlElementsData(gData) .htmlElement(d => { const el = document.createElement('div'); el.innerHTML = markerSvg; el.style.color = d.color; el.style.width = `${d.size}px`; el.style.transition = 'opacity 250ms'; el.style['pointer-events'] = 'auto'; el.style.cursor = 'pointer'; el.onclick = () => console.info(d); return el; }) .htmlElementVisibilityModifier((el, isVisible) => el.style.opacity = isVisible ? 1 : 0);
```
--------------------------------
### Initialize Globe Instance
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Create a new Globe instance, passing the DOM element where the globe will be rendered. You can chain methods to configure the globe's appearance and data.
```javascript
const myGlobe = new Globe(myDOMElement)
.globeImageUrl(myImageUrl)
.pointsData(myData);
```
--------------------------------
### Initialize and Configure Globe.gl with Volcano Data
Source: https://github.com/vasturiano/globe.gl/blob/master/example/volcanoes/index.html
This code initializes the Globe.gl instance, sets background and earth images, configures point and label properties, and fetches and displays volcano data. Ensure the 'globeViz' element exists in your HTML.
```javascript
import { scaleOrdinal } from 'https://esm.sh/d3-scale';
import { schemeCategory10 } from 'https://esm.sh/d3-scale-chromatic';
import { transparentize } from 'https://esm.sh/polished';
const catColor = scaleOrdinal(schemeCategory10.map(col => transparentize(0.2, col)));
const getAlt = d => d.elevation * 5e-5;
const getTooltip = d =>
`
${d.name}, ${d.country}
(${d.type})
Elevation: ${d.elevation}m
`;
const myGlobe = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.backgroundImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/night-sky.png')
.pointLat('lat')
.pointLng('lon')
.pointAltitude(getAlt)
.pointRadius(0.12)
.pointColor(d => catColor(d.type))
.pointLabel(getTooltip)
.labelLat('lat')
.labelLng('lon')
.labelAltitude(d => getAlt(d) + 1e-6)
.labelDotRadius(0.12)
.labelDotOrientation(() => 'bottom')
.labelColor(d => catColor(d.type))
.labelText('name')
.labelSize(0.15)
.labelResolution(1)
.labelLabel(getTooltip);
fetch('../datasets/world_volcanoes.json').then(res => res.json()).then(volcanoes => {
myGlobe.pointsData(volcanoes)
.labelsData(volcanoes);
});
```
--------------------------------
### Initialize Globe with Random Points
Source: https://github.com/vasturiano/globe.gl/blob/master/example/basic/index.html
This code initializes a Globe.gl instance, sets a background image, and populates it with randomly generated data points. Ensure the 'globeViz' element exists in your HTML.
```javascript
body { margin: 0; }
// Gen random data const N = 300;
const gData = [...Array(N).keys()].map(() => ({
lat: (Math.random() - 0.5) * 180,
lng: (Math.random() - 0.5) * 360,
size: Math.random() / 3,
color: ['red', 'white', 'blue', 'green'][Math.round(Math.random() * 3)]
}));
new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.pointsData(gData)
.pointAltitude('size')
.pointColor('color');
```
--------------------------------
### Initialize Globe with Populated Places Data
Source: https://github.com/vasturiano/globe.gl/blob/master/example/world-cities/index.html
Initializes a new Globe instance and loads populated places data from a GeoJSON file. Configures globe and background images, and sets properties for displaying labels such as latitude, longitude, name, size, color, and resolution. Use this to visualize geographical points with associated data.
```javascript
body { margin: 0; }
fetch('../datasets/ne_110m_populated_places_simple.geojson').then(res => res.json()).then(places => { new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.backgroundImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/night-sky.png')
.labelsData(places.features)
.labelLat(d => d.properties.latitude)
.labelLng(d => d.properties.longitude)
.labelText(d => d.properties.name)
.labelSize(d => Math.sqrt(d.properties.pop_max) * 4e-4)
.labelDotRadius(d => Math.sqrt(d.properties.pop_max) * 4e-4)
.labelColor(() => 'rgba(255, 165, 0, 0.75)')
.labelResolution(2); });
```
--------------------------------
### Initialize Globe with Rings Data
Source: https://github.com/vasturiano/globe.gl/blob/master/example/random-rings/index.html
Initializes a Globe.gl instance, sets the globe's background image, and configures rings with custom data and visual properties. Ensure the 'globeViz' element exists in your HTML.
```javascript
const N = 10;
const gData = [...Array(N).keys()].map(() => ({
lat: (Math.random() - 0.5) * 180,
lng: (Math.random() - 0.5) * 360,
maxR: Math.random() * 20 + 3,
propagationSpeed: (Math.random() - 0.5) * 20 + 1,
repeatPeriod: Math.random() * 2000 + 200
}));
const colorInterpolator = t => `rgba(255,100,50,${Math.sqrt(1-t)})`;
const globe = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.ringsData(gData)
.ringColor(() => colorInterpolator)
.ringMaxRadius('maxR')
.ringPropagationSpeed('propagationSpeed')
.ringRepeatPeriod('repeatPeriod');
```
--------------------------------
### Globe Initialization Configuration
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
When initializing a Globe instance, you can provide configuration options. These options control aspects like the WebGL renderer, animation, and initial loading behavior.
```javascript
new Globe(, { configOptions })
```
--------------------------------
### Initialize Globe and Display Arcs
Source: https://github.com/vasturiano/globe.gl/blob/master/example/random-arcs/index.html
This code initializes a new Globe instance, sets the globe's texture, and configures animated arcs with random properties. Ensure the 'globeViz' element exists in your HTML.
```javascript
const N = 20;
const arcsData = [...Array(N).keys()].map(() => ({
startLat: (Math.random() - 0.5) * 180,
startLng: (Math.random() - 0.5) * 360,
endLat: (Math.random() - 0.5) * 180,
endLng: (Math.random() - 0.5) * 360,
color: [['red', 'white', 'blue', 'green'][Math.round(Math.random() * 3)], ['red', 'white', 'blue', 'green'][Math.round(Math.random() * 3)]]
}));
new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg')
.arcsData(arcsData)
.arcColor('color')
.arcDashLength(() => Math.random())
.arcDashGap(() => Math.random())
.arcDashAnimateTime(() => Math.random() * 4000 + 500);
```
--------------------------------
### Initialize Globe with Heatmap Data
Source: https://github.com/vasturiano/globe.gl/blob/master/example/population-heatmap/index.html
Initializes a globe visualization and configures it to display a heatmap based on population data. Ensure the 'globeViz' element exists in your HTML. The heatmap bandwidth and color saturation can be adjusted for visual tuning.
```javascript
body { margin: 0; }
import { csvParse } from 'https://esm.sh/d3-dsv'; const world = new Globe(document.getElementById('globeViz')) .globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-night.jpg') .heatmapPointLat('lat') .heatmapPointLng('lng') .heatmapPointWeight('pop') .heatmapBandwidth(0.9) .heatmapColorSaturation(2.8) .enablePointerInteraction(false); fetch('../datasets/world_population.csv').then(res => res.text()) .then(csv => csvParse(csv, ({ lat, lng, pop }) => ({ lat: +lat, lng: +lng, pop: +pop }))) .then(data => world.heatmapsData([data]));
```
--------------------------------
### Initialize Globe with Textures
Source: https://github.com/vasturiano/globe.gl/blob/master/example/clouds/index.html
Initializes a new Globe instance and sets the globe and bump map textures. Ensure the target element exists and textures are accessible.
```javascript
import * as THREE from 'https://esm.sh/three';
const world = new Globe(document.getElementById('globeViz'), {
animateIn: false
})
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-blue-marble.jpg')
.bumpImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-topology.png');
```
--------------------------------
### Initialize Globe with Heatmap Data
Source: https://github.com/vasturiano/globe.gl/blob/master/example/heatmap/index.html
This code initializes a Globe instance, sets the globe image, and configures heatmap data with latitude, longitude, and weight properties. It also sets heatmap altitude and transition duration, and disables pointer interaction.
```javascript
body { margin: 0; }
// Gen random data const N = 900;
const gData = [...Array(N).keys()].map(() => ({
lat: (Math.random() - 0.5) * 160,
lng: (Math.random() - 0.5) * 360,
weight: Math.random()
}));
const world = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-dark.jpg')
.heatmapsData([gData])
.heatmapPointLat('lat')
.heatmapPointLng('lng')
.heatmapPointWeight('weight')
.heatmapTopAltitude(0.7)
.heatmapsTransitionDuration(3000)
.enablePointerInteraction(false);
```
--------------------------------
### Globe Ready Callback
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Register a callback function that executes once the globe has been fully initialized and rendered in the scene.
```javascript
onGlobeReady(fn)
```
--------------------------------
### Initialize Globe with Custom Materials
Source: https://github.com/vasturiano/globe.gl/blob/master/example/custom-globe-styling/index.html
Initializes a globe instance and applies custom textures for the globe, bump map, and background. It also demonstrates how to modify globe material properties like bump scale, specular map, color, and shininess. Ensure the THREE library is imported.
```javascript
import * as THREE from 'https://esm.sh/three';
const world = new Globe(document.getElementById('globeViz'))
.globeImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-blue-marble.jpg')
.bumpImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-topology.png')
.backgroundImageUrl('//cdn.jsdelivr.net/npm/three-globe/example/img/night-sky.png');
// custom globe material
const globeMaterial = world.globeMaterial();
globeMaterial.bumpScale = 10;
new THREE.TextureLoader().load('//cdn.jsdelivr.net/npm/three-globe/example/img/earth-water.png', texture => {
globeMaterial.specularMap = texture;
globeMaterial.specular = new THREE.Color('grey');
globeMaterial.shininess = 15;
});
const directionalLight = world.lights().find(light => light.type === 'DirectionalLight');
directionalLight && directionalLight.position.set(1, 1, 1);
```
--------------------------------
### Utility Methods
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
A collection of utility methods for coordinate system conversions and retrieving globe properties.
```APIDOC
## Utility Methods
### getGlobeRadius()
#### Description
Returns the cartesian distance of a globe radius in absolute spatial units.
### getCoords(lat, lng [,altitude])
#### Description
Utility method to translate spherical coordinates to cartesian. Given a pair of latitude/longitude coordinates and optionally altitude (in terms of globe radius units), returns the equivalent `{x, y, z}` cartesian spatial coordinates.
### getScreenCoords(lat, lng [,altitude])
#### Description
Utility method to translate spherical coordinates to the viewport domain. Given a pair of latitude/longitude coordinates and optionally altitude (in terms of globe radius units), returns the current equivalent `{x, y}` in viewport coordinates.
### toGeoCoords({ x, y, z })
#### Description
Utility method to translate cartesian coordinates to the geographic domain. Given a set of 3D cartesian coordinates `{x, y, z}`, returns the equivalent `{lat, lng, altitude}` spherical coordinates. Altitude is defined in terms of globe radius units.
### toGlobeCoords(x, y)
#### Description
Utility method to translate viewport coordinates to the globe surface coordinates directly under the specified viewport pixel. Returns the globe coordinates in the format `{ lat, lng }`, or `null` if the globe does not currently intersect with that viewport location.
```
--------------------------------
### Globe Event Callbacks
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Define callback functions for globe initialization and user interactions like clicks.
```APIDOC
## Globe Event Callbacks
### Description
Define callback functions for globe initialization and user interactions like clicks.
### Methods
- **onGlobeReady(fn)**: Callback function to invoke immediately after the globe has been initialized and visible on the scene.
- **onGlobeClick(fn)**: Callback function for (left-button) clicks on the globe. The clicked globe coordinates and the event object are included as arguments: `onGlobeClick({ lat, lng }, event)`.
- **onGlobeRightClick(fn)**: Callback function for right-clicks on the globe. The clicked globe coordinates and the event object are included as arguments: `onGlobeRightClick({ lat, lng }, event)`.
```
--------------------------------
### Tile Interaction Events
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Event handlers for user interactions with tiles.
```APIDOC
## Tile Interaction Events
### Description
Event handlers for user interactions with tiles.
### Methods
- **onTileClick**(`fn`)
Callback function for tile (left-button) clicks. The tile object, the event object and the clicked coordinates are included as arguments: `onTileClick(tile, event, { lat, lng, altitude })`.
- **onTileRightClick**(`fn`)
Callback function for tile right-clicks. The tile object, the event object and the clicked coordinates are included as arguments: `onTileRightClick(tile, event, { lat, lng, altitude })`.
- **onTileHover**(`fn`)
Callback function for tile mouse over events. The tile object (or `null` if there's no tile under the mouse line of sight) is included as the first argument, and the previous tile object (or `null`) as second argument: `onTileHover(tile, prevTile)`.
```
--------------------------------
### Rings Layer Configuration
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Configure the appearance and behavior of the animated ripple rings.
```APIDOC
## Rings Layer Configuration
### Description
This section details the configuration options for the rings layer, allowing customization of data, position, color, size, speed, and repetition of the animated ripple rings.
### Methods & Properties
- **ringsData**([`array`])
- Getter/setter for the list of self-propagating ripple rings. Each data point is displayed as an animated set of concentric circles.
- Default: `[]`
- **ringLat**([`num`, `str` or `fn`])
- Accessor for each circle's center latitude coordinate.
- Default: `lat`
- **ringLng**([`num`, `str` or `fn`])
- Accessor for each circle's center longitude coordinate.
- Default: `lng`
- **ringAltitude**([`num`, `str` or `fn`])
- Accessor for the circle's altitude in terms of globe radius units.
- Default: `0.0015`
- **ringColor**([`str`, `[str, ...]` or `fn`])
- Accessor for the stroke color of each ring. Supports radial color gradients or a color interpolator function.
- Default: `() => '#ffffaa'`
- **ringResolution**([`num`])
- Getter/setter for the geometric resolution of each circle (number of slice segments).
- Default: `64`
- **ringMaxRadius**([`num`, `str` or `fn`])
- Accessor for the maximum outer radius of the circles in angular degrees.
- Default: `2`
- **ringPropagationSpeed**([`num`, `str` or `fn`])
- Accessor for the propagation velocity of the rings in degrees/second. Negative values invert the direction.
- Default: `1`
- **ringRepeatPeriod**([`num`, `str` or `fn`])
- Accessor for the interval (in ms) between consecutive auto-generated concentric circles. `0` or less disables repetition.
- Default: `700`
### Example Usage
```javascript
// Assuming 'globe' is an instance of Globe
globe.ringsData([
{ lat: 40, lng: -74, maxRadius: 3, propagationSpeed: 0.5, color: 'red' },
{ lat: 30, lng: 10, maxRadius: 2, propagationSpeed: -0.2, color: ['yellow', 'blue'] }
])
.ringMaxRadius(d => d.maxRadius)
.ringPropagationSpeed(d => d.propagationSpeed)
.ringColor(d => d.color);
```
```
--------------------------------
### Import Globe.gl Library
Source: https://github.com/vasturiano/globe.gl/blob/master/README.md
Import the Globe.gl library for use in your project. This can be done using ES6 imports or a script tag.
```javascript
import Globe from 'globe.gl';
```
```html
```