globe.gl

repository·master·Indexed 25 days ago

https://github.com/vasturiano/globe.gl

A high-level web component for 3D data visualization on a spherical globe, acting as a wrapper around the three-globe plugin using ThreeJS and WebGL. It supports multiple data layers including points, arcs, polygons, paths, heatmaps (using Gaussian KDE), and Hex Bin Maps (using H3 tessellation), with built-in support for custom textures, atmosphere effects, and interactive event handling.

Tokens
11.5K
Snippets
3
Records
37
Agent score
83%

What's inside globe.gl

  1. Quick start with Globe.GL

    master

    Globe.GL is a web component for visualizing data layers on a 3D globe using a spherical projection. It is a convenience wrapper around three-globe and uses ThreeJS/WebGL for rendering.

    You can use it via ESM import or a script tag.

    import Globe from 'globe.gl';
    
    // Or using a script tag in HTML:
    // <script src="//cdn.jsdelivr.net/npm/globe.gl"></script>
    
    const myGlobe = new Globe(myDOMElement)
      .globeImageUrl(myImageUrl)
      .pointsData(myData);
  2. Configure the Tiles Layer

    master

    The Tiles Layer represents data as spherical surface segments (tiles) on the globe. Use these methods to define the geometry, appearance, and interaction of the tiles.

    Key Methods:

    • tilesData([array]): Sets the list of tiles to display.
    • tileLat, tileLng, tileAltitude: Accessors for the segment's centroid coordinates and altitude (in globe radius units).
    • tileWidth, tileHeight: Accessors for the segment's dimensions in angular degrees.
    • tileMaterial([material, str, or fn]): Sets the ThreeJS material used to style the surface.
    • tileCurvatureResolution(num): Sets the resolution of the surface curvature (higher is smoother but more expensive).
    • tilesTransitionDuration(num): Sets the duration (ms) for animating tile changes.

    Interactions:

    • onTileClick(fn): Callback with (tile, event, { lat, lng, altitude }).
    • onTileRightClick(fn): Callback with (tile, event, { lat, lng, altitude }).
    • onTileHover(fn): Callback with (tile, prevTile).
  3. Configure the Paths Layer

    master

    The Paths Layer allows you to represent lines connecting coordinate pairs on the globe. You can customize the appearance, animation, and interaction of these paths.

    Key Configuration Methods:

    • pathsData([array]): Sets the list of path objects.
    • pathPoints([array, str, or fn]): Defines the set of points for each path. Defaults to [lat, lng] arrays.
    • pathPointLat, pathPointLng, pathPointAlt: Accessors for latitude, longitude, and altitude (in globe radius units).
    • pathColor([str, [str, ...], or fn]): Sets the line color. Supports gradients via color arrays or interpolator functions.
    • pathStroke([num, str, or fn]): Sets the line diameter. If null or undefined, it uses a standard ThreeJS Line (constant 1px width). Otherwise, it uses FatLine for thickness that responds to camera distance.
    • pathDashLength, pathDashGap, pathDashInitialGap: Controls dashed line patterns as relative lengths (0 to 1).
    • pathDashAnimateTime([num]): Animates the dash motion in milliseconds.
    • pathResolution([num]): Sets angular resolution for curvature interpolation. Lower values are smoother but more expensive.

    Path Interactions:

    • onPathClick(path, event, { lat, lng, altitude })
    • onPathRightClick(path, event, { lat, lng, altitude })
    • onPathHover(path, prevPath)
  4. Configure the Hex Bin Map Layer

    master

    The Hex Bin Map layer aggregates points into hexagonal prisms using H3 tessellation. You can provide a dataset via hexBinPointsData and customize the appearance and behavior of the hexagons.

    Key Configuration Options:

    • Data & Resolution: Use hexBinPointsData for the point array and hexBinResolution (0-15) to set the H3 geographic binning resolution. Default resolution is 4.
    • Coordinates & Weight: Specify latitude via hexBinPointLat, longitude via hexBinPointLng, and weight via hexBinPointWeight. Weights determine the default altitude.
    • Visuals:
      • hexAltitude: Set altitude in globe radius units (0 to 1). Supports an accessor function: ({ sumWeight }) => ....
      • hexMargin: Set radial margin (0 to 1) to create gaps between hexagons.
      • hexTopColor / hexSideColor: Accessor functions for hexagon colors.
      • hexTopCurvatureResolution: Controls the smoothness of the top surface curvature.
    • Performance & Animation:
      • hexBinMerge: Set to true to merge meshes into a single ThreeJS object for better performance (note: this disables interactive callbacks).
      • hexTransitionDuration: Duration (ms) for animating geometry changes. Only works if hexBinMerge is false.
  5. Configure the Labels Layer

    master

    The Labels Layer allows you to render text labels on the globe. You can control their position, appearance, and interactivity using the following methods:

    • labelsData([array]): Set the list of label objects.
    • labelLat([num, str, or fn]): Set the latitude accessor (default: 'lat').
    • labelLng([num, str, or fn]): Set the longitude accessor (default: 'lng').
    • labelText([str, or fn]): Set the text content accessor (default: 'text').
    • labelLabel([str, or fn]): Set the tooltip label accessor (supports plain text, HTML, or HTMLElement).
    • labelColor([str, or fn]): Set the color accessor (default: () => 'lightgrey').
    • labelAltitude([num, str, or fn]): Set the altitude in globe radius units (default: 0.002).
    • labelSize([num, str, or fn]): Set the text height in angular degrees (default: 0.5).
    • labelTypeFace([typeface]): Set the typeface JSON object (Facetype.js compatible).
    • labelRotation([num, str, or fn]): Set rotation in degrees clockwise along the latitude parallel plane.
    • labelIncludeDot([bool, str, or fn]): Whether to include a dot marker at the exact coordinates (default: true).
    • labelDotOrientation([str, or fn]): Orientation of the dot if present ('right', 'top', or 'bottom').
    • labelsTransitionDuration([num]): Duration in ms for animating position changes (default: 1000).

    Interactivity:

    • onLabelClick(fn): Callback with (label, event, { lat, lng, altitude }).
    • onLabelRightClick(fn): Callback with (label, event, { lat, lng, altitude }).
    • onLabelHover(fn): Callback with (label, prevlabel).
  6. Handle Arc Events

    master

    You can attach callback functions to respond to user interactions with arcs:

    • onArcClick(fn): Triggered on left-button click. Arguments: (arc, event, { lat, lng, altitude }).
    • onArcRightClick(fn): Triggered on right-button click. Arguments: (arc, event, { lat, lng, altitude }).
    • onArcHover(fn): Triggered on mouseover. Arguments: (arc, prevArc) (where arc is the current object and prevArc is the previous one, both can be null).
  7. Configure the Hexed Polygons Layer

    master

    The Hexed Polygons layer represents polygon shapes as a tessellated group of hexagons. This is useful for visualizing geographic boundaries.

    Key Configuration Options:

    • Data & Geometry: Provide shapes via hexPolygonsData. Use hexPolygonGeoJsonGeometry to specify the GeoJson geometry (supports Polygon and MultiPolygon).
    • Resolution:
      • hexPolygonResolution: H3 geographic binning resolution (0-15).
      • hexPolygonCurvatureResolution: Smoothness of the polygon hexes surface curvature.
      • hexPolygonDotResolution: Smoothness of circular dots if using dot mode.
    • Visuals:
      • hexPolygonColor: Color of each hexagon.
      • hexPolygonAltitude: Altitude in globe radius units.
      • hexPolygonMargin: Radial margin (0 to 1) to create gaps between hexagons.
      • hexPolygonUseDots: Boolean to represent points as circular dots instead of hexagons.
    • Animation: hexPolygonsTransitionDuration (ms) animates altitude and margin changes.
  8. Configure pointer interactions and hover effects

    master

    Globe.GL provides several methods to control how users interact with objects via the mouse:

    • enablePointerInteraction([boolean]): Enables/disables mouse tracking. Disabling this can improve performance but prevents object hover/click and tooltips. Defaults to true.
    • pointerEventsFilter([fn]): A filter function (obj, data) => boolean that determines if an object can be the target of pointer events. This allows passing events through certain layers to deeper objects.
    • lineHoverPrecision([num]): Sets the precision for detecting hover events over Line and Points objects (e.g., arcs or particles). Defaults to 0.2.
    • showPointerCursor(boolean | fn): Controls whether the pointer cursor appears when hovering over clickable parts. Can accept a boolean or a callback (obj) => boolean.
  9. Configure the Globe Layer

    master

    Methods to control the appearance and behavior of the globe surface itself.

    MethodDescriptionDefault
    globeImageUrl(url)URL of the equirectangular image used to wrap the globe.null
    bumpImageUrl(url)URL of the equirectangular image used as a bump map for terrain.null
    globeTileEngineUrl(fn(x, y, l))Function returning a URL string for slippy map tiles. Arguments: x, y, l (zoom).-
    globeTileEngineClearCache()Clears the tile engine cache.-
    showGlobe(boolean)Whether to show the globe surface.true
    showGraticules(boolean)Whether to show a latitude/longitude grid every 10 degrees.false
    showAtmosphere(boolean)Whether to show a bright halo around the globe.true
    atmosphereColor(str)Color of the atmosphere.lightskyblue
    atmosphereAltitude(str)Max altitude of the atmosphere in globe radius units.0.15
    globeCurvatureResolution(number)Resolution of sphere curvature (finer = smoother but slower).4
    globeMaterial(material)ThreeJS material used to wrap the globe.MeshPhongMaterial
    onGlobeReady(fn)Callback invoked after the globe is initialized and visible.-
    onGlobeClick(fn)Callback for left-clicks. Args: { lat, lng }, event.-
    onGlobeRightClick(fn)Callback for right-clicks. Args: { lat, lng }, event.-
  10. Initialize a Globe instance

    master

    Create a new globe by passing a DOM element and an optional configuration object to the Globe constructor.

    Config options:

    • rendererConfig (object): Parameters passed to the ThreeJS WebGLRenderer constructor. Default: { antialias: true, alpha: true }.
    • waitForGlobeReady (boolean): If true, waits for the globe wrapping or background image to load before rendering layers. Default: true.
    • animateIn (boolean): If true, animates the globe scaling and rotating into position during initialization. Default: true.
  11. Handle Hexed Polygon Events

    master

    You can attach interactive callbacks to the Hexed Polygons layer. The arguments include the polygon object, the event object, and the clicked/hovered coordinates.

    Available Callbacks:

    • onHexPolygonClick(polygon, event, { lat, lng, altitude }): Triggered on left-button clicks.
    • onHexPolygonRightClick(polygon, event, { lat, lng, altitude }): Triggered on right-button clicks.
    • onHexPolygonHover(polygon, prevPolygon): Triggered on mouse over events.