Hello World 2.0
· 2 min read
My first hello world post included the famous "earthrise" Apollo 8 photo. Just for fun here's an interactive 3D globe in the browser. Compliments of Mapbox, using their free tier. This demo uses a React .tsx component in a docusaurus .mdx page...
- 3D Globe
- Source Code
// filename map.tsx
import { useRef, useEffect, useState } from "react";
export const MapComponent = () => {
const mapContainer = useRef(null);
const map = useRef(null);
const [mapboxgl, setMapboxgl] = useState(null);
// effect: react reference to the window mapboxgl object. mapboxgl is loaded in <head>.
useEffect(() => {
if (window.mapboxgl) {
setMapboxgl(window.mapboxgl);
} else {
const checkMapboxGL = setInterval(() => {
if (window.mapboxgl) {
setMapboxgl(window.mapboxgl);
clearInterval(checkMapboxGL);
}
}, 10);
return () => clearInterval(checkMapboxGL);
}
}, []);
// effect: setup and tear down map component
useEffect(() => {
if (map.current || !mapboxgl) return;
// setup access token
mapboxgl.accessToken = '*****'
// create map
map.current = new mapboxgl.Map({
container: mapContainer.current,
projection: 'globe',
style: 'mapbox://styles/mapbox/standard-satellite',
center: [-85, 30], // lon, lat
zoom: 1.5,
});
map.current.on('style.load', () => {
map.current.setFog({
color: 'rgb(186, 210, 235)', // Lower atmosphere
'high-color': 'rgb(36, 92, 223)', // Upper atmosphere
'horizon-blend': 0.02, // Atmosphere thickness (default 0.2 at low zooms)
'space-color': 'rgb(11, 11, 25)', // Background color
'star-intensity': 0.6 // Background star brightness (default 0.35 at low zoooms )
});
});
map.current.addControl(new mapboxgl.NavigationControl());
return () => {
if (map.current) {
map.current.remove();
}
}
}, [mapboxgl]);
return <div ref={mapContainer} style={{ height: '500px', width: '100%' }}></div>;
};
A globe! Yes, you're very clever. (reference: map projections explained in XKCD #977)