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:
- 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).
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.