Is there a way to use leaflet.heat in react?

Viewed 3060

I am trying to use leaflet.heat in reactJS. I have already made leaflet library to work with react hooks but unfortunately I can't use leaflet.heat in react. I import the module like:

import "../libraries/HeatLayer";

And the code for HeatLayer.js is: https://github.com/Leaflet/Leaflet.heat/blob/gh-pages/src/HeatLayer.js

When I run the react app I do not get any errors but the leaflet heatmap is not displayed

NOTE: I don't want to use components such as react-leaflet nor react-leaflet-heatmap.

2 Answers
  • install leaflet.heat via npm : npm i leaflet.heat
  • import the library: import "leaflet.heat";
  • Create a map component and use an effect to load the map and instantiate L.heatLayer

Here is an example from the library's github page written in React without react-leaflet components:

function Map() {
  useEffect(() => {
    var map = L.map("map").setView([-37.87, 175.475], 12);

    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution:
        '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    const points = addressPoints
      ? addressPoints.map((p) => {
          return [p[0], p[1]];
        })
      : [];

    L.heatLayer(points).addTo(map);
  }, []);

  return <div id="map" style={{ height: "100vh" }}></div>;
}

Demo

For React Leaflet V3 useMap hook makes it really easy too:

import { useMap } from 'react-leaflet'
import L from 'leaflet'
import "leaflet.heat"
function heatmapFunction(){
   const map = useMap()
   useEffect(() => {
     const points = addressPoints
     ? addressPoints.map((p) => {
       return [p[0], p[1], p[2]]; // lat lng intensity
       })
     : [];

     L.heatLayer(points).addTo(map);
   }, []);
}

This way you can break the heat map into it's own component etc.

Related