0

I am trying to create a Leaflet map using this solution. I pasted the code to my javascript file called heatmap.js which is referenced in a <script> tag of my html file called map.html.

The code I pasted into my heatmap.js is as follows.

var map = L.map('myMap').setView([0.3556, 37.5833], 6.5);

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

///////////////////////////////////////////////////////
var geoJsonUrl = "https://raw.githubusercontent.com/sammigachuhi/geojson_files/main/selected_hospitals.json";

L.geoJson.ajax(geoJsonUrl, {
    //

    success: function (geoJSON) {
      // Create a heatmap layer and add the GeoJSON data to it
      var heatmapLayer = L.heatLayer(geoJSON.features.map(function (feature) {
        return [feature.geometry.coordinates[1], feature.geometry.coordinates[0]];
      }))
    }
  }).addTo(map);

heatmapLayer.setOptions({
    // Customize heatmap options here, such as radius, gradient, etc.
    radius: 40,
    blur: 10, 
    gradient: {
            '0': 'Navy', '0.25': 'Navy',
            '0.26': 'Green',
            '0.5': 'Green',
            '0.51': 'Yellow',
            '0.75': 'Yellow',
            '0.76': 'Red',
            '1': 'Red'
            }
});

heatmapLayer.addTo(map); // Add the heatmap layer to the map

The purpose is to create a heatmap and the Leaflet.heat plugin is already included in my html file as <script src="my-directory\Leaflet.heat-gh-pages\dist\leaflet-heat.js"></script>.

Running the Javascript code only generates the json features as marker points, which are actually hospital locations, however, my main interest is generating a heatmap from the json file.

enter image description here

Running the above code generates this error in the console:

enter image description here

I know variables in local scope cannot be available in global scope, but being clever by even inserting the heatmapLayer.setOptions and heatmapLayer.addTo(map) within the L.geoJson.ajax especially after the success key yields no results.

How can I create a heatmap in leafletjs using L.heatLayer and a json file in a server?

  • If you still need a solution: [codepen](https://codepen.io/svystunp/pen/xxyNpZa ). I don't like leaflet Ajax plugin, so solved via xhr request. – Svystun May 30 '23 at 06:00
  • Hello, I managed to sort it out using the js here-- https://www.dropbox.com/s/49ichaa4ozfwry5/heatmap.js?dl=0 which was extracted from someone with a similar problem here -- https://gis.stackexchange.com/questions/337294/heatmap-with-geojson-leaflet-and-leaflet-heat-plugin?utm_source=pocket_reader – Samuel Gachuhi Jun 01 '23 at 08:45

0 Answers0