Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 775
Angel Avatar asked Sep 18 '25 14:09

Angel


1 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

like image 171
kboul Avatar answered Sep 21 '25 04:09

kboul