Example
This map is a live example created with JavaScript and the HeatMapAPI. It connects a Google Map to the API in a backend service, as shown in the JSON POST example below. The script 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 triggers a real-time rendering of the heatmap. Each image is generated on the fly, so every request produces a fresh result. This makes it easy to adjust data dynamically while keeping the visualization responsive and flexible, rather than relying on static or tiled images. Unlike the built-in Google Maps heatmap layer, this service is designed to handle very large datasets and render them quickly. You can send a huge number of data points in a single request, and the API produces a heatmap image on the fly. Because the heavy lifting happens in the backend, it avoids the performance issues that come up when trying to push all the rendering into the browser.
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: 600,
Height: 400,
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-591111065781.us-west3.run.app/api/createHeatmap', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: jsonBody
})
.then(response => {
if (!response.ok) throw new Error(`HTTP error ${response.status}`);
return response.blob();
})
.then(blob => {
const url = URL.createObjectURL(blob);
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(url, bounds);
heatmapOverlay.setMap(map);
})
.catch(err => console.error('Error updating heatmap:', err));
}
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-591111065781.us-west3.run.app/api/createHeatmap endpoint allows you to create heatmap overlays dynamically. Below is an overview of the parameters you can use:
- Width: The width of the generated heatmap image in pixels.
- Height: The height of the generated heatmap image in pixels.
- Lat1: The top latitude of the map bounding box.
- Lat2: The bottom latitude of the map bounding box.
- Lon1: The left longitude of the map bounding box.
- Lon2: The right longitude of the map bounding box.
- DistanceMultiple: Controls the spread or influence radius of data points. Depending on the number of points, this value is often around 5 to 30.
- UseAverage: A boolean indicating whether to use average mode for data point calculations.
- ColorPalette: A string representing the color palette to use for the heatmap. Available options include predefined color sets, or you can provide custom colors (see below). You send 1, 2, 3, 4, or a custom string of colors as described below.
- DataPoints: A comma-separated string containing latitude, longitude, and intensity values for each data point. E.g. "37.7749,-122.4194,1,37.7849,-122.4094,2"
If false: The heatmap emphasizes density, treating each point as an individual contributor to the intensity. This mode is ideal for applications like crime mapping, where clusters of incidents create "hotspots" based on proximity and frequency. In this mode, 10 closely grouped points are treated as having the same overall intensity as one point with 10 times the weight (defined by the third parameter in the data points array).
The API returns a PNG (blob) heatmap.
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.