Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Real-Time Vehicle Tracking with Offline Mapbox, MQTT, and Vue

Tech 1

Offline Mapbox addresses scenarios where backend systems or dashboards operate within intranet environments, such as on-premises deployments or client internal networks. In these cases, online mapping services like Gaode or Baidu Maps are unavailable, making offline solutions necessary. Mapbox stands out as a viable option for offline implementation due to its flexibility and local deployement capabilities.

A key challenge with offline Mapbox is the absence of map styles, which are typically fetched on line. Unlike services that embed styles directly, Mapbox relies on npm packages and requires a style definition for rendering features like roads and buildings. The default style can be omitted, resulting in a blank canvas that still supports core functionalities such as adding layers, markers, and zoom controls.

const mapInstance = new mapboxgl.Map({
    container: 'mapContainer',
    style: {
        version: 8,
        sources: {},
        layers: [
            {
                id: 'baseLayer',
                type: 'background',
                paint: {
                    'background-color': '#000000'
                }
            }
        ]
    },
    center: [116.490282, 39.729515],
    zoom: 20
});

To populate the map with data, two approaches are common. First, using GeoServer to publish high-precision WMS layers from shapefiles or TIFF formats provides detailed road networks but demands server resources and higher customization effort. Alternatively, converting TIFF files to PNG images with corner coordinates via ArcMap allows direct overlay as image layers in Mapbox. This method offers flexibility without service deployment, though with less refined styling.

Integrating real-time data via MQTT or WebSocket enables dynamic vehicle tracking. The process involves generating markers for vehicles, updating their positions, and managing stale data. A marker creation function defines visual elements based on vehicle type and unique identifiers.

function generateMarker(position, category, identifier) {
    const element = document.createElement('div');
    element.textContent = identifier;
    element.className = determineCategoryClass(category);
    return new mapboxgl.Marker(element).setLngLat(position);
}

Position updates are handled by maintaining a collection of markers, updating existing ones or creating new entries as needed.

const markerCollection = new Map();
function updatePosition(identifier, newPosition, orientation = 0) {
    if (markerCollection.has(identifier)) {
        markerCollection.get(identifier).marker
            .setLngLat(newPosition)
            .setRotation(orientation);
        markerCollection.get(identifier).timestamp = Date.now();
    } else {
        markerCollection.set(identifier, {
            marker: generateMarker(newPosition, category, identifier).addTo(mapInstance),
            timestamp: Date.now()
        });
    }
}

To remove inactive vehicles, a cleanup function deletes markers that haven't received updates within a specified interval, such as one second.

function removeInactiveMarkers() {
    const currentTime = Date.now();
    markerCollection.forEach((entry, key) => {
        if (currentTime - entry.timestamp > 1000) {
            entry.marker.remove();
            markerCollection.delete(key);
        }
    });
}

let intervalId = null;
function startCleanupInterval() {
    intervalId = setInterval(removeInactiveMarkers, 1000);
}

This approach combines offline mapping with real-time data streaming to visualize moving vehicles, suitable for environments without internet connectivity.

Tags: MapboxMQTT

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.