Example

This map is an example of a heatmap created using JavaScript and the HeatMapAPI. Below the map, you can see the script that generates 50 random points and overlays them on a Google map as a heatmap using an image overlay. You can interact with the map by panning and zooming, which will trigger a real-time rendering of the heatmap. Each heatmap is generated on the fly, meaning you always get a fresh image, allowing for dynamic adjustment of data points for each request. These heatmaps are not static or tiled images, offering flexibility and responsiveness.

JavaScript Code Example

    <script>
    let map;
    let heatmapOverlay;
    let dataPoints; // Variable to store the data points
    let isInitialLoad = true; // Flag to check if it's the first load

    function initMap() {
        const center = { lat: 37.775, lng: -122.434 };

        map = new google.maps.Map(document.getElementById("map"), {
            zoom: 12,
            center: center,
            mapTypeId: "satellite",
        });

        // Generate data points when the page loads
        dataPoints = generateRandomPoints(center, 50, 1);

        // Call the service initially and on every zoom or pan
        google.maps.event.addListener(map, 'idle', () => {
            if (isInitialLoad) {
                isInitialLoad = false; // Set the flag to false after the first load
            } else {
                updateHeatmap();
            }
        });
    }

    function updateHeatmap() {
        const bounds = map.getBounds();
        const ne = bounds.getNorthEast(); // Northeast corner
        const sw = bounds.getSouthWest(); // Southwest corner

        if (!Array.isArray(dataPoints) || dataPoints.length === 0) {
            console.error("Data points are not properly defined or are empty.");
            return;
        }

        // Generate comma-separated data points
        try {
            const dataPointsString = dataPoints.map(point => {
                if (point.Lat == null || point.Lon == null || point.Weight == null) {
                    throw new Error("Data point is missing one of the required properties (Lat, Lon, Weight).");
                }
                return `${point.Lat},${point.Lon},${point.Weight}`;
            }).join(",");

            const heatmapParameters = {
                Width: 400,
                Height: 300,
                Lat1: sw.lat(),
                Lat2: ne.lat(),
                Lon1: sw.lng(),
                Lon2: ne.lng(),
                DistanceMultiple: 20,
                UseAverage: false,
                ColorPalette: '1',
                DataPoints: dataPointsString
            };


            callJsonService(heatmapParameters);
        } catch (error) {
            console.error("Error preparing data points string:", error.message);
        }
    }

    function callJsonService(heatmapParameters) {
        const jsonBody = JSON.stringify(heatmapParameters);

        fetch('https://heatmapapi.com/heatmapapiservices/api/createHeatmap', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Api-Key': 'YOUR_HEATMAP_API_KEY_HERE'
            },
            body: jsonBody
        })
        .then(response => {
            if (!response.ok) {
                console.error("Network response error:", response.status, response.statusText);
                throw new Error(`Network response was not ok. Status: ${response.status} - ${response.statusText}`);
            }
            return response.json().catch(jsonError => {
                console.error("Failed to parse JSON response:", jsonError);
                throw new Error("Failed to parse response body as JSON.");
            });
        })
        .then(data => {
            if (data && data.imageUrl) {
                const fullImageUrl = `https://heatmapapi.com/hm/${data.imageUrl}`;

                const bounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(heatmapParameters.Lat1, heatmapParameters.Lon1),
                    new google.maps.LatLng(heatmapParameters.Lat2, heatmapParameters.Lon2)
                );

                if (heatmapOverlay) {
                    heatmapOverlay.setMap(null);
                }

                heatmapOverlay = new google.maps.GroundOverlay(fullImageUrl, bounds);
                heatmapOverlay.setMap(map);
            } else {
                console.error('Image URL is undefined or empty in response data:', JSON.stringify(data, null, 2));
            }
        })
        .catch(error => {
            console.error('Error updating heatmap:', error.message);
        });
    }

    function generateRandomPoints(center, numPoints, radiusMile) {
        const points = [];
        for (let i = 0; i < numPoints; i++) {
            const lat = center.lat + (Math.random() - 0.5) / 25;
            const lon = center.lng + (Math.random() - 0.5) / 12;
            points.push({ Lat: lat, Lon: lon, Weight: 1 });
        }
        return points;
    }
    </script>
    

HeatMapAPI Documentation

The https://heatmapapi.com/heatmapapiservices/api/createHeatmap endpoint allows you to create heatmap overlays dynamically. Below is an overview of the parameters you can use:

Each request to the API must be accompanied by an API key in the request headers (X-Api-Key). This key is used for authentication and rate limiting. Get a key here.


The API returns a JSON response that contains the filename of the generated PNG heatmap. To correctly use this response, you need to parse the JSON and construct the complete URL to reference the PNG file on your web server. For example:

            {
                "imageUrl": "/heatmaps/heatmap_abc123.png"
            }
        
And can be found at https://heatmapapi.com/hm/[THAT URL].

Heatmap Color Palettes

Below are the four predefined color palettes available for the HeatMapAPI, as well as an option to create a custom color palette. Each predefined palette consists of six distinct colors, ranging from cold (on the table bottom) to hot (top of the table below).

Palette #1 (Default) Palette #2 Palette #3 Palette #4
#ffffff #660000 #ff9900 #174702
#ffff33 #cc0000 #fff600 #389d0c
#f2be21 #ff6600 #66ff00 #5d9245
#fe2a00 #ffff33 #01329e #86a07b
#d50243 #8bfe94 #000033 #9eaa98
#9000ff #6bffcf #000000 #b3b3b3

Custom Color Palette

You can also create a custom color palette by passing a string of six colors in hexadecimal format, separated by commas. These colors will replace the default colors, giving you full control over the visual appearance of the heatmap. For example instead of sending 1,2,3 or 4, you would send the entire custom color set:

        "#123456,#abcdef,#654321,#ffcc00,#00ffcc,#ff00ff"
    

In the above example, the heatmap will use the specified colors, ranging from the coldest to the hottest point on the map.