React Mapbox 1

by dollysingh3192

HTML

<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css">
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf8" />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <link href='https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css' rel='stylesheet' />
  </head>
  <body>
   <div id="root"></div>
  </body>
</html>

CSS

#container {
  display: flex;
  justify-content: space-between;
  background-color: lightyellow;
}

#container > div {
  width: 100px;
  height: 100px;
  border: 2px dashed red
}

JavaScript

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


import './App.css';
import './style.css';

mapboxgl.accessToken = 'pk.eyJ1IjoiZWdyb2ptb25yb3kiLCJhIjoiY2tlcHczMW1qMGxweTJycnc4Y2pqYTl6OSJ9.1Ost6s4IRPVPBaf-pqjprw';

const App = () => {
  const mapContainerRef = useRef(null);
  const [_map, setMap] = useState(null);
  const addBuildingPopUp = (e) => {
    console.log("COORD", e.features[0].geometry);
  } 
  const removeEvent = () => {
    if(_map) {
      console.log("REMOVING EVENT");
      _map.on('mousemove', 'mapillary', addBuildingPopUp);
    }
  }
  // initialize map when component mounts
  useEffect(() => {
    const map = new mapboxgl.Map({
      container: mapContainerRef.current,
      // See style options here: https://docs.mapbox.com/api/maps/#styles
      style: 'mapbox://styles/mapbox/streets-v11',
      zoom: 12,
      center: [-87.622088, 41.878781]
    });

    // add navigation control (the +/- zoom buttons)
    map.addControl(new mapboxgl.NavigationControl(), 'bottom-right');
    map.on("load", () => { 
      map.addSource('mapillary', {
          'type': 'vector',
          'tiles':[`https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt`]
        });
      let slyr = {
          'id': 'mapillary',
          'type': 'line',
          'source': 'mapillary',
          'source-layer': 'mapillary-sequences',
          'layout': {
          'line-cap': 'round',
          'line-join': 'round'
          },
          'paint': {
          'line-opacity': 0.6,
          'line-color': 'rgb(53, 175, 109)',
          'line-width': 2
          }
          };
        map.addLayer(slyr);
        map.on('mousemove', 'mapillary', addBuildingPopUp);
        // setTimeout(()=>{
        //   console.log("REMOVE BUILDING");
        //   map.off('mousemove','mapillary',addBuildingPopUp);
        // },15000);
        setMap(map);
    });
    
    // clean up on unmount
    return () => map.remove();
  }, []); //...