Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Creating Heatmaps with ECharts and Baidu Maps API

Tech 1

Integrating ECharts with the Baidu Maps API enhances the development of interactive heatmap visualizations for large-screen dashboards.

Simulating GPS Data with Python

Generate random gegoraphic coordinates within a specified radius using Python to simulate GPS data for heatmap testing.

import random
import math
import json

def create_random_points(base_lat, base_lon, radius_km, point_count):
    """
    Produces random latitude and longitude points within a circular area.
    Inputs: base_lat (float), base_lon (float) for center coordinates,
    radius_km (float) for radius in kilometers, point_count (int) for number of points.
    Returns a list of (latitude, longitude) tuples.
    """
    points_list = []
    lat_rad = math.radians(base_lat)
    lon_rad = math.radians(base_lon)
    radius_m = radius_km * 1000  # Convert to meters

    for _ in range(point_count):
        distance = radius_m * math.sqrt(random.random())
        angle = random.uniform(0, 2 * math.pi)
        
        delta_x = distance * math.cos(angle)
        delta_y = distance * math.sin(angle)
        
        # Approximate conversion: 1 degree latitude ≈ 111,111 meters, longitude varies with latitude
        new_lat = base_lat + (delta_y / 111111)
        new_lon = base_lon + (delta_x / (111111 * math.cos(lat_rad)))
        
        points_list.append((new_lat, new_lon))
    
    return points_list

# Configuration for data generation
center_lat = 26.389193
center_lon = 106.642337
radius = 10.0  # 10 kilometers
num_points = 30000

coordinates = create_random_points(center_lat, center_lon, radius, num_points)

# Format data for JSON output
data_output = []
for lat, lon in coordinates:
    point_entry = {
        "elevation": random.uniform(0, 3000),  # Random elevation in meters
        "coord": [lon, lat]  # Longitude first for ECharts compatibility
    }
    data_output.append(point_entry)

# Save to a JSON file
with open('heatmap_data.json', 'w') as file:
    json.dump([data_output], file)

Implementing the Heatmap with ECharts and Baidu Maps

Use HTML and JavaScript to render a heatmap on a Baidu Map using ECharts.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Heatmap Visualization with Baidu Maps</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js"></script>
    <script src="https://api.map.baidu.com/api?v=3.0&ak=YOUR_BAIDU_MAP_API_KEY"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/extension/bmap.min.js"></script>
</head>
<body>
    <div id="mapContainer" style="width: 100%; height: 600px;"></div>
    <script>
        const chartElement = document.getElementById('mapContainer');
        const chartInstance = echarts.init(chartElement);
        
        $.getJSON('heatmap_data.json', function(data) {
            const heatmapPoints = data[0].map(item => item.coord.concat([1]));
            
            const chartOptions = {
                bmap: {
                    center: [106.642337, 26.389193],
                    zoom: 14,
                    roam: true
                },
                visualMap: {
                    show: true,
                    top: 'top',
                    min: 0,
                    max: 5,
                    seriesIndex: 0,
                    calculable: true,
                    inRange: {
                        color: ['blue', 'cyan', 'lime', 'yellow', 'red']
                    }
                },
                series: [{
                    type: 'heatmap',
                    coordinateSystem: 'bmap',
                    data: heatmapPoints,
                    pointSize: 5,
                    blurSize: 6
                }]
            };
            
            chartInstance.setOption(chartOptions);
            const bmap = chartInstance.getModel().getComponent('bmap').getBMap();
            bmap.addControl(new BMap.MapTypeControl());
        });
    </script>
</body>
</html>

To obtain precise latitued and longitude coordinates, utilize the Baidu Maps coordinate picker tool available through their API documentation.

Tags: echarts

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.