Coder Social home page Coder Social logo

three-geo's Introduction

three-geo

NPM MIT licensed CI

three-geo is a three.js based geographic visualization library. Using three-geo, we can easily build satellite-textured 3D terrain models in near real-time by simply specifying GPS coordinates anywhere on the globe. The geometry of the terrain is based on the RGB-encoded DEM (Digital Elevation Model) provided by the Mapbox Maps API.

The terrain is represented by standard THREE.Mesh objects. This makes it easy for us to access underlying geometry/texture array and perform original GIS (Geographic Information System) experiments in JavaScript. (See Usage for how to programatically obtain those mesh objects).

Credits: this library has been made possible thanks to

Demo

1) examples/geo-viewer (live | source code)

This demo app includes features such as

  • on-demand 3D terrain building (by a mouse click on the Leaflet map),
  • real-time camera projection onto Leaflet (with oritentaion and HFoV indication),
  • terrain interaction with a VR-like laser beam,
  • measuring Euclidean distances between terrain points,
  • auto camera orbiting around the custom z-axis.

Live:

2) examples/heightmaps (live | source code)

This demo illustrates the relationship between a reconstructed 3D terrain and its underlying satellite/DEM tiles.

image

3) examples/flat (live | source code)

How to get a flattened view of the terrain by post-editing the underlying geometry.

4) examples/projection (live | source code)

How to register a new 3D object on top of the terrain based on its geographic location [latitude, longitude, elevation].

Setup

Installation

$ npm i three-geo

Loading

Script tag: use ThreeGeo after

<script src="dist/three-geo.min.js"></script>

ES6:

import ThreeGeo from 'dist/three-geo.esm.js';

Usage

Here is an example of how to build a geographic terrain located at GPS coordinates (46.5763, 7.9904) in a 5 km radius circle. The terrain's satellite zoom resolution is set to 12. (The highest zoom value supported is 17.)

For standalone tests, use examples/simple-viewer (source code).

For use with NodeJS, do enable this isNode option as well.

const tgeo = new ThreeGeo({
    tokenMapbox: '********', // <---- set your Mapbox API token here
});

const terrain = await tgeo.getTerrainRgb(
    [46.5763, 7.9904], // [lat, lng]
    5.0,               // radius of bounding circle (km)
    12);               // zoom resolution

const scene = new THREE.Scene();
scene.add(terrain);

const renderer = new THREE.WebGLRenderer({ canvas });
renderer.render(scene, camera);

image

Who is using three-geo?

API

In this section, we list three-geo's public API methods, where origin, radius, and zoom are parameters common to them:

  • origin Array<number> Center of the terrain represented as GPS coordinates [latitude, longitude].

  • radius number Radius of the circle that fits the terrain.

  • zoom number (integer) Satellite zoom resolution of the tiles in the terrain. Select from {11, 12, 13, 14, 15, 16, 17}, where 17 is the highest value supported. For a fixed radius, higher zoom resolution results in more tileset API calls.

ThreeGeo

  • constructor(opts={})

    Create a ThreeGeo instance with parameters.

    • opts.tokenMapbox="" string Mapbox API token. This must be provided.

    • opts.unitsSide=1.0 number The side length of the square that fits the terrain in WebGL space.

    • opts.isNode=false boolean To use three-geo with NodeJS, you must explicitly set this option to true. [ Added in v1.4.5 ]

  • async getTerrainRgb(origin, radius, zoom) [ Added in v1.4 ]

    Return a THREE.Group object that represents a 3D surface of the terrain.

    The group object contains an Array<THREE.Mesh> as .children. Each mesh corresponds to a partial geometry of the terrain textured with satellite images.

  • async getTerrainVector(origin, radius, zoom) [ Added in v1.4 ]

    Return a THREE.Group object that represents a 3D contour map of the terrain.

    The group object contains an Array<THREE.Object3D> as .children. Each child object is either an extruded THREE.Mesh with .name attribute prefixed by dem-vec-shade-<ele>-, or a THREE.Line with .name prefixed by dem-vec-line-<ele>- (<ele> is the height of each contour in meters).

  • getProjection(origin, radius, unitsSide=1.0) [ Example ]

    Return an object { proj, projInv, bbox, unitsPerMeter } that includes transformation-related functions and parameters, where

    • proj(latlng) is a function that maps geo coordinates latlng (an array [lat, lng]) to WebGL coordinates [x, y].

    • projInv(x, y) is a function that maps WebGL coordinates [x, y] to geo coordinates [lat, lng].

    • bbox is an array [w, s, e, n] that represents the computed bounding box of the terrain, where w (West) and e (East) are longitudinal limits; and s (South) and n (North) are latitudinal limits.

    • unitsPerMeter is the length in WebGL-space per meter.

Legacy callback based API
  • getTerrain(origin, radius, zoom, callbacks={})

    • callbacks.onRgbDem function (meshes) {} Implement this to request the geometry of the terrain. Called when the entire terrain's geometry is obtained.

      • meshes Array<THREE.Mesh> All the meshes belonging to the terrain.
    • callbacks.onSatelliteMat function (mesh) {} Implement this to request the satellite textures of the terrain. Called when the satellite texture of each mesh belonging to the terrain is obtained.

      • mesh THREE.Mesh One of the meshes that's part of the terrain.
    • callbacks.onVectorDem function (objs) {} Implement this to request the contour map of the terrain. Called when the contour map of the terrain is obtained.

      • objs Array<THREE.Object3D> Extruded meshes (THREE.Mesh objects with .name attribute prefixed by dem-vec-shade-<ele>-) and lines (THREE.Line objects with .name attribute prefixed by dem-vec-line-<ele>-), where <ele> is the height of each contour in meters.

Build

After git clone and cd to the repository,

$ npm i
$ npm run build

Building on Windows

While npm run build on Windows is confirmed to work (via GitHub's workflow with some tweaks), for better results, it is recommended to use WSL2 instead (thanks @sonicviz for reporting this).

three-geo's People

Contributors

j-devel avatar johncoene 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

three-geo's Issues

How to get the mouse click model?

I've tried this, but it doesn't work.

const { offsetX, offsetY } = event; 
const x = (offsetX / window.innerWidth) * 2 - 1;
const y = - (offsetY / window.innerHeight) * 2 + 1;
const mousePoint = new THREE.Vector2(x,y);
let raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mousePoint, camera);
var intersects = raycaster.intersectObjects(scene.children ,true);
for (var i = 0; i < intersects.length; i++) {
     intersects[i].object.material.color.set(0xff0000);
 }

Looking forward to your reply

How to retrieve Lat/Log from WebGL Coordinates?

The function getProjection returns 2 other functions proj and projInv I would assume that calling projInv giving the values retrieved from proj should return the "inverse" however it doesnt seems to be working correctly.. given this example:

const latlog = proj([46.5775, 8.0052]) // returns x-> 0.08057597127180505, y-> 0.2778929650063131
const inverse = projInv(0.08057597127180505, 0.2778929650063131) // -> 46.59840265750662, 8.033210992856766

as you can see the inverse isn't returning the correct value 46.5775, 8.0052

Do you have any idea how to translate the WebGL Coordinates back to Lat/Lon?

Add geometries

Thank you so much for the awesome library.

I was toying with the idea of adding geometries, e.g.: a point.

var dotGeometry = new THREE.Geometry();
dotGeometry.vertices.push(new THREE.Vector3( longitude, elevation, latitude));
var dotMaterial = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
var dot = new THREE.Points( dotGeometry, dotMaterial );
scene.add( dot );

However doing the above places the points way off, I assume there is some rescaling done internally but looking through the source code I cannot find out where or how.

How should I go about doing this?

How to reference in Vue

I use it this way in Vue component,but it throws an error:THREE is not defined

import * as THREE from "three";
import ThreeGeo from 'three-geo/dist/three-geo.esm.js';

error with es-pack-js when executing 'npm i'

Hope someone know this problem. I just clone this repo, cd three-geo and npm i, then comes this error below.

node ./postinstall.js

Thank you for installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/)

[email protected] postinstall D:\gisdemo8threejs\three-geo\node_modules\es-pack-js
(cd ./node-polyfill && npm run install); (cd ./rustwasm-polyfill && npm i);

此时不应有 (cd。
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\es-pack-js\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] postinstall: (cd ./node-polyfill && npm run install); (cd ./rustwasm-polyfill && npm i);
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

Consider A-Frame

Hi, have you considered creating an A-Frame component for your geographic visualization library? This would allow for mixing the visualizations with other developed components and make VR access automatic. In the example below, I created a simple version of what such a component could look like for three-geo, and placed it in a scene with an environment component and VR hand control components.

Sample:
https://jet-wasp.glitch.me/

Source Code:
https://glitch.com/edit/#!/jet-wasp?path=index.html:71:27

Change number of vertices

Is there a way to specify how many vertices you want the downloaded tile to contain, with three.geo?
By default it seems to download a terrain with a fairly large amount of edge loops, vertices - more than I really need for my project - so I was wondering if it was possible to change that.
Many thanks.

Draw a line on openstreemap( via leaflet) and extrude something in threejs in this geo-viewer example?

Hi there,
geo-viewer is an amazing example and I am learning it (in three-geo/examples/geo-viewer/io/).

I would like to add something onto both openstreemap via leaflet and threejs in this geo-viewer example. Any documentations or suggestions? It is really appreciated if a demo is available for the above purpose.

Also, It is hard to read app.min.js, where can I get the unminified version?

Thanks a lot.

ouyang

require("THREE") should be require("three")

Hi - Thanks for the great library! I'm using three-geo along side three.js in my application. dist/three-geo.min.js has require('THREE') which webkit will not compile as it is not the right case. Changing the min.js to use require("three") works just fine.

If this is just a setup issue on my side I apologize - but typically npm packages are all lower case. Might make sense to update this.

Thanks!

Support for flat terrain without excessive geometry data

Hello,

There is an example for a flat terrain, but the implementation is pretty crude - just reseting each vertice's z-position. Could we instead have an option where the PlaneGeometry is not extruded at all but instead consists of 4 vertices? That would greatly help with performance.

how to store the terrain in js object ?

Hello , i am getting the problem while storing the terrain into an object by using the toJSON on mesh it gives me error Failed to execute 'drawImage' on 'CanvasRenderingContext2D' please any way to store it in js objects so i store it in db and save the api call , @j-devel any thoughts on this

Hi i need your urjent help please i want to draw some border on the terrain with the help of lat and long

this let long i want to use to draw a border
[[-77.30522819340669,42.96423763352498],[-77.3059223734583,42.964179176325736],[-77.30668664897728,42.964067083163854],[-77.3062256437749,42.96254712071273],[-77.30674026959481,42.962037292662025],[-77.3073391876918,42.96189235179205],[-77.3072505717396,42.96128261626483],[-77.30118424335645,42.96211363781834],[-77.29794874261192,42.962547626807506],[-77.29845792709837,42.96430285852641],[-77.29914301403079,42.96436576542904],[-77.299744691128,42.96441565552973],[-77.30058236572809,42.964404467143545],[-77.30157247952,42.964465480488535],[-77.3017170473554,42.96458163125009],[-77.301809685117,42.96475991519502],[-77.30191431818879,42.965268665784514],[-77.3019381500124,42.96572107107565],[-77.3057054275332,42.966113539621055],[-77.30522819340669,42.96423763352498]]

All dependencies listed as development only

In the package.json all dependencies are listed as dev. If installing via npm, these are not included with the package itself even though they are used explicitly and required to use three-geo.

At least the packages below should probably be under dependencies, so that users of this package don't have to list them as explicit dependencies when importing.

`These dependencies were not found:

  • @mapbox/sphericalmercator in ./node_modules/three-geo/src/index.js
  • @mapbox/tile-cover in ./node_modules/three-geo/src/index.js
  • @mapbox/tilebelt in ./node_modules/three-geo/src/index.js
  • @mapbox/vector-tile in ./node_modules/three-geo/src/index.js
  • @turf/area in ./node_modules/three-geo/src/index.js
  • @turf/destination in ./node_modules/three-geo/src/index.js
  • @turf/helpers in ./node_modules/three-geo/src/index.js
  • @turf/intersect in ./node_modules/three-geo/src/index.js
  • @turf/transform-translate in ./node_modules/three-geo/src/index.js
  • @turf/union in ./node_modules/three-geo/src/index.js
  • get-pixels in ./node_modules/three-geo/src/index.js
  • pbf in ./node_modules/three-geo/src/index.js
  • xhr in ./node_modules/three-geo/src/index.js

To install them, you can run: npm install --save @mapbox/sphericalmercator @mapbox/tile-cover @mapbox/tilebelt @mapbox/vector-tile @turf/area @turf/destination @turf/helpers @turf/intersect @turf/transform-translate @turf/union get-pixels pbf xhr
`

I'm happy to make a pr for this, but the solution is just the above code which will populate dependencies.

Loading custom DEM data (GeoTIFF) instead of Mapbox data

Is there a way wherein we can add a custom layer with elevation data instead of the mapbox satellite data. For example, if we have a DEM Geotiff that is routed through the geoserver as tiled layer, can we make use of it instead of the mapbox satellite imagery?

getTerrainRgb returns Promise { <state>: "rejected" }

Problem:

the getTerrainRgb method returns a rejected Promise

I'm calling the following inside a useEffect() React hook:

const ioToken = <mytoken>
const tgeo = new ThreeGeo({
                    tokenMapbox: ioToken,
});

async function fetchGeo() {
    const terrain = await tgeo.getTerrainVector(
                        [0.0, 0.0], // [lat, lng]
                        1.0,               // radius of bounding circle (km)
                        13)               // zoom resolution
    fgRef.current.scene().add(terrain)
                    };               

fetchGeo();

what happens
The getTerrainRgb method returns a rejected Promise

additional comments
The fgRef.current.scene().add() method is from react-force-graph.

I've checked that the mapbox API token is valid.

Any ideas why it's not working?

How to reduce vertex count?

How to reduce vertex count?

Currently it is using 128 * 128

I hope to reduce that to 30

There is any solution?

Invalid in node

I already set useNodePixels: truein the constructor,but the children of the object is empty.The same code is available in browsers.

My approach is to add global.require = require;const THREE = require("three") to the head of the file and add module.exports = ThreeGeo at the end of the file.

I would like to ask if my usage is wrong. I look forward to your reply

How to cache tiles on the Web side

My project needs a large radius, so it takes too long to download tiles. I want to implement caching on the Web side, how to achieve it?

Change mapbox API endpoint?

It looks like the URIs in getUriMapbox() are hardcoded. It would be really nice if they could be customized to use, say, a custom style, like https://api.mapbox.com/styles/v1/cobertos/ckg6pj7f52ixh19pnzt7ix48z/tiles/256/{z}/{x}/{y}

none of the live demo's work

all examples have error :
Uncaught (in promise) TypeError: Super expression must either be null or a function
at app.esm.dev.js:2:341338
at app.esm.dev.js:2:341510
at Object.7240 (app.esm.dev.js:2:343246)
at n (app.esm.dev.js:2:480766)
at app.esm.dev.js:2:481372
at app.esm.dev.js:2:481381

Customize height and width of the scene

I added my custom elevation data instead of the one from the Mapbox API and used the same satellite map to apply the texture. Everything works perfectly. But I was looking to somehow customize the height and width of the scene.

Suppose I have a DEM data(a tile) of 50mx50m. In this scenario, the height and width of the scene seems to be fixed. The correct elevation data will be shown only for 50mx50m but the satellite imagery for the remaining area will be shown with incorrect elevation. To prevent this, the only option is to change the size of the scene as per the tile size that is being loaded.

I'm unable to find the actual code where this is being set. It would be great if we could customize the scene height and width dynamically.

export height maps

This is a great project. I hope to add a mouse to customize the range of polygons to generate or export height maps. Thank you very much.

How can I exaggerate elevation?

I want to display small hills on a marathon track as mountains.
How can I exaggerate elevation?

And is it possible to add GPS-track line on top of the map?

Thanks!

Image quality

I am able to understand that you are using mapbox for satelitte image . I want to improve the image quality means i want to see the objects more clearly in image my zoom is 17.

Error when executing npm

Hello,

I have some problems with the npm execution. I have some problems with the npm execution. The log file is below :

Capture

I managed to get the library to work with the dist file, which is your already packaged lib. However, I was not able to use your library from source. Do you know how I could fix this? I work on windows.

PS : What is deltaSeams ?
Array tile size = "3x128x128 (+ deltaSeams)"

install error

when i running npm i three-geo

npm ERR! path C:mythree\node_modules\three-geo
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c ([ -d './examples' ] && cd ./examples/geo-viewer && npm i || true);
npm ERR! '[' �����ڲ����ⲿ���Ҳ���ǿ����еij���
npm ERR! ���������ļ���
npm ERR! 'true' �����ڲ����ⲿ���Ҳ���ǿ����еij���
npm ERR! ���������ļ���

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\AppData\Local\npm-cache\_logs\2023-04-23T02_13_39_783Z-debug-0.log

what should i do? i can't install three-geo

Q: How do you calculate terrain height relative to the position units in three.js, which are also dependant on the zoom factor?

Q: How do you calculate terrain height relative to the position units in three.js, which are also dependant on the zoom factor?

For example, if I want to position an object 1m above sea level (which according to https://docs.mapbox.com/data/tilesets/guides/access-elevation-data/#mapbox-terrain-rgb sea level is 0) how do I translate that into a relative mesh position,z value that will translate it a unit of 1m (or 10m or whatever) relative to the scale of the mesh terrain elevation?

Also. how does that position calculation change based on the zoom factor, which can be from 11 to 17?

https://docs.mapbox.com/help/glossary/zoom-level/ doesn't give me much of a solution either.

Thanks!

How to get elevation of points?

In geo-viewer, clicking a point gives all x,y, and z coordinates of a point. However, I could not find how that is done. Can someone please help?
Much appreciated.

how to set coordinate system in three-geo

Hi,
For an engineering purpose, I would like to set Z axis (blue color) as up one and X (red), Y(green) as a ground plane. I try
THREE.Object3D.DefaultUp = new THREE.Vector3(0,0,1);
which seems not changing the default coordinate system (y (green) is up) in three-geo.

Thanks a lot.

ouyang

Deprecated parameters

Hello,

As of Jun 1, 2020, Mapbox stopped supporting classic styles. (link).

Can you please update the source code? I tired to do it myself, but looks like some styles are created by you, and the new version needs username.

Aligning multiple tiles together

So first of all, I'm not entirely sure if this is the right place to put this because it's more of a question - so let me know if there is a better place to put it.

My question is, adding an individual tile with three.geo is of course very easy. But how do I add multiple tiles next to each other - specifically how do I align them so that their satellite and elevation data(s) line up? The positions of the tiles also of course need to line up too.
The use case for this, is to hopefully do a small program involving flying through different tiles - so I'm just wondering how this would be possible.

Many thanks for your time.

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.