Giter VIP home page Giter VIP logo

react-globe.gl's Introduction

react-globe.gl

NPM package Build Size NPM Downloads

React bindings for the globe.gl UI component.

A React component to represent data visualization layers on a 3-dimensional globe in a spherical projection, using ThreeJS/WebGL for 3D rendering.

Check out the examples:

Quick start

import Globe from 'react-globe.gl';

or using a script tag

<script src="//unpkg.com/react-globe.gl"></script>

then

ReactDOM.render(
  <Globe
    pointsData={myData}
  />, 
  myDOMElement
);

API reference

Container Layout

Prop Type Default Description
width number <window width> Canvas width.
height number <window height> Canvas height.
backgroundColor string #000011 Background color.
backgroundImageUrl string - URL of the image to be used as background to the globe. If no image is provided, the background color is shown instead.
waitForGlobeReady bool true Whether to wait until the globe wrapping or background image has been fully loaded before rendering the globe or any of the data layers.
animateIn bool true Whether to animate the globe initialization, by scaling and rotating the globe into its inital position. This prop only has an effect on component mount.

Globe Layer

Prop Type Default Description
globeImageUrl string - URL of the image used in the material that wraps the globe. If no image is provided, the globe is represented as a black sphere.
bumpImageUrl string - URL of the image used to create a bump map in the material, to represent the globe's terrain.
showGlobe bool true Whether to show the globe surface itself.
showGraticules bool false Whether to show a graticule grid demarking latitude and longitude lines at every 10 degrees.
showAtmosphere bool true Whether to show a bright halo surrounding the globe, representing the atmosphere.
atmosphereColor string lightskyblue The color of the atmosphere.
atmosphereAltitude string 0.15 The max altitude of the atmosphere, in terms of globe radius units.
globeMaterial Material MeshPhongMaterial ThreeJS material used to wrap the globe. Can be used for more advanced styling of the globe, like in this example.
onGlobeReady func - Callback function to invoke immediately after the globe has been initialized and visible on the scene.
onGlobeClick func - 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 func - Callback function for right-clicks on the globe. The clicked globe coordinates and the event object are included as arguments: onGlobeRightClick({ lat, lng }, event).

Points Layer

Prop Type Default Description
pointsData array [] List of points to represent in the points map layer. Each point is displayed as a cylindrical 3D object rising perpendicularly from the surface of the globe.
pointLabel string or func name Point object accessor function or attribute for label (shown as tooltip). Supports plain text or HTML content.
pointLat number, string or func lat Point object accessor function, attribute or a numeric constant for the cylinder's center latitude coordinate.
pointLng number, string or func lng Point object accessor function, attribute or a numeric constant for the cylinder's center longitude coordinate.
pointColor string or func () => '#ffffaa' Point object accessor function or attribute for the cylinder color.
pointAltitude number, string or func 0.1 Point object accessor function, attribute or a numeric constant for the cylinder's altitude in terms of globe radius units (0 = 0 altitude (flat circle), 1 = globe radius).
pointRadius number, string or func 0.25 Point object accessor function, attribute or a numeric constant for the cylinder's radius, in angular degrees.
pointResolution number 12 Radial geometric resolution of each cylinder, expressed in how many slice segments to divide the circumference. Higher values yield smoother cylinders.
pointsMerge bool false Whether to merge all the point meshes into a single ThreeJS object, for improved rendering performance. Visually both options are equivalent, setting this option only affects the internal organization of the ThreeJS objects.
pointsTransitionDuration number 1000 Duration (ms) of the transition to animate point changes involving geometry modifications. A value of 0 will move the objects immediately to their final position. New objects are animated by scaling them from the ground up. Only works if pointsMerge is disabled.
onPointClick func - Callback function for point (left-button) clicks. The point object, the event object and the clicked coordinates are included as arguments: onPointClick(point, event, { lat, lng, altitude }). Only works if pointsMerge is disabled.
onPointRightClick func - Callback function for point right-clicks. The point object, the event object and the clicked coordinates are included as arguments: onPointRightClick(point, event, { lat, lng, altitude }). Only works if pointsMerge is disabled.
onPointHover func - Callback function for point mouse over events. The point object (or null if there's no point under the mouse line of sight) is included as the first argument, and the previous point object (or null) as second argument: onPointHover(point, prevPoint). Only works if pointsMerge is disabled.

Arcs Layer

Prop Type Default Description
arcsData array [] List of links to represent in the arcs map layer. Each link is displayed as an arc line that rises from the surface of the globe, connecting the start and end coordinates.
arcLabel string or func name Arc object accessor function or attribute for label (shown as tooltip). Supports plain text or HTML content.
arcStartLat number, string or func startLat Arc object accessor function, attribute or a numeric constant for the line's start latitude coordinate.
arcStartLng number, string or func startLng Arc object accessor function, attribute or a numeric constant for the line's start longitude coordinate.
arcEndLat number, string or func endLat Arc object accessor function, attribute or a numeric constant for the line's end latitude coordinate.
arcEndLng number, string or func endLng Arc object accessor function, attribute or a numeric constant for the line's end longitude coordinate.
arcColor string, [string, ...] or func () => '#ffffaa' Arc object accessor function or attribute for the line's color. Also supports color gradients by passing an array of colors, or a color interpolator function.
arcAltitude number, string or func null Arc object accessor function, attribute or a numeric constant for the arc's maximum altitude (ocurring at the half-way distance between the two points) in terms of globe radius units (0 = 0 altitude (ground line), 1 = globe radius). If a value of null or undefined is used, the altitude is automatically set proportionally to the distance between the two points, according to the scale set in arcAltitudeAutoScale.
arcAltitudeAutoScale number, string or func 0.5 Arc object accessor function, attribute or a numeric constant for the scale of the arc's automatic altitude, in terms of units of the great-arc distance between the two points. A value of 1 indicates the arc should be as high as its length on the ground. Only applicable if arcAltitude is not set.
arcStroke number, string or func null Arc object accessor function, attribute or a numeric constant for the line's diameter, in angular degrees. A value of null or undefined will render a ThreeJS Line whose width is constant (1px) regardless of the camera distance. Otherwise, a TubeGeometry is used.
arcCurveResolution number 64 Arc's curve resolution, expressed in how many straight line segments to divide the curve by. Higher values yield smoother curves.
arcCircularResolution number 6 Radial geometric resolution of each line, expressed in how many slice segments to divide the tube's circumference. Only applicable when using Tube geometries (defined arcStroke).
arcDashLength number, string or func 1 Arc object accessor function, attribute or a numeric constant for the length of the dashed segments in the arc, in terms of relative length of the whole line (1 = full line length).
arcDashGap number, string or func 0 Arc object accessor function, attribute or a numeric constant for the length of the gap between dash segments, in terms of relative line length.
arcDashInitialGap number, string or func 0 Arc object accessor function, attribute or a numeric constant for the length of the initial gap before the first dash segment, in terms of relative line length.
arcDashAnimateTime number, string or func 0 Arc object accessor function, attribute or a numeric constant for the time duration (in ms) to animate the motion of dash positions from the start to the end point for a full line length. A value of 0 disables the animation.
arcsTransitionDuration number 1000 Duration (ms) of the transition to animate arc changes involving geometry modifications. A value of 0 will move the arcs immediately to their final position. New arcs are animated by rising them from the ground up.
onArcClick func - Callback function for arc (left-button) clicks. The arc object, the event object and the clicked coordinates are included as arguments: onArcClick(arc, event, { lat, lng, altitude }).
onArcRightClick func - Callback function for arc right-clicks. The arc object, the event object and the clicked coordinates are included as arguments: onArcRightClick(arc, event, { lat, lng, altitude }).
onArcHover func - Callback function for arc mouse over events. The arc object (or null if there's no arc under the mouse line of sight) is included as the first argument, and the previous arc object (or null) as second argument: onArcHover(arc, prevArc).

Polygons Layer

Prop Type Default Description
polygonsData array [] List of polygon shapes to represent in the polygons map layer. Each polygon is displayed as a shaped cone that extrudes from the surface of the globe.
polygonLabel string or func name Polygon object accessor function or attribute for label (shown as tooltip). Supports plain text or HTML content.
polygonGeoJsonGeometry string or func geometry Polygon object accessor function or attribute for the GeoJson geometry specification of the polygon's shape. The returned value should have a minimum of two fields: type and coordinates. Only GeoJson geometries of type Polygon or MultiPolygon are supported, other types will be skipped.
polygonCapColor string or func () => '#ffffaa' Polygon object accessor function or attribute for the color of the top surface.
polygonCapMaterial Material, string or func - Polygon object accessor function, attribute or material object for the ThreeJS material to use in the top surface. This prop takes precedence over polygonCapColor, which will be ignored if both are defined.
polygonSideColor string or func () => '#ffffaa' Polygon object accessor function or attribute for the color of the cone sides.
polygonSideMaterial Material, string or func - Polygon object accessor function, attribute or material object for the ThreeJS material to use in the cone sides. This prop takes precedence over polygonSideColor, which will be ignored if both are defined.
polygonStrokeColor string or func - Polygon object accessor function or attribute for the color to stroke the polygon perimeter. A falsy value will disable the stroking.
polygonAltitude number, string or func 0.01 Polygon object accessor function, attribute or a numeric constant for the polygon cone's altitude in terms of globe radius units (0 = 0 altitude (flat polygon), 1 = globe radius).
polygonCapCurvatureResolution number, string or func 5 Polygon object accessor function, attribute or a numeric constant for the resolution (in angular degrees) of the cap surface curvature. The finer the resolution, the more the polygon is fragmented into smaller faces to approximate the spheric surface, at the cost of performance.
polygonsTransitionDuration number 1000 Duration (ms) of the transition to animate polygon altitude changes. A value of 0 will size the cone immediately to their final altitude. New polygons are animated by rising them from the ground up.
onPolygonClick func - Callback function for polygon (left-button) clicks. The polygon object, the event object and the clicked coordinates are included as arguments: onPolygonClick(polygon, event, { lat, lng, altitude }).
onPolygonRightClick func - Callback function for polygon right-clicks. The polygon object, the event object and the clicked coordinates are included as arguments: onPolygonRightClick(polygon, event, { lat, lng, altitude }).
onPolygonHover func - Callback function for polygon mouse over events. The polygon object (or null if there's no polygon under the mouse line of sight) is included as the first argument, and the previous polygon object (or null) as second argument: onPolygonHover(polygon, prevPolygon).

Paths Layer

Prop Type Default Description
pathsData array [] List of lines to represent in the paths map layer. Each path is displayed as a line that connects all the coordinate pairs in the path array.
pathLabel string or func name Path object accessor function or attribute for label (shown as tooltip). Supports plain text or HTML content.
pathPoints array, string or func pnts => pnts Path object accessor function, attribute or an array for the set of points that define the path line. By default, each path point is assumed to be a 2-position array ([<lat>, <lon>]). This default behavior can be modified using the pathPointLat and pathPointLng methods.
pathPointLat number, string or func arr => arr[0] Path point object accessor function, attribute or a numeric constant for the latitude coordinate.
pathPointLng number, string or func arr => arr[1] Path point object accessor function, attribute or a numeric constant for the longitude coordinate.
pathPointAlt number, string or func 0.001 Path point object accessor function, attribute or a numeric constant for the point altitude, in terms of globe radius units (0 = 0 altitude (ground), 1 = globe radius).
pathResolution number 2 The path's angular resolution, in lat/lng degrees. If the ground distance (excluding altitude) between two adjacent path points is larger than this value, the line segment will be interpolated in order to approximate the curvature of the sphere surface. Lower values yield more perfectly curved lines, at the cost of performance.
pathColor string, [string, ...] or func () => '#ffffaa' Path object accessor function or attribute for the line's color. Also supports color gradients by passing an array of colors, or a color interpolator function. Transparent colors are not supported in Fat Lines with set width.
pathStroke number, string or func null Path object accessor function, attribute or a numeric constant for the line's diameter, in angular degrees. A value of null or undefined will render a ThreeJS Line whose width is constant (1px) regardless of the camera distance. Otherwise, a FatLine is used.
pathDashLength number, string or func 1 Path object accessor function, attribute or a numeric constant for the length of the dashed segments in the path line, in terms of relative length of the whole line (1 = full line length).
pathDashGap number, string or func 0 Path object accessor function, attribute or a numeric constant for the length of the gap between dash segments, in terms of relative line length.
pathDashInitialGap number, string or func 0 Path object accessor function, attribute or a numeric constant for the length of the initial gap before the first dash segment, in terms of relative line length.
pathDashAnimateTime number, string or func 0 Path object accessor function, attribute or a numeric constant for the time duration (in ms) to animate the motion of dash positions from the start to the end point for a full line length. A value of 0 disables the animation.
pathTransitionDuration number 1000 Duration (ms) of the transition to animate path changes. A value of 0 will move the paths immediately to their final position. New paths are animated from start to end.
onPathClick func - Callback function for path (left-button) clicks. The path object, the event object and the clicked coordinates are included as arguments: onPathClick(path, event, { lat, lng, altitude }).
onPathRightClick func - Callback function for path right-clicks. The path object, the event object and the clicked coordinates are included as arguments: onPathRightClick(path, event, { lat, lng, altitude }).
onPathHover func - Callback function for path mouse over events. The path object (or null if there's no path under the mouse line of sight) is included as the first argument, and the previous path object (or null) as second argument: onPathHover(path, prevPath).

Heatmaps Layer

Prop Type Default Description
heatmapsData array [] List of heatmap datasets to represent in the heatmaps map layer. Each set of points is represented as an individual global heatmap with varying color and/or altitude, according to the point density. It uses a Gaussian KDE to perform the density estimation, based on the great-arc distance between points.
heatmapPoints array, string or func pnts => pnts Heatmap object accessor function, attribute or an array for the set of points that define the heatmap. By default, each point is assumed to be a 2-position array ([<lat>, <lon>]). This default behavior can be modified using the heatmapPointLat and heatmapPointLng methods.
heatmapPointLat number, string or func arr => arr[0] Heatmap point object accessor function, attribute or a numeric constant for the latitude coordinate.
heatmapPointLng number, string or func arr => arr[1] Heatmap point object accessor function, attribute or a numeric constant for the longitude coordinate.
heatmapPointWeight number, string or func 1 Heatmap point object accessor function, attribute or a numeric constant for the weight of the point. The weight of a point determines its influence on the density of the surrounding area.
heatmapBandwidth number, string or func 4 Heatmap object accessor function, attribute or a numeric constant for the heatmap bandwidth, in angular degrees. The bandwidth is an internal parameter of the Gaussian kernel function and defines how localized is the influence of a point on distant locations. A narrow bandwidth leads to a more spiky representation, while a broad one has smoother curves.
heatmapColorFn string or func Turbo colormap interpolator with fading opacity Heatmap object accessor function or attribute for the color interpolator function to represent density in the heatmap. This function should receive a number between 0 and 1 (or potentially higher if saturation > 1), and return a color string.
heatmapColorSaturation number, string or func 1.5 Heatmap object accessor function, attribute or a numeric constant for the color scale saturation. The saturation is a multiplier of the normalized density value ([0,1]) before passing it to the color interpolation function. It can be used to dampen outlier peaks in density and bring the data floor into view.
heatmapBaseAltitude number, string or func 0.01 Heatmap object accessor function, attribute or a numeric constant for the heatmap base floor altitude in terms of globe radius units (0 = 0 altitude, 1 = globe radius).
heatmapTopAltitude number, string or func - Heatmap object accessor function, attribute or a numeric constant for the heatmap top peak altitude in terms of globe radius units (0 = 0 altitude, 1 = globe radius). An equal value to the base altitude will yield a surface flat heatmap. If a top altitude is set, the variations in density will be used to define the altitude curves between base and top.
heatmapsTransitionDuration number 0 Duration (ms) of the transition to animate heatmap changes. A value of 0 will set the heatmap colors/altitudes immediately in their final position. New heatmaps are animated by rising them from the ground up and gently fading in through the color scale.
onHeatmapClick func - Callback function for heatmap (left-button) clicks. The heatmap object, the event object and the clicked coordinates are included as arguments: onHeatmapClick(heatmap, event, { lat, lng, altitude }).
onHeatmapRightClick func - Callback function for heatmap right-clicks. The heatmap object, the event object and the clicked coordinates are included as arguments: onHeatmapRightClick(heatmap, event, { lat, lng, altitude }).
onHeatmapHover func - Callback function for heatmap mouse over events. The heatmap object (or null if there's no heatmap under the mouse line of sight) is included as the first argument, and the previous heatmap object (or null) as second argument: onHeatmapHover(heatmap, prevHeatmap).

Hex Bin Layer

Prop Type Default Description
hexBinPointsData array [] List of points to aggregate using the hex bin map layer. Each point is added to an hexagonal prism 3D object that represents all the points within a tesselated portion of the space.
hexLabel string or func - Hex object accessor function or attribute for label (shown as tooltip). An hex object includes all points binned, and has the syntax: { points, sumWeight, center: { lat, lng } }. Supports plain text or HTML content.
hexBinPointLat number, string or func lat Point object accessor function, attribute or a numeric constant for the latitude coordinate.
hexBinPointLng number, string or func lng Point object accessor function, attribute or a numeric constant for the longitude coordinate.
hexBinPointWeight number, string or func 1 Point object accessor function, attribute or a numeric constant for the weight of the point. Weights for points in the same bin are summed and determine the hexagon default altitude.
hexBinResolution number 4 The geographic binning resolution as defined by H3. Determines the area of the hexagons that tesselate the globe's surface. Accepts values between 0 and 15. Level 0 partitions the earth in 122 (mostly) hexagonal cells. Each subsequent level sub-divides the previous in roughly 7 hexagons.
hexMargin number or func 0.2 The radial margin of each hexagon. Margins above 0 will create gaps between adjacent hexagons and serve only a visual purpose, as the data points within the margin still contribute to the hexagon's data. The margin is specified in terms of fraction of the hexagon's surface diameter. Values below 0 or above 1 are disadvised. This property also supports using an accessor method based on the hexagon's aggregated data, following the syntax: hexMargin(({ points, sumWeight, center: { lat, lng }}) => ...). This method should return a numeric constant.
hexAltitude number or func ({ sumWeight }) => sumWeight * 0.01 The altitude of each hexagon, in terms of globe radius units (0 = 0 altitude (flat hexagon), 1 = globe radius). This property also supports using an accessor method based on the hexagon's aggregated data, following the syntax: hexAltitude(({ points, sumWeight, center: { lat, lng }}) => ...). This method should return a numeric constant.
hexTopCurvatureResolution number 5 The resolution (in angular degrees) of the top surface curvature. The finer the resolution, the more the top area is fragmented into smaller faces to approximate the spheric surface, at the cost of performance.
hexTopColor func () => '#ffffaa' Accessor method for each hexagon's top color. The method should follow the signature: hexTopColor(({ points, sumWeight, center: { lat, lng }}) => ...) and return a color string.
hexSideColor func () => '#ffffaa' Accessor method for each hexagon's side color. The method should follow the signature: hexSideColor(({ points, sumWeight, center: { lat, lng }}) => ...) and return a color string.
hexBinMerge bool false Whether to merge all the hexagon meshes into a single ThreeJS object, for improved rendering performance. Visually both options are equivalent, setting this option only affects the internal organization of the ThreeJS objects.
hexTransitionDuration number 1000 Duration (ms) of the transition to animate hexagon changes related to geometry modifications (altitude, radius). A value of 0 will move the hexagons immediately to their final position. New hexagons are animated by scaling them from the ground up. Only works if hexBinMerge is disabled.
onHexClick func - Callback function for hexagon (left-button) clicks. The hex object including all points binned, the event object and the clicked coordinates are included as arguments: onHexClick({ points, sumWeight, center: { lat, lng } }, event, { lat, lng, altitude }). Only works if hexBinMerge is disabled.
onHexRightClick func - Callback function for hexagon right-clicks. The hex object including all points binned, the event object and the clicked coordinates are included as arguments: onHexRightClick({ points, sumWeight, center: { lat, lng } }, event, { lat, lng, altitude }). Only works if hexBinMerge is disabled.
onHexHover func - Callback function for hexagon mouse over events. The hex object (or null if there's no hex under the mouse line of sight) is included as the first argument, and the previous hex object (or null) as second argument: onHexHover(hex, prevHex). Each hex object includes all points binned, and has the syntax: { points, sumWeight, center: { lat, lng } }. Only works if hexBinMerge is disabled.

Hexed Polygons Layer

Prop Type Default Description
hexPolygonsData array [] List of polygon shapes to represent in the hexed polygons map layer. Each polygon is displayed as a tesselated group of hexagons that approximate the polygons shape according to the resolution specified in hexPolygonResolution.
hexPolygonLabel string or func name Hexed polygon object accessor function or attribute for label (shown as tooltip). Supports plain text or HTML content.
hexPolygonGeoJsonGeometry string or func geometry Hexed polygon object accessor function or attribute for the GeoJson geometry specification of the polygon's shape. The returned value should have a minimum of two fields: type and coordinates. Only GeoJson geometries of type Polygon or MultiPolygon are supported, other types will be skipped.
hexPolygonColor string or func () => '#ffffaa' Hexed polygon object accessor function or attribute for the color of each hexagon in the polygon.
hexPolygonAltitude number, string or func 0.001 Hexed polygon object accessor function, attribute or a numeric constant for the polygon's hexagons altitude in terms of globe radius units (0 = 0 altitude, 1 = globe radius).
hexPolygonResolution number, string or func 3 Hexed polygon object accessor function, attribute or a numeric constant for the geographic binning resolution as defined by H3. Determines the area of the hexagons that tesselate the globe's surface. Accepts values between 0 and 15. Level 0 partitions the earth in 122 (mostly) hexagonal cells. Each subsequent level sub-divides the previous in roughly 7 hexagons.
hexPolygonMargin number, string or func 0.2 Hexed polygon object accessor function, attribute or a numeric constant for the radial margin of each hexagon. Margins above 0 will create gaps between adjacent hexagons within a polygon. The margin is specified in terms of fraction of the hexagon's surface diameter. Values below 0 or above 1 are disadvised.
hexPolygonUseDots bool, string or func false Hexed polygon object accessor function, attribute or a boolean constant for whether to represent each polygon point as a circular dot instead of an hexagon.
hexPolygonCurvatureResolution number, string or func 5 Hexed polygon object accessor function, attribute or a numeric constant for the resolution (in angular degrees) of each hexed polygon surface curvature. The finer the resolution, the more the polygon hexes are fragmented into smaller faces to approximate the spheric surface, at the cost of performance.
hexPolygonDotResolution number, string or func 12 Hexed polygon object accessor function, attribute or a numeric constant for the resolution of each circular dot, expressed in how many slice segments to divide the circumference. Higher values yield smoother circles, at the cost of performance. This is only applicable in dot representation mode.
hexPolygonsTransitionDuration number 0 Duration (ms) of the transition to animate hexed polygons altitude and margin changes. A value of 0 will move the hexagons immediately to their final state. New hexed polygons are animated by sizing each hexagon from 0 radius.
onHexPolygonClick func - Callback function for hexed polygon (left-button) clicks. The polygon object, the event object and the clicked coordinates are included as arguments: onHexPolygonClick(polygon, event, { lat, lng, altitude }).
onHexPolygonRightClick func - Callback function for hexed polygon right-clicks. The polygon object, the event object and the clicked coordinates are included as arguments: onHexPolygonRightClick(polygon, event, { lat, lng, altitude }).
onHexPolygonHover func - Callback function for hexed polygon mouse over events. The polygon object (or null if there's no polygon under the mouse line of sight) is included as the first argument, and the previous polygon object (or null) as second argument: onHexPolygonHover(polygon, prevPolygon).

Tiles Layer

Prop Type Default Description
tilesData array [] List of tiles to represent in the tiles map layer. Each tile is displayed as a spherical surface segment. The segments can be placed side-by-side for a tiled surface and each can be styled separately.
tileLabel string or func name Tile object accessor function or attribute for label (shown as tooltip). Supports plain text or HTML content.
tileLat number, string or func lat Tile object accessor function, attribute or a numeric constant for the segment's centroid latitude coordinate.
tileLng number, string or func lng Tile object accessor function, attribute or a numeric constant for the segment's centroid longitude coordinate.
tileAltitude number, string or func 0.01 Tile object accessor function, attribute or a numeric constant for the segment's altitude in terms of globe radius units.
tileWidth number, string or func 1 Tile object accessor function, attribute or a numeric constant for the segment's longitudinal width, in angular degrees.
tileHeight number, string or func 1 Tile object accessor function, attribute or a numeric constant for the segment's latitudinal height, in angular degrees.
tileUseGlobeProjection bool, string or func true Tile object accessor function, attribute or a boolean constant for whether to use the globe's projection to shape the segment to its relative tiled position (true), or break free from this projection and shape the segment as if it would be laying directly on the equatorial perimeter (false).
tileMaterial Material, string or func () => new MeshLambertMaterial({ color: '#ffbb88' }) Tile object accessor function, attribute or material object for the ThreeJS material used to style the segment's surface.
tileCurvatureResolution number, string or func 5 Tile object accessor function, attribute or a numeric constant for the resolution (in angular degrees) of the surface curvature. The finer the resolution, the more the tile geometry is fragmented into smaller faces to approximate the spheric surface, at the cost of performance.
tilesTransitionDuration number 1000 Duration (ms) of the transition to animate tile changes involving geometry modifications. A value of 0 will move the tiles immediately to their final position. New tiles are animated by scaling them from the centroid outwards.
onTileClick func - 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 func - 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 func - 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

Prop Type Default Description
ringsData array [] List of self-propagating ripple rings to represent in the rings map layer. Each data point is displayed as an animated set of concentric circles that propagate outwards from (or inwards to) a central point through the spherical surface.
ringLat number, string or func lat Ring object accessor function, attribute or a numeric constant for each circle's center latitude coordinate.
ringLng number, string or func lng Ring object accessor function, attribute or a numeric constant for each circle's center longitude coordinate.
ringAltitude number, string or func 0.0015 Ring object accessor function, attribute or a numeric constant for the circle's altitude in terms of globe radius units.
ringColor string, [string, ...] or func () => '#ffffaa' Ring object accessor function or attribute for the stroke color of each ring. Also supports radial color gradients by passing an array of colors, or a color interpolator function.
ringResolution number 64 Geometric resolution of each circle, expressed in how many slice segments to divide the circumference. Higher values yield smoother circles.
ringMaxRadius number, string or func 2 Ring object accessor function, attribute or a numeric constant for the maximum outer radius of the circles, at which the rings stop propagating and are removed. Defined in angular degrees.
ringPropagationSpeed number, string or func 1 Ring object accessor function, attribute or a numeric constant for the propagation velocity of the rings, defined in degrees/second. Setting a negative value will invert the direction and cause the rings to propagate inwards from the maxRadius.
ringRepeatPeriod number, string or func 700 Ring object accessor function, attribute or a numeric constant for the interval of time (in ms) to wait between consecutive auto-generated concentric circles. A value less or equal than 0 will disable the repetition and emit a single ring.

Labels Layer

Prop Type Default Description
labelsData array [] List of label objects to represent in the labels map layer.
labelLabel string or func - Label object accessor function or attribute for its own tooltip label. Supports plain text or HTML content.
labelLat number, string or func lat Label object accessor function, attribute or a numeric constant for the latitude coordinate.
labelLng number, string or func lng Label object accessor function, attribute or a numeric constant for the longitude coordinate.
labelText string or func text Label object accessor function or attribute for the label text.
labelColor string or func () => 'lightgrey' Label object accessor function or attribute for the label color.
labelAltitude number, string or func 0 Label object accessor function, attribute or a numeric constant for the label altitude in terms of globe radius units.
labelSize number, string or func 0.5 Label object accessor function, attribute or a numeric constant for the label text height, in angular degrees.
labelTypeFace typeface object helvetiker regular Text font typeface JSON object. Supports any typeface font generated by Facetype.js.
labelRotation number, string or func 0 Label object accessor function, attribute or a numeric constant for the label rotation in degrees. The rotation is performed clockwise along the axis of its latitude parallel plane.
labelResolution number 3 The text geometric resolution of each label, expressed in how many segments to use in the text curves. Higher values yield smoother labels.
labelIncludeDot bool, string or func true Label object accessor function, attribute or a bool constant for whether to include a dot marker next to the text indicating the exact lat, lng coordinates of the label. If enabled the text will be rendered offset from the dot.
labelDotRadius number, string or func 0.1 Label object accessor function, attribute or a numeric constant for the radius of the dot marker, in angular degrees.
labelDotOrientation string or func () => 'bottom' Label object accessor function or attribute for the orientation of the label if the dot marker is present. Possible values are right, top and bottom.
labelsTransitionDuration number 1000 Duration (ms) of the transition to animate label changes involving position modifications (lat, lng, altitude, rotation). A value of 0 will move the labels immediately to their final position. New labels are animated by scaling their size.
onLabelClick func - Callback function for label (left-button) clicks. The label object, the event object and the clicked coordinates are included as arguments: onLabelClick(label, event, { lat, lng, altitude }).
onLabelRightClick func - Callback function for label right-clicks. The label object, the event object and the clicked coordinates are included as arguments: onLabelRightClick(label, event, { lat, lng, altitude }).
onLabelHover func - Callback function for label mouse over events. The label object (or null if there's no label under the mouse line of sight) is included as the first argument, and the previous label object (or null) as second argument: onLabelHover(label, prevlabel).

HTML Elements Layer

Prop Type Default Description
htmlElementsData array [] List objects to represent in the HTML elements map layer. Each HTML element is rendered using ThreeJS CSS2DRenderer.
htmlLat number, string or func lat HTML element accessor function, attribute or a numeric constant for the latitude coordinate of the element's central position.
htmlLng number, string or func lng HTML element accessor function, attribute or a numeric constant for the longitude coordinate of the element's central position.
htmlAltitude number, string or func 0 HTML element accessor function, attribute or a numeric constant for the altitude coordinate of the element's position, in terms of globe radius units.
htmlElement string or func null Accessor function or attribute to retrieve the DOM element to use. Should return an instance of HTMLElement.
htmlTransitionDuration number 1000 Duration (ms) of the transition to animate HTML elements position changes. A value of 0 will move the elements immediately to their final position.

3D Objects Layer

Prop Type Default Description
objectsData array [] Getter/setter for the list of custom 3D objects to represent in the objects layer. Each object is rendered according to the objectThreeObject method.
objectLabel string or func name Object accessor function or attribute for its own tooltip label. Supports plain text or HTML content.
objectLat number, string or func lat Object accessor function, attribute or a numeric constant for the latitude coordinate of the object's position.
objectLng number, string or func lng Object accessor function, attribute or a numeric constant for the longitude coordinate of the object's position.
objectAltitude number, string or func 0.01 Object accessor function, attribute or a numeric constant for the altitude coordinate of the object's position, in terms of globe radius units.
objectRotation {[x], [y], [z]}, string or func Object accessor function, attribute or a {x, y, z} object for the object's rotation (in degrees). Each dimension is optional, allowing for rotation only in some axes. Rotation is applied in the order X->Y->Z.
objectFacesSurface bool, string or func true Object accessor function, attribute or a boolean constant for whether the object should be rotated to face (away from) the globe surface (true), or be left in its original universe orientation (false).
objectThreeObject Object3d, string or func A yellow sphere Object accessor function or attribute for defining a custom 3d object to render as part of the objects map layer. Should return an instance of ThreeJS Object3d.
onObjectClick func - Callback function for object (left-button) clicks. The object itself, the event and the clicked coordinates are included as arguments: onObjectClick(obj, event, { lat, lng, altitude }).
onObjectRightClick func - Callback function for object right-clicks. The object itself, the event and the clicked coordinates are included as arguments: onObjectRightClick(obj, event, { lat, lng, altitude }).
onObjectHover func - Callback function for object mouse over events. The object itself (or null if there's no object under the mouse line of sight) is included as the first argument, and the previous object (or null) as second argument: onObjectHover(obj, prevObj).

Custom Layer

Prop Type Default Description
customLayerData array [] List of items to represent in the custom map layer. Each item is rendered according to the customThreeObject method.
customLayerLabel string or func name Object accessor function or attribute for label (shown as tooltip). Supports plain text or HTML content.
customThreeObject Object3d, string or func - Object accessor function or attribute for generating a custom 3d object to render as part of the custom map layer. Should return an instance of ThreeJS Object3d.
customThreeObjectUpdate string or func - Object accessor function or attribute for updating an existing custom 3d object with new data. This can be used for performance improvement on data updates as the objects don't need to be removed and recreated at each update. The callback method's signature includes the object to be update and its new data: customThreeObjectUpdate((obj, objData) => { ... }).
onCustomLayerClick func - Callback function for custom object (left-button) clicks. The custom object, the event object and the clicked coordinates are included as arguments: onCustomLayerClick(obj, event, { lat, lng, altitude }).
onCustomLayerRightClick func - Callback function for custom object right-clicks. The custom object, the event object and the clicked coordinates are included as arguments: onCustomLayerRightClick(obj, event, { lat, lng, altitude }).
onCustomLayerHover func - Callback function for custom object mouse over events. The custom object (or null if there's no object under the mouse line of sight) is included as the first argument, and the previous custom object (or null) as second argument: onCustomLayerHover(obj, prevObj).

Render Control

Prop Type Default Description
rendererConfig object { antialias: true, alpha: true } Configuration parameters to pass to the ThreeJS WebGLRenderer constructor. This prop only has an effect on component mount.
enablePointerInteraction bool true Whether to enable the mouse tracking events. This activates an internal tracker of the canvas mouse position and enables the functionality of object hover/click and tooltip labels, at the cost of performance. If you're looking for maximum gain in your globe performance it's recommended to switch off this property.
pointerEventsFilter func () => true Filter function which defines whether a particular object can be the target of pointer interactions. In general, objects that are closer to the camera get precedence in capturing pointer events. This function allows having ignored object layers so that pointer events can be passed through to deeper objects in the various globe layers. The ThreeJS object and its associated data (if any) are passed as arguments: pointerEventsFilter(obj, data). The function should return a boolean value.
lineHoverPrecision number 0.2 Precision to use when detecting hover events over Line objects, such as arcs and paths.
Method Arguments Description
pointOfView { lat, lng, altitude } [,ms=0] By default the camera will aim at the cross between the equator and the prime meridian (0,0 coordinates), at an altitude of 2.5 globe radii.
pauseAnimation - Pauses the rendering cycle of the component, effectively freezing the current view and cancelling all user interaction. This method can be used to save performance in circumstances when a static image is sufficient.
resumeAnimation - Resumes the rendering cycle of the component, and re-enables the user interaction. This method can be used together with pauseAnimation for performance optimization purposes.
onZoom func Callback function for point-of-view changes by zooming or rotating the globe using the orbit controls. The current point of view (with the syntax { lat, lng, altitude }) is included as sole argument.
lights array Getter/setter for the list of lights to use in the scene. Each item should be an instance of Light.
scene - Access the internal ThreeJS Scene. Can be used to extend the current scene with additional objects not related to globe.gl.
camera - Access the internal ThreeJS Camera.
renderer - Access the internal ThreeJS WebGL renderer.
postProcessingComposer - Access the post-processing composer. Use this to add post-processing rendering effects to the scene. By default the composer has a single pass (RenderPass) that directly renders the scene without any effects.
controls - Access the internal ThreeJS orbit controls object.

Utility

Method Arguments Description
getGlobeRadius - Returns the cartesian distance of a globe radius in absolute spatial units.
getCoords lat, lng [,altitude=0] 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=0] 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 } 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 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.

Giving Back

paypal If this project has helped you and you'd like to contribute back, you can always buy me a β˜•!

react-globe.gl's People

Contributors

vasturiano avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-globe.gl's Issues

Unable to continually change globe point of view

Describe the bug
I am unable to continually change the globe's POV

So i have made a globe with labels data changing every 5 seconds. That is working fine and I would like to make the point of view be on that new location every 5 seconds.

I have succeeded in using
const MAP_CENTER = { lat: 0, lng: 0, altitude: 1.5 }; globeEl.current.pointOfView(MAP_CENTER, 0);

to set the globe's initial POV. However when I try to change the POV every 5 seconds, this causes the globe to completely disappear
useEffect(() => { const countryLocation = { lat: country.latitude, lng: country.longitude, altitude: 2.7, }; globeEl.current.pointOfView(countryLocation, 0); }, [country]);

Remove outline

Is your feature request related to a problem? Please describe.
Is it possible to remove the focus outline around the globe component?

I have tried using outline: none and focus: outline: none on the Globe component as well as it's parent component and it seems that I am not able to remove the outline using that.

Make globe component inherit width and height from parent element

Is your feature request related to a problem? Please describe.
When creating responsive globes for devices with smaller screens it becomes quite complicated setting the width and height of the globe component.

Describe the solution you'd like
I'd like the width and height props of the globe component to be either number or strings so in instances when a responsive globe is needed I can just set the width like width="100%"

Describe alternatives you've considered
I have tried setting the width and height using strings, ie. width="100%". I have also tried to use refs to get the width and height of the parent element of the Globe and using hooks to set the width and height of the Globe, however this solution becomes more complex when taking into account responsiveness. Or I would like to know if there are any workarounds currently being used to achieve this outcome. Thanks

How to remove zoom with mouse wheel/trackpad?

Hello, and thank you for this awesome library. We've got a sweet looking globe set up with very little work on our end!

I'm attempting to remove the zoom feature, so that a user scrolling down the page does not get interrupted by the canvas, and so that I have more control over the size of the globe when adjusting the responsive design of my page.

I've tried removing the "wheel" event listener from the canvas element, but have had no luck blocking the zoom so far. Any suggestions would be much appreciated. Thank you!

Update, duplicate of #23.

Initial Zoom

Hi,

I'm looking to tweak a little bit the globe but couldn't find any solution.

  • Is there a way to set a different initial zoom that will be used to generate the first load animation? (I found how to set a different zoom, but there is a glitch when it loads)
  • Also, is there a way to decide where the globe will stop after the load animation ends? (if we pass a lng/lat coordinate)

Thanks!

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I'm getting an Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 for the choropleth-countries/index.html example. It seems that the fetch does nothing, i also tried using axios and just importing it locally but nothing worked. I cant seem to get the geojson data into the countries state. How did you get it to work if the example on github doesn't?

Disable globe zoom onScroll

Hello @vasturiano, thanks for an awesome globe library.

I'm trying to disable globe zoom when I scroll over it. Is there a way to do this?

I haven't seen anything related to this issue in the docs.

v2.13.0, MacOS Catalina

Thank you.

Data format of Polygons Layer ?

hi @vasturiano first of all Thanks for this amazing library. I couldn't find the exact data format that should be fed to the polygonsData ? I'm trying to show some information in a label when the user clicks on a country on the globe. In order to do this I must fill the globe with the details of the countries.
It would be a great help if i could have a simple codesandbox of this Polygonal layered globe

enable support for building in a static site (before window is defined)

Is your feature request related to a problem? Please describe.
I am trying to use this in a gatsbyjs project but the build step fails due to a reference error: window is not defined

Describe the solution you'd like
could this library defer loading any modules that reference window until it is available?
some ways to do this described here:
gatsbyjs/gatsby#309

Describe alternatives you've considered
this problem could also be solved on my end but i think a solution baked into your library would be more elegant.

Additional context
gatsbyjs error output posted in a below comment.

Altitude of the starting or ending point of an arc

I have on my globe some custom layer in orbit, I would like to create some arc which starting (or ending) at a specific altitude. Do you know how can I do ? the property "arcAltitude" doesn't help, it changes only the max height of the arc.

hexPolygonCurvatureResolution does not give any effects

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Got an error with the globe in a Next.JS project

Describe the bug
I got this error

globe.gl.module.js:595 Uncaught TypeError: Cannot read property '__globeObjType' of null
    at globe.gl.module.js:595
    at Function.tick (three-render-objects.module.js:258)
    at Function.comp.<computed> [as tick] (kapsule.module.js:159)
    at Function._animationCycle (globe.gl.module.js:373)
    at comp.<computed> (kapsule.module.js:159)

To Reproduce
Steps to reproduce the behavior:

https://codesandbox.io/s/quizzical-moore-59x4h

Expected behavior
It should work

Desktop (please complete the following information):

  • OS: Windows
  • Browser: Chrome
  • Version: 90

Error when trying to run the 'Custom Layer' Example

Hi @vasturiano, thanks so much for this library - it's awesome!

I'm trying to run the 'Custom Layer' example that you put in the README, but I'm getting the following error:

three.module.js:25120 Uncaught TypeError: Cannot read property 'getUniforms' of undefined
    at setProgram (three.module.js:25120)
    at WebGLRenderer.renderBufferDirect (three.module.js:24125)
    at renderObject (three.module.js:24886)
    at renderObjects (three.module.js:24856)
    at WebGLRenderer.render (three.module.js:24633)
    at Function.tick (three-render-objects.module.js:146)
    at Function.comp.<computed> [as tick] (kapsule.module.js:159)
    at Function._animationCycle (globe.gl.module.js:278)
    at comp.<computed> (kapsule.module.js:159)

I'm wondering if it's an issue with the version of three I'm using (version 0.111), or maybe how I'm importing it. The code is unchanged otherwise from your source.

Any guidance or suggestions would be greatly appreciate. Thanks again!

Transparent background

Is your feature request related to a problem? Please describe.
I'd like to be able to see my site background

Describe the solution you'd like
I'd like a way for the background to be transparent

How to make a Transparent Globe

i don't know if it's a bug or not but i'm trying to turn the globe transparent like this.
image

I found the same issue here in the pure js version
vasturiano/globe.gl#20
when i tried this solution using react the globe has become entirely the same color as the background

here is the code

     const img = require('./assets/test.png')
    const globeE1 = useRef();
    useEffect(() => {
        const globeMaterial = globeE1.current.globeMaterial();
        globeMaterial.opacity = 0;
    }, [])
    return (
        <div >
            <Globe
                ref={globeE1}
                globeImageUrl={img.default}
                backgroundColor={'rgba(255, 255, 255, 12)'}
                animateIn={true}
                showAtmosphere={false}
                height={400}
                width={400}
            />

thanks for help

QUESTION: Rotation animation on globe click

Hi!

I was wondering if there were a way to smoothly transition the globe rotation on a different coordinate ?

For example, manually changing the coordinates with pointOfView({lat, lng})}) would make the globe rotate smoothly toward these coordinates.

Thanks!

ReferenceError: window is not defined

Running the library sometimes render the globe, sometimes throw an exception. Are you using global window somewhere in your code?

Server Error
ReferenceError: window is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

import Globe from 'react-globe.gl';

const World = (props) => <Globe {...props} />;

export default World;
 at Object.<anonymous> (file:///Users/sample/node_modules/three-geojson-geometry/dist/three-geojson-geometry.common.js:152:13)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (file:///Users/sample/node_modules/three-globe/dist/three-globe.common.js:6:28)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (file:///Users/sample/node_modules/globe.gl/dist/globe.gl.common.js:4:18)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
getNodeError @ nodeStackFrames.js?aca3:39
eval @ index.tsx?8abf:326
setTimeout (async)
_callee$ @ index.tsx?8abf:312
tryCatch @ runtime.js?96cf:63
invoke @ runtime.js?96cf:293
eval @ runtime.js?96cf:118
asyncGeneratorStep @ asyncToGenerator.js?c973:3
_next @ asyncToGenerator.js?c973:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?c973:13
_next @ asyncToGenerator.js?c973:25
eval @ asyncToGenerator.js?c973:32
eval @ asyncToGenerator.js?c973:21
_default @ index.js:442
eval @ next-dev.js?53bc:31
eval @ next-dev.js?53bc:31
./node_modules/next/dist/client/next-dev.js @ main.js?ts=1609233259916:2107
__webpack_require__ @ webpack.js?ts=1609233259916:873
checkDeferredModules @ webpack.js?ts=1609233259916:46
webpackJsonpCallback @ webpack.js?ts=1609233259916:33
(anonymous) @ webpack.js?ts=1609233259916:1015
(anonymous) @ webpack.js?ts=1609233259916:1023
unfetc

Is there a way to use threejs postprocessing on the globe?

Is your feature request related to a problem? Please describe.
I would like to be able to layer post processing over the globe.

Describe the solution you'd like
a good api for this would be if you exposed a passes config option that accepted an array of the post processing passes to apply during each render loop iteration.

Describe alternatives you've considered
without minor changes to the render loop logic, i dont think post processing layers are possible with this tool so i would have to recreate the tool.

Additional context
n/a

window is not defined with next js

I'm trying to use the react globe with Next JS and once i add
import Globe from 'react-globe.gl';
I get: the below error

Screen Shot 2021-04-03 at 11 42 25 PM

any ideas would be appreciated

[Question] How could I make the Github globe?

@vasturiano Just want to say that I'm absolutely amazed by this project. I've now seen incredible globes from Vercel, Stripe and GitHub, and I'm looking to implement a similar one.

Do you have a rough idea of how I would configure the globe to look like the one from github.com?

Screen Shot 2021-04-24 at 4 44 17 PM

It seems like the data part is relatively straightforward, but I'm curious mostly about the design.

I also noticed that GitHub has image/video fallbacks in case it loads slowly or GL isn't supported(?) Do you have any suggestions for how to implement that.

Thanks for your help and great contributions.

Bug: "Attempted import error: 'Face3' is not exported from 'three' (imported as 'o')."

Describe the bug
The three.js library has made a recent update in January 28 that removed Face3 from core (here is the deprecated folder that shows this). Due to this, when I try to display a basic react-globe example in the browser, the error gets diplayed "Attempted import error: 'Face3' is not exported from 'three' (imported as 'o')." because Face3 is no longer in Three.js although react-globe requires it.

To Reproduce
Steps to reproduce the behavior:

  1. Download the latest version of Three.js and the react-globe dependency
  2. Create a basic render of react-globe
  3. Run npm start in React and open the browser
  4. See error

Expected behavior
I expect the react-globe to appear on the page

Desktop (please complete the following information):

  • OS: IOS Mac M1
  • Browser: Chrome
  • Version: 89.0.4389.90 (Official Build) (arm64)

Additional context
This deprecated folder shows that Face3 is no longer part of Three.js so I think react-globe needs to update the version of three.js for it to work with the latest updates.

add specularMap

Hey @vasturiano,
I am currently working on a project where I have to create a globe and visualize data on it. I'm happy to use such a great lib, thanks to you. Since I'm new to JS and especially React it's hard for me to understand all the connections.

Coming to why I created this request: I would love to add a specular map for water reflection such as in this project here.

Maybe there is an easy answer, then I'd love to hear it.

Nevertheless, I took a deep look into your libaries and found the globe.js script of your three-globe library. There you defined a new THREE.Mesh respectively a new THREE.MeshPhongMaterial. As far as I understood I'm not able to add anything to this material, because there are only defined variables for the bumpmap and texturemap. As I said before I would love to have one where I can add a 'specularImageUrl'.

I appreciate your response
Marvin

Error when switching pages

Describe the bug
Getting an error while changing from a page that has the Globe component to a page where it doesn't have.
If I remove the hexPolygonsData prop the error is gone

To Reproduce

Expected behavior

Screenshots
three-globe-error

Desktop (please complete the following information):

Smartphone (please complete the following information):

Additional context

import HEX_DATA from './data/countries_hex_data.json';

<Globe
      ref={globeEl}
      globeImageUrl="/globe/globe-background.png"
      backgroundColor="rgba(0,0,0,0)"
      labelsData={[selectedCountry]}
      labelTypeFace={customFont}
      labelText={useCallback((point) => point.label, [])}
      labelSize={useCallback(() => 1.6, [])}
      labelColor={useCallback(() => 'white', [])}
      labelDotRadius={useCallback(() => 0.4, [])}
      labelAltitude={useCallback(() => 0.05, [])}
      hexPolygonsData={useCallback(HEX_DATA.features, [])} // <- if I remove this line the error is gone
      hexPolygonResolution={useCallback(() => 3, [])}
      hexPolygonMargin={useCallback(() => 0.62, [])}
      hexPolygonColor={useCallback(() => HEX_COLOR, [])}
      enablePointerInteraction={false}
      showAtmosphere={false}
      width={600}
    />

NextJs: "^10.0.1"
React: "16.14.0"
react-globe.gl: "^2.12.6"

QUESTION: High number of tiles

Hi again :)

I need to create a high number of tiles (10,000 only visible one at a time on hover) and I can start to feel some performance issue (especially on Safari).

Do you think of another solution than the traditional tilesData props?

Here is how I do it at the moment:

[...Array(80).keys()].forEach((latIdx) =>
  [...Array(125).keys()].forEach((lngIdx) =>
    arr.push({
      lng: -180 + lngIdx * (360 /  125) + 1.5,
      lat: 90 - latIdx * (180 / 80) - 1
    })
  )
);
onTileHover={(tile: any, prevTile: any) => {
    globeEl.current.controls().autoRotate = !tile;
  if (tile?.__threeObj) {
    tile.__threeObj.material = new materials.MeshLambertMaterial({
      color: "#c026d3",
      opacity: 0.6,
      transparent: true,
    });
  }
  if (prevTile?.__threeObj) {
    prevTile.__threeObj.material = new materials.MeshLambertMaterial({
      color: "#c026d3",
      opacity: 0,
      transparent: true,
    });
  }
}}

Thanks a lot for your help!

Unable to run basic examples

Describe the bug
I am a novice to react.js and javascript, so may be it's some rather stupid mistake.

I saw examples, but they look rather non standard. I've tried to do the following:

  1. generate basic react app with npx create-react-app my-app
  2. added globe.gl with npm install --save globe.gl
  3. modified index.js in the following way
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';

import Globe from 'globe.gl';

  // 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)]
  }));

ReactDOM.render(    
      <Globe
        globeImageUrl="//unpkg.com/three-globe/example/img/earth-night.jpg"
        pointsData={gData}
        pointAltitude="size"
        pointColor="color"
     />,
     document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
  1. run application with npm start.

But all I see is blank screen and some strange errors

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

If I move the same piece of code into index.html (as in react-globe.gl examples) than I can see the globe, but it doesn't look like a good solution.

korean label text crashes

Thanks to your gorgeous library! 😁
But I think there's a problem with korean label support.

Describe the bug
image

To Reproduce
when I use LabelText as Other language, It goes to "??".

Expected behavior
Ex. "Vatican City" to korean, It should produce "λ°”ν‹°μΉΈ μ‹œ", but it shows "??".

Screenshots
image

Desktop (please complete the following information):

  • Chrome, MacOS 10.15 (Catalina)

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

pathStroke isn't working

Hello,

I'm trying to change the diameter of the path between 2 points, I'm doing exactly the same as arcStroke, but it changes nothing, the path isn't displaying.

Do you have the real syntax to use that ? I didn't find the solution by reading the documentation...

Thank you

onPolygonClick won't trigger

Describe the bug
When performing a left click onPolygonClick is not called. I do notice however the function is called when the onPolygonRightClick prop is passed and triggered.

To Reproduce
Steps to reproduce the behavior:

  1. Create an instance of Globe Element.
  2. Ensure polygonsData is correctly populated.
  3. Pass function to onPolygonClick prop.
    4.Attempt to call onPolygonClick by left-clicking

Expected behavior
The function passed as a parameter should be executed.

Additional context
Here's an example of the instance.

	<Globe
			ref={globeEl}
			globeImageUrl='//unpkg.com/three-globe/example/img/earth-night.jpg'
			backgroundImageUrl='//unpkg.com/three-globe/example/img/night-sky.png'
			polygonsData={countries.features}
			polygonAltitude={d => (d === hoverD ? 0.12 : 0.06)}
			polygonCapColor={d => (d === hoverD ? "green" : "black")}
			polygonSideColor={() => "rgba(0, 100, 0, 0.15)"}
			polygonStrokeColor={() => "#111"}
			polygonLabel={({ properties: d }) => getPolygonLabel(d)}
			onPolygonHover={setHoverD}
			onPolygonClick={polygon => global.console.log("polygon", polygon)}
			polygonsTransitionDuration={300}
		/>

How to properly use react-globe.gl with Next.js (ref, ssr, props

I can't use the reat-globe.gl library with Next.js.

I would like to use globeEl ref with methods provided in globeEl.current

Got error like those :

// globeEl.current.controls is not a function

// with this stack
import dynamic from "next/dynamic";

const Globe = dynamic(import("react-globe.gl"), { ssr: false });

/////

function initGlobe() {
		if (globeEl.current) {
			globeEl.current.controls().autoRotate = true;
		}
	}

///

<Globe
				ref={globeEl}
				arcsData={arcsData}
				arcStroke={1}
				globeMaterial={globeMaterial}
				width={800}
				onGlobeReady={() => initGlobe()}
				arcAltitude={0.2}
				backgroundColor="rgba(0,0,0,0)"
				arcColor={"color"}
				globeImageUrl="/images/earth-blue-marble.jpg"
				bumpImageUrl="/images/earth-topology.png"
			/>

Does somebody hass succeeded with next.js ?

csvParseRows Webpack error when using in React

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Following the US international outbound tutorial: https://github.com/vasturiano/react-globe.gl/blob/master/example/airline-routes/us-international-outbound.html
  2. Load the code directly into a React component and run the development server. Only change: I took the code out of the World() function.
  3. Got the following error:

Screen Shot 2021-02-15 at 11 35

Can't determine whether this is a Webpack error, a D3 error, or something going awry with the code.

Just in case, here's the entire component:

import React from "react";
import * as d3 from "d3";
import Globe from "react-globe.gl";

function GlobeHome() {
  const { useState, useEffect, useRef } = React;

  const COUNTRY = "United States";
  const OPACITY = 0.1;

  const airportParse = ([
    airportId,
    name,
    city,
    country,
    iata,
    icao,
    lat,
    lng,
    alt,
    timezone,
    dst,
    tz,
    type,
    source,
  ]) => ({
    airportId,
    name,
    city,
    country,
    iata,
    icao,
    lat,
    lng,
    alt,
    timezone,
    dst,
    tz,
    type,
    source,
  });
  const routeParse = ([
    airline,
    airlineId,
    srcIata,
    srcAirportId,
    dstIata,
    dstAirportId,
    codeshare,
    stops,
    equipment,
  ]) => ({
    airline,
    airlineId,
    srcIata,
    srcAirportId,
    dstIata,
    dstAirportId,
    codeshare,
    stops,
    equipment,
  });

  const globeEl = useRef();
  const [airports, setAirports] = useState([]);
  const [routes, setRoutes] = useState([]);

  useEffect(() => {
    Promise.all([
      fetch(
        "https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat"
      )
        .then((res) => res.text())
        .then((d) => d3.csvParseRows(d, airportParse)),
      fetch(
        "https://raw.githubusercontent.com/jpatokal/openflights/master/data/routes.dat"
      )
        .then((res) => res.text())
        .then((d) => d3.csvParseRows(d, routeParse)),
    ]).then(([airports, routes]) => {
      const byIata = d3.indexBy(airports, "iata", false);

      const filteredRoutes = routes
        .filter(
          (d) =>
            byIata.hasOwnProperty(d.srcIata) && byIata.hasOwnProperty(d.dstIata)
        ) // exclude unknown airports
        .filter((d) => d.stops === "0") // non-stop flights only
        .map((d) =>
          Object.assign(d, {
            srcAirport: byIata[d.srcIata],
            dstAirport: byIata[d.dstIata],
          })
        )
        .filter(
          (d) =>
            d.srcAirport.country === COUNTRY && d.dstAirport.country !== COUNTRY
        ); // international routes from country

      setAirports(airports);
      setRoutes(filteredRoutes);
    });
  }, []);

  useEffect(() => {
    // aim at continental US centroid
    globeEl.current.pointOfView({ lat: 39.6, lng: -98.5, altitude: 2 });
  }, []);

  return (
    <Globe
      ref={globeEl}
      globeImageUrl="//unpkg.com/three-globe/example/img/earth-night.jpg"
      arcsData={routes}
      arcLabel={(d) => `${d.airline}: ${d.srcIata} &#8594; ${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}
      pointsData={airports}
      pointColor={() => "orange"}
      pointAltitude={0}
      pointRadius={0.02}
      pointsMerge={true}
    />
  );
}


export default GlobeHome;

Desktop (please complete the following information):
Mac, Chrome

Hex layer overlapping Labels layer

Describe the bug
I am using two layers, the Hex polygon and Labels layer as shown in:
https://react-globe.vercel.app/

As you can see, when the labels of transactions pop up around every 3 seconds, it gets covered partially by he hex layer around it. Is there a way to set the z-index of the Labels layer to be higher?

Expected behavior
The labels should not have their text obscured

Setting camera zoom doesn't respect controls().maxDistance and controls().minDistance

Hello @vasturiano! Amazing library, I absolutely love and appreciate the effort that's been put into this.

The issue I have is with zooming, so I have created two buttons one for zooming in and the other for zooming out. I change the zoom through:

function zoomInClick() {
  const camera = globeEl.current.camera();
  camera.zoom += .2;
  camera.updateProjectionMatrix();
}

But it completely ignores the value I set as controls().maxDistance:

const controls = globeEl.current.controls();
controls.maxDistance = 370;
controls.minDistance = 180;

How can I programmatically zoom in the globe and respect the maxDistance?

Expose onGlobeReady() to react component

Is your feature request related to a problem? Please describe.
I was looking for a way to adjust the scene settings once the globe has been loaded. For example, I'm trying to remove the directional light from the scene using scene.children[2].intensity = 0; but scene.children takes a while to load and isn't always available on render.

Describe the solution you'd like
I saw that onGlobeReady is available in globe.gl - would it be possible to expose this to the react cpt?

Describe alternatives you've considered
I've attempted using a callback ref for the globe element to watch for changes, but this broke my layers.

Additional context
After my country data loads, the first country in the list is selected and the globe moves into position. This all works fine, including disabling zoom controls, however manipulating directional light does not.

useEffect(() => {
    function getAltitudeByContainerWidth() {
    ...
    }

    if (globeEl.current) {
      const countryLocation = {
        lat: selectedCountry.lat,
        lng: selectedCountry.lng,
        altitude: getAltitudeByContainerWidth()
      };
      globeEl.current.controls().enableZoom = false; // disable zoom
      globeEl.current.pointOfView(countryLocation, 1000); // move globe into position
      const scene = globeEl.current.scene();
      if (scene.children) {
        // This does not work:
        scene.children[2].intensity = 0; // disable light
        // Uncaught TypeError: Cannot set property 'intensity' of undefined
      }
    }
  }, [selectedCountry]);

Ref missing when using dynamic import in Nextjs

Describe the bug
Hi i am building a globe using the library in NextJs, and due to: #1
I am dynamically importing the library to prevent SSR, in this manner:
const Globe = dynamic(import('react-globe.gl'), { ssr: false });

However when I do so, the ref pointing to the globe is missing and I am unable to call:
GlobeEl.current.controls().autoRotate = true; Globe.current.controls().autoRotateSpeed = 0.1;
where
const GlobeEl = useRef()
and
ref={globeEl}
is passed into Globe,

as shown in the example of https://github.com/vasturiano/react-globe.gl/blob/master/example/world-population/index.html
as current is undefined.

Is there a way to me to pass on the ref that was originally attached? Maybe using React.forwardRef or something

Change DirectionalLight

Hey!
How can I change DirectionalLight of globe? I need to change default "intensity" to 0

I use next, but it doesn't work for me

// some code
const globeEl = useRef()

useEffect(() => {
    const scene = globeEl.current.scene()
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0)
    scene.add(directionalLight, ambientLight)
}, [])

//some code

Need your help!

Can't auto rotate globe

Hello,
I'm using react-globe-gl with next JS and it's working fine for the most part, however i can't set auto rorate for the globe to any speed. in the ThreeGlobe library i was able to achieve this by doing Globe.rotation.y += 0.005;:

   function animate() {
      tbControls.update();
      Globe.rotation.y += 0.005;
      renderer.render(scene, camera);
      requestAnimationFrame(animate);
    }

However, in next i can't see any exposed property for this, also wheh i tried to access the exposed elements like globeEl.current.controls() it's always undefined.

Here is a high level code:

import dynamic from 'next/dynamic';
const Globe = dynamic(import('react-globe.gl'), { ssr: false });
const controls = globeEl.current.controls();
export default function Home() {
  const globeEl = useRef();
  const controls = globeEl.current.controls();==> controls always undefined

also when tried

  useEffect(() => {
    globeEl.current.pointOfView({ altitude: 3.5 });
  }, []);

I got the following error

Screen Shot 2021-04-04 at 1 50 07 AM

am I missing anything?

Performance issues

How can I best improve the performance of the globe? It is currently causing my google Lighthouse report to score a performance of 30 which is pretty bad

Here are some of the parameters, I am using. I have referred to https://github.com/vasturiano/react-globe.gl/issues/21
and turned most of them into memoized functions. Is there a way to better it?

Screenshot from 2021-01-22 03-10-27

How to disable pointer interaction

Is your feature request related to a problem? Please describe.
Hi, I would like to disable the pointer interaction such that the user cannot zoom into the globe nor drag around the canvas.

I have tried using the prop enablePointerInteraction and yet it does not work.

Screenshot from 2020-10-21 13-28-51

I have tried the following:

      enablePointerInteraction={[false]}
      enablePointerInteraction={false}
      enablePointerInteraction={()=>[false]}
      enablePointerInteraction={()=>false}

End of drag triggers click on Safari

When interacting with the globe in Safari (both Mac and iOS) the end of a drag event triggers a click (the onGlobeClick callback function is executed). This is not the case in other browsers, which is what I would expect.

Thank you for this great component!

Cannot Add Arcs to arcsData

Describe the bug
Once an arc is removed from arcsData no new arcs added to arcsData will be rendered

To Reproduce
Steps to reproduce the behavior:
Using this example: https://github.com/RomanBaiocco/react-globe.gl/blob/arcs_wont_update/example/arcs-bug/index.html

  1. Go to the globe
  2. Click on REMOVE LINE button on top left to remove arcs from arcsData.
  3. See that the removed arcs disappear from the render.
  4. Click on RESET to reset arcsData back to initial value.
  5. See that the arcs that have been added back are not rendered.

Expected behavior
The arcs were added back to arcsData should be rendered. They are definitely back in arcsData as you have to press the remove button as many times as you did before to start removing the arcs that still remain on the globe.

How to change the atmosphere color

Hi,

I have 3 questions about this amazing library (thank you!)

  • Is it possible to change the atmosphere blueish color?
  • I'm using the tile feature but I was wondering how I can display a tile only when I hover it and mask the rest by default?
  • Is it possible to pause the globe rotation when we hover it?

I hope it's possible!

Thanks

[bug] onLabelClick when set width and height

Describe the bug
Hi @vasturiano. Thanks for this very good library. I have one problem. When i use react-globe.gl/example/moon-landing-sites in my React Project, i set "onLabelClick = { (d) => console.log(d) }". It work normaly. But when i set attributes "width" and "height" of Globe at value 400 for exemple, the onLabelClick don't work. Have you un idee where have the problem ?

To Reproduce
In exemple "react-globe.gl/example/moon-landing-sites" :

  1. Set width and height attributes of Globe at 400.
  2. Start projet and go to web page.
  3. Click on "Apolo 15", "Luna 2" or other.
  4. See that nothing execute click event.

Expected behavior
Normally, a click event start. In the original example, a new page is open.

Desktop (please complete the following information):

  • OS: [Windows 10]
  • Browser [Firefox 79, Chrome 84]
  • Version [2.12.2]

Unable to use custom font

Describe the bug
I am unable to use custom font

What I have tried
I have used this website: http://gero3.github.io/facetype.js/
and generated a typeface json file from an otf file I had

I then did this:
import customFont from './telegraf_regular.json';

However it seems the font is distorted, eg. text appears blocked out

Screenshot from 2020-11-13 17-14-52

Could it be that I require some sort of text-loader?

Is it possible to adjust the initial globe position so it's not centered?

Hi - firstly, thank you so much for creating this library. I found it very easy to work with, despite being completely new to WebGL and 3D rendering in general.

I was wondering if it is possible to adjust the initial globe position so it is not centered. I can move it manually by adjusting the position of the underlying Three.js sphere, but then I would have to move all the points and atmosphere as well - so I was curious if there might be a better way?

Basically I need the canvas to take up the entire screen, but the globe should be more toward the bottom (vertically).

Thanks again for your work! :)

Cheers

broken on React 17

No matter what i try i keep getting this error only on React 17, prior versions were working fine:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Enabling Touch Events

First of all, thanks for creating a great library!

I wanted to try this library on mobile devices, but can't seem to get touchevents to work.
Would you happen to have a suggestion as to how this might be possible?

Look forward to hearing from you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.