Real-time Map Tracking WebSocket API

Stream live vehicle locations, delivery updates, and route information for building real-time delivery and fleet tracking applications.

WebSocket Connection

Establish real-time communication for map tracking data.

wss://mockly.me/ws/map/{client_id}
WebSocket
JavaScript
Python
// Connect to Map Tracking WebSocket
const clientId = 'client-' + Math.floor(Math.random() * 10000);
const mapSocket = new WebSocket(`wss://mockly.me/ws/map/${clientId}`);

// Custom configuration (optional)
const config = {
  update_frequency: 1.5,      // Updates per second
  show_traffic_events: true,  // Enable traffic events
  detail_level: "medium"      // Detail level: "low", "medium", "high" 
};

// Handle connection open
mapSocket.onopen = function() {
  console.log('Map tracking connection established');
  
  // Send configuration (optional)
  mapSocket.send(JSON.stringify(config));
  
  // Setup UI to show connection status
  document.getElementById('connection-status').textContent = 'Connected';
  document.getElementById('connection-status').className = 'text-green-600';
};

// Handle received messages
mapSocket.onmessage = function(event) {
  const data = JSON.parse(event.data);
  
  // Handle different message types
  switch(data.type) {
    case 'fleet_info':
      // Initial information about all vehicles
      console.log('Received fleet info:', data.vehicles);
      initializeMap(data.vehicles);
      break;
      
    case 'delivery_assignments':
      // Information about delivery routes
      console.log('Received delivery assignments:', data.assignments);
      displayDeliveryRoutes(data.assignments);
      break;
      
    case 'batch_update':
      // Process batch of updates
      data.updates.forEach(update => processUpdate(update));
      break;
      
    default:
      console.log('Received message:', data);
  }
};

// Handle connection close
mapSocket.onclose = function() {
  console.log('Map tracking connection closed');
  document.getElementById('connection-status').textContent = 'Disconnected';
  document.getElementById('connection-status').className = 'text-red-600';
};

// Handle errors
mapSocket.onerror = function(error) {
  console.error('WebSocket error:', error);
  document.getElementById('connection-status').textContent = 'Error';
  document.getElementById('connection-status').className = 'text-red-600';
};

// Process individual updates
function processUpdate(update) {
  switch(update.type) {
    case 'location_update':
      updateVehiclePosition(
        update.vehicle_id, 
        update.location, 
        update.status
      );
      break;
      
    case 'traffic_event':
      displayTrafficEvent(
        update.vehicle_id, 
        update.event, 
        update.location
      );
      break;
      
    case 'delivery_completed':
      handleDeliveryCompletion(
        update.vehicle_id,
        update.delivery_id,
        update.next_delivery_id
      );
      break;
      
    case 'detailed_update':
      updateDetailedInfo(update);
      break;
  }
}
import asyncio
import websockets
import json
import random

async def connect_to_map_tracking():
    # Generate a random client ID
    client_id = f"client-{random.randint(1000, 9999)}"
    uri = f"wss://mockly.me/ws/map/{client_id}"
    
    # Configuration options (optional)
    config = {
        "update_frequency": 2.0,       # Updates per second
        "show_traffic_events": True,    # Enable traffic events
        "detail_level": "high"         # Detail level: "low", "medium", "high"
    }
    
    try:
        async with websockets.connect(uri) as websocket:
            print(f"Connected to map tracking WebSocket with client ID: {client_id}")
            
            # Send configuration
            await websocket.send(json.dumps(config))
            print(f"Sent configuration: {config}")
            
            # Process incoming messages
            while True:
                message = await websocket.recv()
                data = json.loads(message)
                
                # Handle different message types
                if data.get("type") == "fleet_info":
                    print(f"Received info for {len(data['vehicles'])} vehicles")
                    for vehicle in data["vehicles"]:
                        print(f"Vehicle {vehicle['id']}: {vehicle['type']} at position "
                              f"({vehicle['current_location']['lat']}, {vehicle['current_location']['lng']})")
                
                elif data.get("type") == "delivery_assignments":
                    print(f"Received {len(data['assignments'])} delivery assignments")
                    
                elif data.get("type") == "batch_update":
                    # Process batch of updates
                    update_count = len(data["updates"])
                    location_updates = sum(1 for u in data["updates"] if u.get("type") == "location_update")
                    traffic_events = sum(1 for u in data["updates"] if u.get("type") == "traffic_event")
                    
                    print(f"Batch update: {update_count} total updates "
                          f"({location_updates} location updates, {traffic_events} traffic events)")
                    
                    # Process individual updates if needed
                    for update in data["updates"]:
                        if update.get("type") == "traffic_event":
                            event = update.get("event", {})
                            print(f"Traffic event: {event.get('type')} - {event.get('message')}")
                
    except websockets.exceptions.ConnectionClosed:
        print("Connection closed")
    except Exception as e:
        print(f"Error: {e}")

# Run the async function
if __name__ == "__main__":
    asyncio.run(connect_to_map_tracking())

Connection Parameters

Parameter Description
client_id A unique identifier for your client connection. Can be any string value.
Event Types

Different types of map tracking events that your client can receive.

The Map Tracking WebSocket provides different event types to power your real-time tracking UI. Below are the event types you will receive:

Event Type Description Example Payload
fleet_info Initial information about all vehicles in the fleet
delivery_assignments Initial information about all delivery routes and assignments
batch_update Batch of vehicle updates sent periodically
location_update Vehicle position and status update
traffic_event Traffic events affecting a vehicle
delivery_completed Notification when a delivery is completed
detailed_update Detailed information (only sent with high detail level)
Configuration Options

Customize the behavior of your map tracking connection.

After establishing a WebSocket connection, you can optionally send a JSON configuration object to customize the behavior:

// Example configuration object
const config = {
  "update_frequency": 2.0,       // Updates per second (0.5 to 10.0)
  "show_traffic_events": true,    // Enable traffic events (true/false)
  "detail_level": "high"         // Detail level: "low", "medium", "high"
};

// Send to WebSocket after connection opens
mapSocket.onopen = function() {
  mapSocket.send(JSON.stringify(config));
};

Configuration Parameters

Parameter Description Default Valid Values
update_frequency How frequently location updates are sent (in seconds) 2.0 0.5 to 10.0
show_traffic_events Whether to simulate random traffic events true true, false
detail_level The level of detail in updates "medium" "low", "medium", "high"

Detail Level Differences

  • Low: Only provides basic location updates and traffic events.
  • Medium: Adds delivery assignments and completion notifications.
  • High: Adds detailed vehicle status, ETA, and route progress information.

Configuration Timing

Send the configuration object immediately after the WebSocket connection is established. The server will wait up to 2 seconds for configuration before proceeding with default values. If no configuration is sent, the default settings will be used.

Examples

Fast Updates
High Detail
Simple Tracking
// Configuration for fast updates (good for real-time tracking)
const config = {
  "update_frequency": 0.5,    // Fast updates (every 0.5 seconds)
  "show_traffic_events": true,
  "detail_level": "low"       // Low detail for better performance
};
// Configuration for detailed tracking dashboard
const config = {
  "update_frequency": 2.0,     // Standard update rate
  "show_traffic_events": true,
  "detail_level": "high"       // Maximum information
};
// Configuration for simple tracking without distractions
const config = {
  "update_frequency": 5.0,      // Slower updates to reduce network usage
  "show_traffic_events": false, // No traffic events
  "detail_level": "medium"      // Standard detail level
};
Live Demo

See the Map Tracking WebSocket API in action with a live interactive demo.

Live Fleet Tracking

Connection: Disconnected

Active Vehicles

Connect to see vehicles

Event Log

Connect to see events

Selected Vehicle

Click a vehicle on the map
AI-Powered

Meet Mockly Assistant

Your AI assistant for API testing, debugging and code generation. Access the power of mockly.me directly in ChatGPT.

  • Generate code examples in your preferred language
  • Get guidance for request/response handling and formatting
  • Supercharged by ChatGPT Plus from OpenAI

"How do I send data to a POST endpoint"

"I can show you how to structure your request with headers and JSON — here's a code example..."

Powered by AI