Skip to content

Instantly share code, notes, and snippets.

@luciaaldana
Last active February 2, 2023 12:27
Show Gist options
  • Save luciaaldana/9796f682a692963e4f68791d7240883d to your computer and use it in GitHub Desktop.
Save luciaaldana/9796f682a692963e4f68791d7240883d to your computer and use it in GitHub Desktop.
Mapbox GL JS with React

Mapbox with React JS >= 18

Docs: https://docs.mapbox.com/mapbox-gl-js/guides/install/

Install the npm package:

npm install --save mapbox-gl

Include the CSS file in the of your HTML file.

<link href='https://api.mapbox.com/mapbox-gl-js/v2.12.0/mapbox-gl.css' rel='stylesheet' />

** If you're using a CSS loader like webpack css-loader, you can import the CSS directly in your JavaScript.

import 'mapbox-gl/dist/mapbox-gl.css';

DRAW MAP

import { useEffect, useRef } from 'react';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

const DrawMap = () => {
  mapboxgl.accessToken = 'YOUR_TOKEN';
  const mapContainer = useRef(null);
  const map = useRef(null);

  useEffect(() => {
    if (map.current) return;

    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox://styles/mapbox/streets-v12',
      center: [YOUR_LATITUD, YOUR_LONGITUD], // It is the point where the map will start
      zoom: 11,
    });

    // Added zoom and direction controllers
    map.current.addControl(new mapboxgl.NavigationControl());

    // Added controller to go to your current location
    const geolocate = new mapboxgl.GeolocateControl({ 
      positionOptions: {
        enableHighAccuracy: true,
      },
      trackUserLocation: true,
      showUserHeading: true,
    });
    map.current.addControl(geolocate);
  });

  return (
    <div className="mapContainer">
      <div ref={mapContainer} className="map" />
    </div>
  );
};

export default DrawMap;

DRAW MARKER

  
import { useEffect, useRef, useState } from 'react';
import mapboxgl from 'mapbox-gl';

const DrawMarker = () => {
  const MARKER_LIST = [{ latitud: -3.70744, longitud: 40.415402 }];

  mapboxgl.accessToken = 'YOUR_TOKEN';

  const mapContainer = useRef(null);
  const map = useRef(null);

  const drawMarkers = () => {
    MARKER_LIST.forEach(({ latitud, longitud }) => {
      new mapboxgl.Marker({
        color: 'blue',
        draggable: false,
      })
        .setLngLat([longitud, latitud])
        .addTo(map.current);
    });
  };

  useEffect(() => {
    if (map.current) return;

    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: 'mapbox://styles/mapbox/streets-v12',
      center: [MARKER_LIST[0].latitud, MARKER_LIST[0].longitud],
      zoom,
    });

    map.current.addControl(new mapboxgl.NavigationControl());

    const geolocate = new mapboxgl.GeolocateControl({
      positionOptions: {
        enableHighAccuracy: true,
      },
      trackUserLocation: true,
      showUserHeading: true,
    });
    map.current.addControl(geolocate);

    drawMarkers();
  });

  return (
    <div className="mapContainer">
      <div ref={mapContainer} className="map" />
    </div>
  );
};

export default DrawMarker;

EDIT DEFAUL MARKER

When we add our marker in this part of the code:

 new mapboxgl.Marker({
        color: 'blue',
        draggable: false,
      })
        .setLngLat([longitud, latitud])
        .addTo(map.current);
    });

We use the marker that mapbox has by default. We only change the color.

To edit this marker we are going to try changing it to a circle that we will create.

  const drawMarkers = () => {
    MARKER_LIST.forEach(({ latitud, longitud }) => {
      
      // we create our new marker
      const markCard = document.createElement('div');
      markCard.className = 'marker';
      markCard.style.backgroundColor = 'green';
      markCard.style.height = '15px';
      markCard.style.width = '15px';
      markCard.style.borderRadius = '50%';
      markCard.style.boxShadow = '1px 1px 10px 1px rgba(0,0,0,0.8)';

      // Add the marker in the map
      const marker = new mapboxgl.Marker(markCard).setLngLat([longitud, latitud]).addTo(map.current);
    });
  };

ADD ONCLICK TO MARKER

// After adding the marker:

const marker = new mapboxgl.Marker...;

marker.getElement().addEventListener('click', () => {
  handleClickMarker({...});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment