Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· OpenAIAi2 WildChat-4.8M (AI2)

I want to use the globe.gl function: "onGlobeReady(fn) Callback function to invoke…

  1. User

    I want to use the globe.gl function: "onGlobeReady(fn) Callback function to invoke immediately after the globe has been initialized and visible on the scene. " to figure out when the globe is ready and use the time taken a the duration for the transition motion div's in the transition component but it should only apply on the pageProp for the root page ("/"). The overall goal is to keep the transition for as long as it takes to render the globe so that a user does not get shown a blank space as the globe loads. My codebase snippets with relavant files for modification with new logic: GlobeComponent.jsx: import React, { useEffect, useState, useRef } from 'react'; import Globe from 'react-globe.gl'; import * as THREE from 'three'; import { useRouter } from 'next/router'; import countries from './files/globe-data-min.json'; import travelHistory from './files/my-flights.json'; import airportHistory from './files/my-airports.json';

    const GlobeComponent = () => { const [arcsData, setArcsData] = useState([]); const router = useRouter(); const globeRef = useRef();

    useEffect(() => {
        // Check if the globe instance is loaded
        if (globeRef && globeRef.current) {
                const kenyaCoordinates = {
                    lat: 2.286389, // latitude for Nairobi, Kenya
                    lng: 18.82023 // longitude for Nairobi, Kenya
                   
                };
                globeRef.current.pointOfView(kenyaCoordinates, 3000); // Animate the camera movement over 3000ms (3 seconds)
        }
    }, []);
    
    
    useEffect(() => {
        const handleRouteChange = () => {
            // You could update state here to ensure fresh data is fetched when a route changes
            setArcsData(travelHistory.flights);
        };
    
        router.events.on('routeChangeComplete', handleRouteChange);
    
        // Fetch the initial data
        setArcsData(travelHistory.flights);
    
        return () => {
            router.events.off('routeChangeComplete', handleRouteChange);
        };
    }, [router.events]);
    
    return (
        <Globe
            ref={globeRef}
            hexPolygonsData = { countries.features }
            hexPolygonResolution = { 3}
            hexPolygonMargin = {0.75}
            hexPolygonAltitude = {0.01}
            hexPolygonUseDots = {false}
            enablePointerInteraction ={false}
            showAtmosphere = { true}
            atmosphereColor="#ffffff"
            atmosphereAltitude = { 0.1}
            backgroundColor="rgba(0, 0, 0, 0)" 
            globeImageUrl="//unpkg.com/three-globe/example/img/earth-dark.jpg"            
            hexPolygonColor = {(e) => {
            return ["KEN", "CHN", "FRA", "ZAF", "JPN", "USA", "AUS", "CAN"].includes(e.properties.ISO_A3)
                ? "#9cff00"
            : "rgba(255, 255, 255, 0.5)";
            }}
            width={1100}
            height={1100}
            arcsData={arcsData}
            arcColor = {(e) => {
                return e.status ? "#9cff00" : "#f13024";
            }}
            arcAltitude = {(e) => {
                return e.arcAlt;
            }}
            arcStroke = {(e) => {
                return e.status ? 0.5 : 0.3;
            }}
            arcDashLength = { 0.9}
            arcDashGap = { 4}
            arcDashAnimateTime = { 1000}
            arcsTransitionDuration = { 1000}
            arcDashInitialGap = {(e) => e.order * 1}
            labelsData = { airportHistory.airports }
            labelColor={() => "#ffffff"}
            labelDotOrientation = {(e) => {
                return e.text === "NGA" ? "top" : "right";
            }}
            labelDotRadius = { 0.35}
            labelSize = {1.1}
            labelText = {"city" }
            labelResolution = { 6}
            labelAltitude = { 0.07}
            pointsData = { airportHistory.airports }
            pointColor={() => "#ffffff"}
            pointsMerge = { true}
            pointAltitude = { 0.07}
            pointRadius = { 0.10}
        />
    );
    

    };

    export default GlobeComponent; Transition.jsx: import { motion } from "framer-motion"; import { useState, useEffect } from "react"; import ParticlesContainer from "./ParticlesContainer";

    const Transition = () => { const [isLoaded, setIsLoaded] = useState(false); const transitionVariants = { initial: { x: "100%", width: "100%", }, animate: { x: "0%", width: "0%", }, exit: { x: ["0%", "100%"], width: ["0%", "100%"], }, };

    useEffect(() => { const handleLoad = () => { setIsLoaded(true); }

    window.addEventListener('load', handleLoad);
    
    return () => {
      window.removeEventListener('load', handleLoad);
    };
    

    }, []);

    return ( <> {!isLoaded && ( <motion.div role="status" className="fixed top-0 bottom-0 right-full w-screen h-screen z-30 bg-[#2e2257]" variants={transitionVariants} initial="initial" animate="animate" exit="exit" transition={{ delay: 0.2, duration: 0.6, ease: "easeInOut" }} aria-hidden > <motion.img src="/logo.svg" alt="Descriptive text" style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '500px', height: '500px' }} /> </motion.div> )} <motion.div role="status" className="fixed top-0 bottom-0 right-full w-screen h-screen z-20 bg-[#3b2d71]" variants={transitionVariants} initial="initial" animate="animate" exit="exit" transition={{ delay: 0.4, duration: 0.6, ease: "easeInOut" }} aria-hidden /> <motion.div role="status" className="fixed top-0 bottom-0 right-full w-screen h-screen z-10 bg-[#4b3792]" variants={transitionVariants} initial="initial" animate="animate" exit="exit" transition={{ delay: 0.6, duration: 0.6, ease: "easeInOut" }} aria-hidden />

    </>
    

    ); };

    export default Transition; _app.jsx: import { AnimatePresence, motion } from "framer-motion"; import { useRouter } from "next/router";

    import Layout from "../components/Layout"; import Transition from "../components/Transition";

    import "../styles/globals.css";

    function MyApp({ Component, pageProps }) { const router = useRouter();

    return ( <motion.div key={router.route} className="h-full"> <Component {...pageProps} /> </motion.div> ); }

    export default MyApp;

  2. Assistant

    To achieve the desired effect where the transition duration is explicitly tied to the globe's load completion, you'll need to communicate between the GlobeComponent and the Transition component. In this case, we'll use React.Context to provide the app-wide state representing whether the Globe is ready. When the Globe is ready (onGlobeReady), you can update this state and have the Transition component listen to that state to control the exit animation. Here's a step-by-step guide:

    1. Create a new context file for storing whether or not the globe is ready:
    // GlobeContext.js
    import { createContext, useContext } from 'react';
    
    const GlobeContext = createContext();
    
    export const useGlobe = () => useContext(GlobeContext);
    export default GlobeContext;
    
    1. Update _app.jsx to include a provider for the new context:
    import GlobeContext from '../contexts/GlobeContext';
    
    function MyApp({ Component, pageProps }) {
      const [globeReady, setGlobeReady] = useState(false);
      const router = useRouter();
    
      // ...
    
      return (
        <GlobeContext.Provider value={{ globeReady, setGlobeReady }}>
          // existing code...
        </GlobeContext.Provider>
      );
    }
    
    1. In GlobeComponent.jsx, use onGlobeReady from react-globe.gl and update the context state accordingly:
    import { useGlobe } from './path_to_GlobeContext';
    
    const GlobeComponent = () => {
      // existing code...
    
      const { setGlobeReady } = useGlobe();
    
      // Call setGlobeReady when the Globe is ready
      useEffect(() => {
        if (globeRef.current) {
          globeRef.current.onGlobeReady(() => {
            setGlobeReady(true);
          });
        }
      }, [globeRef, setGlobeReady]);
    
      // existing return...
    };
    
    1. Modify Transition.jsx to respond to the globe-ready state:
    import { useGlobe } from './path_to_GlobeContext';
    
    const Transition = () => {
      const { globeReady } = useGlobe();
    
      // existing code...
    
      return (
        <>
          {!globeReady && (
            // existing motion.div code
          )}
          // existing motion.div code
        </>
      );
    };
    
    export default Transition;
    

    Ensure to replace path_to_GlobeContext with the correct path to your GlobeContext.js file.

    By following these steps, you have created a global state that tracks whether the globe is ready. When the globe loads and is ready, the onGlobeReady function will update the context, which in turn will trigger an update in the Transition component to hide the transition elements. This approach ensures that the transition only occurs once the globe is ready and thus avoids showing a blank space as the Globe loads.

    Remember that the onGlobeReady function should be a part of the globe library you are using (react-globe.gl or another). If it is not exposed by default within the react-globe.gl library, you might need to call a different function or access the underlying THREE.js globe instance to detect when it's ready directly. If that's the case, you might want to wrap your direct Three.js manipulation in a useEffect hook with an appropriate cleanup to avoid memory leaks or unwanted side effects.