Establish real-time communication for map tracking data.
// 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. |
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 |
{ "type": "fleet_info", "vehicles": [ { "id": "vehicle_1", "type": "truck", "capacity": "large", "max_speed": 90, "color": "#3498db", "driver": "Driver 1", "plate": "DL-1234", "current_status": "loading", "current_location": { "lat": 40.7128, "lng": -74.0060 }, "battery_level": 85 }, // ... more vehicles ], "timestamp": "2023-07-15T14:30:00.000Z" } |
delivery_assignments |
Initial information about all delivery routes and assignments |
{ "type": "delivery_assignments", "assignments": [ { "vehicle_id": "vehicle_1", "deliveries": [ { "id": "delivery_1_1", "vehicle_id": "vehicle_1", "customer": "Customer 123", "package_id": "PKG-12345", "status": "scheduled", "priority": "high", "route": [ { "name": "Downtown", "lat": 40.7128, "lng": -74.0060, "eta": "2023-07-15T14:30:00.000Z" }, { "type": "waypoint", "name": "Waypoint 1", "lat": 40.7200, "lng": -74.0100, "distance_from_prev": 540.25, "eta": "2023-07-15T14:35:00.000Z" }, // ... more waypoints and destinations ], "current_route_index": 0, "scheduled_start": "2023-07-15T14:30:00.000Z", "estimated_completion": "2023-07-15T15:20:00.000Z", "origin": "Downtown", "destination": "Uptown", "notes": "Fragile" } // ... more deliveries ], "current_delivery_index": 0 } // ... more assignments ], "timestamp": "2023-07-15T14:30:00.000Z" } |
batch_update |
Batch of vehicle updates sent periodically |
{ "type": "batch_update", "updates": [ { "type": "location_update", "vehicle_id": "vehicle_1", "location": { "lat": 40.7135, "lng": -74.0070 }, "status": "en-route", "battery": 84, "timestamp": "2023-07-15T14:31:00.000Z" }, { "type": "traffic_event", "vehicle_id": "vehicle_2", "event": { "type": "congestion", "delay": 5, "message": "Heavy traffic, slowing down" }, "location": { "lat": 40.7580, "lng": -73.9855 }, "timestamp": "2023-07-15T14:31:00.000Z" }, // ... more updates ], "timestamp": "2023-07-15T14:31:00.000Z" } |
location_update |
Vehicle position and status update |
{ "type": "location_update", "vehicle_id": "vehicle_1", "location": { "lat": 40.7135, "lng": -74.0070 }, "status": "en-route", "battery": 84, "timestamp": "2023-07-15T14:31:00.000Z" } |
traffic_event |
Traffic events affecting a vehicle |
{ "type": "traffic_event", "vehicle_id": "vehicle_2", "event": { "type": "congestion", "delay": 5, "message": "Heavy traffic, slowing down" }, "location": { "lat": 40.7580, "lng": -73.9855 }, "timestamp": "2023-07-15T14:31:00.000Z" } |
delivery_completed |
Notification when a delivery is completed |
{ "type": "delivery_completed", "vehicle_id": "vehicle_1", "delivery_id": "delivery_1_1", "next_delivery_id": "delivery_1_2", "timestamp": "2023-07-15T15:20:00.000Z" } |
detailed_update |
Detailed information (only sent with high detail level) |
{ "type": "detailed_update", "vehicle_id": "vehicle_1", "current_delivery": "delivery_1_1", "route_progress": "3/8", "eta": "2023-07-15T15:20:00.000Z", "traffic_event": { "type": "roadwork", "delay": 8, "message": "Roadwork ahead, taking detour" }, "speed_factor": 0.75, "timestamp": "2023-07-15T14:40:00.000Z" } |
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
// 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
};
See the Map Tracking WebSocket API in action with a live interactive demo.
Live Fleet Tracking
Active Vehicles
Event Log
Selected Vehicle
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..."