Generating a 3D model and integrating it with a 3D terrain display on Mapbox

My goal is to integrate a 3D model as a custom layer on Mapbox using Three.js, alongside adding a 3D terrain on the map. I have followed the documented examples for incorporating a 3D model and 3D terrain from Mapbox.

The issue I'm encountering is that the 3D model briefly appears until the terrain finishes loading, at which point it disappears. However, if I only load the model without the terrain, everything displays correctly.

The sequence of function calls involves loadTerrain() being called upon map load, which then triggers the loadModel() function:

async function loadTerrain() {
    mapRef.current?.getMap().addSource("mapbox-dem", {
      type: "raster-dem",
      url: "mapbox://mapbox.mapbox-terrain-dem-v1",
      tileSize: 512,
    });

    mapRef.current
      ?.getMap()
      .setTerrain({ source: "mapbox-dem", exaggeration: 1.5 });

    loadModel();
 }

function loadModel(fragGroup: any) {
    // Model configuration details here...
}

Incorporating react-map-gl within a Next.js application, my expectation was to seamlessly load both the model and terrain simultaneously. Unfortunately, the model vanishes once the terrain starts loading.

Answer №1

After loading the terrain layer, it is necessary to recalculate the projection Matrix using the anchor point's elevation in the standard example.

If you are interested, check out the Threebox Camera projection.

// Adjusting the height of 3D layers when including terrain layers: t.camera.z * worldSize
if (t.elevation) cameraWorldMatrix.elements[14] = t._camera.position[2] * worldSize;
// This.camera.matrixWorld.elements corresponds to t._camera._transform
this.camera.matrixWorld.copy(cameraWorldMatrix);

An example showcasing how to position a 3D model on terrain with Glacier d'Argentiere can be found here. I have been maintaining this repository for 4 years and this specific example has even been recognized as an official Mapbox example. https://i.stack.imgur.com/3bcHD.jpg

I hope this information proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to create a NextJS API route without including the "api" in the URL?

In the latest version of NextJS, version 13, I have set up an API route. You can access this endpoint at http://localhost:8080/api/foo/bar // pages/api/foo/bar.ts import { NextApiRequest, NextApiResponse } from "next"; export default async func ...

The curious case of ReactJs/NextJs useEffect(): Unveiling its mysterious double invocation

My custom useEffect() hook is consistently executed twice. It relies on two dependencies: reinitializePage (which triggers the useEffect when set to true) and corporateContext (which updates the component when the context changes). const [reinitializePage, ...

The occurrence of an Error [ERR_HTTP_HEADERS_SENT] arises due to the inability to modify headers after they have already been sent to

I have set axios to use credentials globally: axios.defaults.withCredentials = true However, when using the following useEffect hook, an error in the title is raised: useEffect(() => { const initAuth = async (): Promise<void> => { ...

What is the best way to adjust the value of largePageDataBytes in Next.js?

I am looking to modify the largePageDataBytes setting, despite knowing it may impact performance. I made an attempt in next.config.js with the following code: /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options h ...

Ways to transform information with SWR

I have developed two essential functions to manage data retrieval and manipulation. The first function is responsible for retrieving all quotes, handling mutations, and indicating loading status. // Fetcher and the baseUrl export const baseURL = 'http ...

Struggling to successfully upload a file to the Strapi upload API from a Next.js API route

Currently, I have implemented react dropzone on a specific page for the purpose of sending a file to an API route called /api/upload. Afterward, the file is supposed to be uploaded to a Strapi upload API using the following code: import formidable from &ap ...

What is the best way to upload custom fonts in a next.js application during its production phase?

Alright, so here's a question that might seem simple at first glance, but I've already combed through the next.js documentation and can't seem to find a solution. In my next.js project, I'm facing an issue that seems to be either a bug ...

The query to WpGraphQL results in a null response

I am currently working with a GraphQL query in Nexjs that is connected to headless Wordpress via the WpGraphQl plugin: export const GET_POSTS_BY_CATEGORY_SLUG = gql` query GET_POSTS_BY_CATEGORY_SLUG( $slug: String, $uri: String, $perPage: Int, $offset: In ...

Tips for rendering a server-side component within a client-side component in a React 18 - Next.js 14 application router

As outlined in this RFC: Server Components or call server hooks/utilities cannot be imported by Client Components, as they are specific to server functionality. Currently, I am developing a project using react v18.2 and nextjs v14 with app router integr ...

What steps can I take to troubleshoot and resolve this issue with the yarn.lock conflict

Currently, I am working on a next.js project using yarn and bitbucket. As I attempt to merge my branch with the origin, I encounter a conflict issue specifically related to the yarn.lock file. The differences between the version in the origin and that in ...

What are some ways to create a dynamic child server component?

Take a look at the following code snippet // layout.tsx export default function Layout({children}: any) { return <div> {children} </div> } // page.tsx export const dynamic = "force-dynamic"; const DynamicChild = dynamic( ...

Is there a solution for the error "Unable to persist the session" in a Next.js application that utilizes Supabase, Zustand, and Clerk.dev for authentication?

I have successfully set up a Next.js application with Clerk.dev for authentication and Supabase for data storage. I'm also leveraging Zustand for state management. However, an error is plaguing me, stating that there's "No storage option exists t ...

Encountering difficulty in identifying the error during data fetching on the server side of a Next.js application

I am attempting to troubleshoot an error with my Next.js server-side data fetching, but I am encountering two problems. export async function getStaticProps() { try { const fetchUrl = "some api url"; const resp = await axios.get(fetchUrl); ...

What could be causing the issue where only one of my videos plays when hovered over using UseRef?

I'm currently working on a project where I have a row of thumbnails that are supposed to play a video when hovered over and stop when the mouse moves out of the thumbnail. However, I've encountered an issue where only the last thumbnail plays its ...

A guide on updating various states using React Hooks

Creating a background component with the use of Vanta in NextJS, here's the code snippet: import { useEffect, useRef, useState } from "react"; import * as THREE from "three"; import FOG from "vanta/dist/vanta.fog.min"; im ...

The Vercel error indicates that the file or directory '/var/task/node_modules/shiki/themes/one-dark-pro.json' does not exist

import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype ...

Unable to access attributes of an unknown object (referencing 'Person')

I'm currently facing an issue when trying to POST data from my Next.js project to my MySQL database. Here is my frontend code: import React from 'react' import { useReducer, useEffect, useState } from 'react' import Axios from &ap ...

What is the significance of the command 'npm install -D sass'?

Recently, I've been delving into the world of using sass with Next.js. After scouring through various documents, I finally stumbled upon a solution that involved running npm install -D sass. While I'm familiar with the fact that npm stands for no ...

What are some strategies for maximizing the value of the initial click?

For the past few days, I've been struggling with this particular aspect of the project. Despite extensive research, I haven't been able to find a solution. The issue lies in retrieving a variable from the contextAPI. Although it updates to the co ...

Setting the port for Next.js on PM2 involves configuring the ecosystem file in the project

I am currently working on a standard next js application and have the following scripts in my package.json file. "scripts": { "dev": "next dev", "build": "next build", "start": " ...