Delivery Company Example
A comprehensive guide showing how a delivery company implements geofencing, asset tracking, monitoring, and trip management for their fleet operations.
Business Scenarioβ
FastTrack Deliveries operates a fleet of delivery vehicles across a metropolitan area. They need to:
- Track delivery vehicles in real-time
- Monitor entry/exit from delivery zones and warehouses
- Detect speeding violations for safety compliance
- Record complete trip data for billing and analysis
- Alert when vehicles enter restricted areas
- Track idle time to optimize fuel costs
System Architectureβ
Quick Startβ
Get up and running in 5 minutes with this minimal example:
- JavaScript
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.magiclane.net/api/v1';
// 1. Create a delivery zone geofence
await fetch(`${BASE_URL}/add_geofence_area`, {
method: 'POST',
headers: { 'Authorization': API_KEY, 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify({
geofences: [{
p_id: 'warehouse_main',
p_type: 'circle',
p_name: 'Main Warehouse',
p_keywords: ['warehouse'],
p_geojson: {
type: 'Circle',
coordinates: [25.612211, 45.647781],
radius: 200
}
}]
})
});
// 2. Add a delivery vehicle
await fetch(`${BASE_URL}/add_asset`, {
method: 'POST',
headers: { 'Authorization': API_KEY, 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify({
p_id: 'van_001',
p_name: 'Delivery Van 001',
p_properties: { department: 'logistics' },
p_state: 'active',
p_type: 'user',
p_user_id: 1001
})
});
// 3. Setup area monitor for the vehicle asset and the delivery geofence
await fetch(`${BASE_URL}/add_monitor`, {
method: 'POST',
headers: { 'Authorization': API_KEY, 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify({
p_id: 'zone_monitor',
p_type: 'enter_and_exit_area',
p_name: 'Warehouse Monitor',
p_properties_filter_type: 'all_of',
p_properties: { department: 'logistics' },
p_geofence_config: { geofence_keywords: ['warehouse'] }
})
});
// 4. Asset location updates through the SDK
// 5. Poll for events
const pollEvents = async () => {
const response = await fetch(`${BASE_URL}/poll_monitor_events`, {
method: 'GET',
headers: { 'Authorization': API_KEY, 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify({
p_last_poll_timestamp: Math.floor(Date.now() / 1000) - 3600,
p_limit: 100
})
});
const data = await response.json();
console.log('New events:', data.data.monitor_events.length);
return data;
};
await pollEvents();
Step 1: Create Geofencesβ
First, define the geographical boundaries for warehouses, delivery zones, and restricted areas.
- JavaScript
class GeofenceManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.magiclane.net/api/v1';
}
async createDeliveryGeofences() {
const response = await fetch(`${this.baseUrl}/add_geofence_area`, {
method: 'POST',
headers: {
'Authorization': this.apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
geofences: [
// Main Warehouse
{
p_id: 'main_warehouse',
p_type: 'circle',
p_name: 'Main Distribution Center',
p_keywords: ['warehouse', 'distribution', 'headquarters'],
p_properties: {
facility_type: 'warehouse',
capacity: 'high',
operating_hours: '24/7'
},
p_geojson: {
type: 'Circle',
coordinates: [25.612211, 45.647781],
radius: 200
}
},
// Downtown Delivery Zone
{
p_id: 'downtown_zone',
p_type: 'polygon',
p_name: 'Downtown Delivery Zone',
p_keywords: ['delivery', 'downtown', 'high-priority'],
p_properties: {
zone_type: 'delivery',
priority: 'high',
max_vehicle_size: 'medium'
},
p_geojson: {
type: 'Polygon',
coordinates: [[
[25.598, 45.642],
[25.625, 45.642],
[25.625, 45.658],
[25.598, 45.658],
[25.598, 45.642]
]]
}
},
// Suburban Delivery Zone
{
p_id: 'suburban_zone',
p_type: 'polygon',
p_name: 'Suburban Delivery Zone',
p_keywords: ['delivery', 'suburban', 'standard'],
p_properties: {
zone_type: 'delivery',
priority: 'standard',
max_vehicle_size: 'large'
},
p_geojson: {
type: 'Polygon',
coordinates: [[
[25.625, 45.642],
[25.660, 45.642],
[25.660, 45.668],
[25.625, 45.668],
[25.625, 45.642]
]]
}
},
// Customer Parking Zones
{
p_id: 'customer_a_parking',
p_type: 'rectangle',
p_name: 'Customer A - Loading Bay',
p_keywords: ['customer', 'parking', 'loading-bay'],
p_properties: {
customer_id: 'CUST-A-001',
access_type: 'authorized_only'
},
p_geojson: {
type: 'Rectangle',
coordinates: [
[25.610, 45.650], // Southwest corner
[25.612, 45.652] // Northeast corner
]
}
},
// Restricted Area (Airport)
{
p_id: 'airport_restricted',
p_type: 'circle',
p_name: 'Airport Security Zone',
p_keywords: ['restricted', 'airport', 'no-entry'],
p_properties: {
restriction_type: 'no_unauthorized_entry',
security_level: 'high'
},
p_geojson: {
type: 'Circle',
coordinates: [25.580, 45.655],
radius: 500
}
},
// Speed Enforcement Zone
{
p_id: 'school_zone',
p_type: 'polygon',
p_name: 'School Zone - Reduced Speed',
p_keywords: ['school', 'speed-limit', 'safety'],
p_properties: {
zone_type: 'speed_restriction',
max_speed_kmh: 30,
enforcement: 'strict'
},
p_geojson: {
type: 'Polygon',
coordinates: [[
[25.605, 45.648],
[25.608, 45.648],
[25.608, 45.651],
[25.605, 45.651],
[25.605, 45.648]
]]
}
}
]
})
});
const result = await response.json();
console.log('Geofences created:', result.geofence_ids);
return result;
}
}
// Initialize
const geofenceManager = new GeofenceManager('YOUR_API_KEY');
await geofenceManager.createDeliveryGeofences();
Created Geofences:
- β Main Warehouse (circle, 200m radius)
- β Downtown Delivery Zone (polygon)
- β Suburban Delivery Zone (polygon)
- β Customer Loading Bays (rectangles)
- β Airport Restricted Area (circle)
- β School Zone (polygon)
Step 2: Register Fleet Assets & Configure Location Trackingβ
Add delivery vehicles to the system and configure SDK location updates for real-time tracking.
Location updates are sent automatically through the MagicLane SDK when configured in your mobile or other client application. The SDK handles GPS tracking and automatic location uploads based on your configured settings.
2.1 Register Assets via APIβ
- JavaScript
class FleetManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.magiclane.net/api/v1';
}
async registerFleet() {
const vehicles = [
// Downtown delivery vans
{
p_id: 'van_001',
p_name: 'Downtown Van 001',
p_description: 'Electric delivery van for downtown routes',
p_properties: {
department: 'logistics',
vehicle_type: 'van',
zone: 'downtown',
capacity_kg: 800,
license_plate: 'DT-001',
fuel_type: 'electric'
},
p_state: 'active',
p_type: 'user',
p_user_id: 1001
},
{
p_id: 'van_002',
p_name: 'Downtown Van 002',
p_description: 'Hybrid delivery van for downtown routes',
p_properties: {
department: 'logistics',
vehicle_type: 'van',
zone: 'downtown',
capacity_kg: 800,
license_plate: 'DT-002',
fuel_type: 'hybrid'
},
p_state: 'active',
p_type: 'user',
p_user_id: 1002
},
// Suburban delivery trucks
{
p_id: 'truck_001',
p_name: 'Suburban Truck 001',
p_description: 'Large capacity truck for suburban deliveries',
p_properties: {
department: 'logistics',
vehicle_type: 'truck',
zone: 'suburban',
capacity_kg: 2000,
license_plate: 'SB-001',
fuel_type: 'diesel'
},
p_state: 'active',
p_type: 'user',
p_user_id: 2001
},
// Express courier bikes
{
p_id: 'bike_001',
p_name: 'Express Bike 001',
p_description: 'Electric bike for express downtown deliveries',
p_properties: {
department: 'express',
vehicle_type: 'bike',
zone: 'downtown',
capacity_kg: 30,
license_plate: 'EB-001',
fuel_type: 'electric'
},
p_state: 'active',
p_type: 'user',
p_user_id: 3001
}
];
for (const vehicle of vehicles) {
const response = await fetch(`${this.baseUrl}/add_asset`, {
method: 'POST',
headers: {
'Authorization': this.apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(vehicle)
});
const result = await response.json();
console.log(`β Registered: ${vehicle.p_name} (${result.id})`);
}
return vehicles.length;
}
}
// Initialize fleet
const fleetManager = new FleetManager('YOUR_API_KEY');
const count = await fleetManager.registerFleet();
console.log(`\nTotal vehicles registered: ${count}`);
Registered Fleet:
- β 2 Downtown Vans (electric/hybrid) - User IDs: 1001, 1002
- β 1 Suburban Truck (diesel) - User ID: 2001
- β 1 Express Bike (electric) - User ID: 3001
Each driver must have the SDK properly configured on their device with their unique user_id.
Step 3: Configure Monitorsβ
Set up automated monitoring for delivery zones, speeding, and idle detection.
- JavaScript
class MonitoringSystem {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.magiclane.net/api/v1';
}
async setupMonitors() {
const monitors = [
// 1. Delivery Zone Entry/Exit Monitor
{
p_id: 'delivery_zone_monitor',
p_type: 'enter_and_exit_area',
p_name: 'Delivery Zone Activity Monitor',
p_description: 'Track all vehicles entering/exiting delivery zones',
p_keywords: ['delivery', 'zone-tracking', 'operations'],
p_properties_filter_type: 'all_of',
p_properties: {
department: 'logistics'
},
p_geofence_config: {
geofence_keywords: ['delivery'] // Monitors all zones tagged 'delivery'
}
},
// 2. Warehouse Entry Monitor
{
p_id: 'warehouse_monitor',
p_type: 'enter_and_exit_area',
p_name: 'Warehouse Entry/Exit Monitor',
p_description: 'Track vehicle movements at warehouse facilities',
p_keywords: ['warehouse', 'facility', 'security'],
p_properties_filter_type: 'any_of',
p_properties: {
department: 'logistics',
department_alt: 'express'
},
p_geofence_config: {
geofence_keywords: ['warehouse']
}
},
// 3. Speed Compliance Monitor (Vans)
{
p_id: 'van_speed_monitor',
p_type: 'speeding',
p_name: 'Van Speed Compliance Monitor',
p_description: 'Alert when vans exceed 80 km/h (22.2 m/s) for >30 seconds',
p_keywords: ['speeding', 'compliance', 'vans'],
p_properties_filter_type: 'all_of',
p_properties: {
vehicle_type: 'van'
},
p_speeding_config: {
speed_limit: 22.2, // 80 km/h
time_tolerance: 30000 // 30 seconds
}
},
// 4. Speed Compliance Monitor (Trucks)
{
p_id: 'truck_speed_monitor',
p_type: 'speeding',
p_name: 'Truck Speed Compliance Monitor',
p_description: 'Alert when trucks exceed 90 km/h (25 m/s) for >30 seconds',
p_keywords: ['speeding', 'compliance', 'trucks'],
p_properties_filter_type: 'all_of',
p_properties: {
vehicle_type: 'truck'
},
p_speeding_config: {
speed_limit: 25, // 90 km/h
time_tolerance: 30000 // 30 seconds
}
},
// 5. Idle Time Monitor
{
p_id: 'idle_monitor',
p_type: 'idle',
p_name: 'Vehicle Idle Time Monitor',
p_description: 'Detect vehicles idle for >10 minutes',
p_keywords: ['idle', 'efficiency', 'fuel-optimization'],
p_properties_filter_type: 'any_of',
p_properties: {
fuel_type: 'diesel',
fuel_type_alt: 'hybrid'
},
p_idle_config: {
time_tolerance: 600000, // 10 minutes
distance_tolerance: 50 // 50 meters
}
},
// 6. Restricted Area Monitor
{
p_id: 'restricted_area_monitor',
p_type: 'enter_area',
p_name: 'Restricted Area Breach Monitor',
p_description: 'Alert on entry to restricted zones',
p_keywords: ['security', 'restricted', 'breach'],
p_properties_filter_type: 'all_of',
p_properties: {
department: 'logistics'
},
p_geofence_config: {
geofence_keywords: ['restricted', 'no-entry']
}
},
// 7. Customer Parking Monitor
{
p_id: 'customer_parking_monitor',
p_type: 'enter_and_exit_area',
p_name: 'Customer Location Monitor',
p_description: 'Track arrivals and departures at customer locations',
p_keywords: ['customer', 'delivery-confirmation', 'parking'],
p_properties_filter_type: 'any_of',
p_properties: {
department: 'logistics',
department_alt: 'express'
},
p_geofence_config: {
geofence_keywords: ['customer', 'parking']
}
}
];
const results = [];
for (const monitor of monitors) {
const response = await fetch(`${this.baseUrl}/add_monitor`, {
method: 'POST',
headers: {
'Authorization': this.apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(monitor)
});
const result = await response.json();
console.log(`β Monitor created: ${monitor.p_name}`);
results.push(result);
}
return results;
}
}
// Setup monitoring
const monitoringSystem = new MonitoringSystem('YOUR_API_KEY');
await monitoringSystem.setupMonitors();
console.log('\nβ
Monitoring system active');
Active Monitors:
- β Delivery Zone Activity (entry/exit)
- β Warehouse Entry/Exit
- β Speed Compliance (vans: 80 km/h, trucks: 90 km/h)
- β Idle Time Detection (>10 min)
- β Restricted Area Breach
- β Customer Location Tracking
Step 4: Start and Track Tripsβ
Record complete delivery routes with planned stops.
- JavaScript
class TripManager {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.magiclane.net/api/v1';
}
async startDeliveryTrip(vehicleId, route) {
const tripId = `trip_${vehicleId}_${Date.now()}`;
const response = await fetch(`${this.baseUrl}/start_trip`, {
method: 'POST',
headers: {
'Authorization': this.apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
p_trip_id: tripId,
p_asset_id: vehicleId,
p_name: route.name,
p_description: route.description,
p_meta_data: {
shift: route.shift,
route_type: 'delivery',
priority: route.priority,
route_number: route.routeNumber
},
p_attributes: {
driver_name: route.driver,
driver_id: route.driverId,
total_packages: route.packages,
estimated_duration_minutes: route.estimatedDuration,
start_odometer: route.startOdometer
},
p_stops: route.stops.map((stop, index) => ({
name: stop.name,
meta_data: {
sequence: index + 1,
stop_type: stop.type,
customer_id: stop.customerId,
packages: stop.packages,
estimated_time: stop.estimatedTime
},
geofence_id: stop.geofenceId
}))
})
});
const result = await response.json();
console.log(`β Trip started: ${result.trip_id}`);
return result;
}
async updateTripStatus(tripId, assetId, statusUpdate) {
const response = await fetch(`${this.baseUrl}/update_trip`, {
method: 'POST',
headers: {
'Authorization': this.apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
p_trip_id: tripId,
p_asset_id: assetId,
p_meta_data: statusUpdate.metaData,
p_attributes: statusUpdate.attributes
})
});
return response.json();
}
async endTrip(tripId) {
const response = await fetch(`${this.baseUrl}/end_trip_by_id`, {
method: 'GET',
headers: {
'Authorization': this.apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
p_trip_id: tripId
})
});
const result = await response.json();
console.log(`β Trip ended: ${tripId}`);
return result;
}
async getTripSummary(tripId) {
const response = await fetch(`${this.baseUrl}/get_trip_summary`, {
method: 'GET',
headers: {
'Authorization': this.apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
p_trip_id: tripId
})
});
const summary = await response.json();
const trip = summary.data.trip;
return {
trip_id: trip.id,
distance_km: (trip.distance_m / 1000).toFixed(2),
duration_hours: (trip.duration_s / 3600).toFixed(2),
avg_speed_kmh: ((trip.distance_m / trip.duration_s) * 3.6).toFixed(1),
stops_planned: trip.stops.length,
gps_points: trip.location_count
};
}
}
// Example: Downtown delivery route
const tripManager = new TripManager('YOUR_API_KEY');
const downtownRoute = {
name: 'Downtown Morning Route 1',
description: 'High-priority downtown deliveries',
shift: 'morning',
priority: 'high',
routeNumber: 'DT-M-001',
driver: 'Sarah Johnson',
driverId: 'DRV-1001',
packages: 24,
estimatedDuration: 180,
startOdometer: 45280,
stops: [
{
name: 'Main Warehouse - Loading',
type: 'pickup',
geofenceId: 'main_warehouse',
packages: 24,
estimatedTime: '08:00'
},
{
name: 'Customer A - Office Building',
type: 'delivery',
customerId: 'CUST-A-001',
geofenceId: 'customer_a_parking',
packages: 8,
estimatedTime: '08:45'
},
{
name: 'Downtown Zone - Multiple Stops',
type: 'delivery',
customerId: 'VARIOUS',
geofenceId: 'downtown_zone',
packages: 16,
estimatedTime: '10:30'
},
{
name: 'Main Warehouse - Return',
type: 'return',
geofenceId: 'main_warehouse',
packages: 0,
estimatedTime: '11:00'
}
]
};
// Start trip
const trip = await tripManager.startDeliveryTrip('van_001', downtownRoute);
// During trip: Update status
await tripManager.updateTripStatus(trip.trip_id, 'van_001', {
metaData: {
current_stop: 2,
status: 'in_progress'
},
attributes: {
delivered_packages: 8,
current_location: 'Customer A'
}
});
// End trip
await tripManager.endTrip(trip.trip_id);
// Get analytics
const summary = await tripManager.getTripSummary(trip.trip_id);
console.log('\nTrip Summary:', summary);
Trip Created:
- β Route: Downtown Morning Route 1
- β Driver: Sarah Johnson
- β Vehicle: van_001
- β Stops: 4 (pickup β 2 deliveries β return)
- β Packages: 24
Step 5: Monitor Events in Real-Timeβ
Poll for monitoring events and handle alerts.
- JavaScript
class EventMonitor {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.magiclane.net/api/v1';
this.lastPollTimestamp = Math.floor(Date.now() / 1000);
}
async pollEvents() {
const response = await fetch(`${this.baseUrl}/poll_monitor_events`, {
method: 'GET',
headers: {
'Authorization': this.apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
p_last_poll_timestamp: this.lastPollTimestamp,
p_limit: 100,
p_sort_order: 'asc'
})
});
const data = await response.json();
const events = data.data.monitor_events;
if (events.length > 0) {
this.lastPollTimestamp = events[events.length - 1].event_timestamp;
this.processEvents(events);
}
return events;
}
processEvents(events) {
events.forEach(event => {
switch(event.event_type) {
case 'enter':
this.handleZoneEntry(event);
break;
case 'exit':
this.handleZoneExit(event);
break;
case 'speeding':
this.handleSpeedingViolation(event);
break;
case 'idle':
this.handleIdleDetection(event);
break;
}
});
}
handleZoneEntry(event) {
console.log(`
π ZONE ENTRY
Vehicle: ${event.asset_id}
Zone: ${event.geofence_id}
Time: ${new Date(event.event_timestamp * 1000).toLocaleString()}
Location: [${event.event_location.lat}, ${event.event_location.lon}]
`);
// Send notification to dispatch
this.notifyDispatch({
type: 'zone_entry',
vehicle: event.asset_id,
zone: event.geofence_id,
timestamp: event.event_timestamp
});
}
handleZoneExit(event) {
console.log(`
π ZONE EXIT
Vehicle: ${event.asset_id}
Zone: ${event.geofence_id}
Time: ${new Date(event.event_timestamp * 1000).toLocaleString()}
`);
}
handleSpeedingViolation(event) {
const speedKmh = (event.event_metadata.speed_mps * 3.6).toFixed(1);
const limitKmh = (event.event_metadata.speed_threshold_mps * 3.6).toFixed(1);
console.log(`
β οΈ SPEEDING ALERT
Vehicle: ${event.asset_id}
Speed: ${speedKmh} km/h (Limit: ${limitKmh} km/h)
Duration: ${event.event_metadata.time_window_ms / 1000}s
Location: [${event.event_location.lat}, ${event.event_location.lon}]
Time: ${new Date(event.event_timestamp * 1000).toLocaleString()}
`);
// Send alert to safety team
this.notifySafetyTeam({
type: 'speeding_violation',
vehicle: event.asset_id,
speed: speedKmh,
limit: limitKmh,
location: event.event_location
});
}
handleIdleDetection(event) {
const idleMinutes = Math.round(event.event_metadata.time_window_ms / 60000);
console.log(`
βΈοΈ IDLE DETECTED
Vehicle: ${event.asset_id}
Duration: ${idleMinutes} minutes
Location: [${event.event_location.lat}, ${event.event_location.lon}]
Time: ${new Date(event.event_timestamp * 1000).toLocaleString()}
`);
// Notify fleet manager
this.notifyFleetManager({
type: 'excessive_idle',
vehicle: event.asset_id,
duration_minutes: idleMinutes,
location: event.event_location
});
}
notifyDispatch(alert) {
// Integration with dispatch system
console.log(`π’ Dispatch notified:`, alert);
}
notifySafetyTeam(alert) {
// Integration with safety management system
console.log(`π¨ Safety team alerted:`, alert);
}
notifyFleetManager(alert) {
// Integration with fleet management dashboard
console.log(`π Fleet manager notified:`, alert);
}
// Continuous polling
async startMonitoring(intervalSeconds = 10) {
console.log(`π Starting event monitoring (polling every ${intervalSeconds}s)...`);
setInterval(async () => {
try {
await this.pollEvents();
} catch (error) {
console.error('Error polling events:', error);
}
}, intervalSeconds * 1000);
}
}
// Start real-time monitoring
const eventMonitor = new EventMonitor('YOUR_API_KEY');
eventMonitor.startMonitoring(10); // Poll every 10 seconds
Event Types Monitored:
- β Zone Entry/Exit (delivery zones, warehouse, customers)
- β Speeding Violations (>80 km/h for vans, >90 km/h for trucks)
- β Idle Time (>10 minutes)
- β Restricted Area Breach