1

I'm trying to implement a globe always stays visible no matter the size of the container. I looked at this example, but working with a globe it seems difficult to find the correct bounding box values. Maybe there's a better strategy for achieving this altogether?

Codesandbox

Code:

import * as React from "react";
import mapboxgl from "mapbox-gl";
import Markers from "./markers";
import "mapbox-gl/dist/mapbox-gl.css";

// Globe.jsx
const Globe = () => {
  const mapContainer = React.useRef();
  const [map, setMap] = React.useState();

  const places = [
    {
      name: "Marker",
      longitude: 22.6526884,
      latitude: 65.9140751
    }
  ];

  React.useEffect(() => {
    const map = new mapboxgl.Map({
      container: mapContainer?.current,
      accessToken:
        "pk.eyJ1IjoicGVyc3R1cmVzc29uIiwiYSI6ImNsaDdwd2F1bzAxMmszZXBzZzlqcnl6eGQifQ.5u3IT1QxeDrF0W7jqbyrtQ",
      center: [17.104528, 51.395612],
      style: "mapbox://styles/mapbox/satellite-v9",
      zoom: 2.5,
      projection: { name: "globe" }
    });

    map.scrollZoom.disable();
    setMap(map);

    return () => map.remove();
  }, []);

  const fitBounds = () => {
    const bbox = [
      [-25, -5],
      [40, 80]
    ];
    map.fitBounds(bbox, {
      padding: { top: 10, bottom: 10, left: 10, right: 10 }
    });
  };

  return (
    <>
      <div
        ref={mapContainer}
        style={{ aspectRatio: 4 / 3 }}
      >
        {places && map && <Markers map={map} places={places} />}
      </div>
      <button onClick={fitBounds}>fit globe to container</button>
    </>
  );
};

export default Globe;

// Markers.jsx
import * as React from "react";
import mapboxgl from "mapbox-gl";

const Marker = ({ map, place }) => {
  const markerRef = React.useRef();

  React.useEffect(() => {
    const marker = new mapboxgl.Marker({
      anchor: "right"
    })
      .setLngLat([place.longitude, place.latitude])
      .addTo(map);

    return () => marker.remove();
  }, []);

  return <div ref={markerRef} />;
};

const Markers = ({ map, places }) => {
  return (
    <>
      {places &&
        places.map((place) => (
          <Marker key={place.name} map={map} place={place} />
        ))}
    </>
  );
};

export default Markers;
INT
  • 910
  • 4
  • 21
  • 45

0 Answers0