Blog

Improving Field Technician Efficiency: Automating Dispatching with NextBillion.ai’s Geofence API

12 mins Read

July 27, 2023

Geofencing is a location-based technology that defines virtual boundaries around real-world geographical areas. These boundaries, known as geofences, can be customized to specific shapes, such as circles, polygons, or isochrones. The system triggers pre-defined actions or notifications when a person or device enters or exits these defined geofences.

Geofencing technology relies on the Global Positioning System (GPS) or other location-based services to continuously track the real-time location of devices, such as smartphones or GPS-enabled assets. When a device’s location matches the defined geofence parameters, the system detects this containment and initiates the corresponding actions.

Utilizing Geofencing to Automate Dispatching for Field Technicians

Proximity-Based Dispatching: Geofencing allows field service businesses to automate dispatching by assigning tasks to technicians based on their real-time proximity to job sites. When a service request is received, the system automatically identifies the nearest available technician within the geofenced area and dispatches them to the job location.

Efficient Resource Allocation: By utilizing geofencing, dispatchers can optimize resource allocation and ensure the efficient utilization of field technicians. Tasks can be intelligently distributed among technicians based on their locations, minimizing travel time and maximizing productivity.

Real-Time Updates and Notifications: Geofencing enables real-time communication with field technicians. Dispatchers can send updates, instructions, or new assignments directly to technicians’ devices when they enter specific geofenced zones, ensuring they stay informed and responsive.

Benefits of Incorporating Geofencing into the Dispatching Process

  • Enhanced Dispatching Accuracy: Geofencing technology ensures accurate dispatching decisions by considering real-time location data. This precision eliminates the risk of assigning tasks to technicians who are far away from the job site, reducing delays and customer wait times.
  • Improved Response Times: Automated dispatching through geofencing results in quicker response times to service requests. Technicians are dispatched promptly to nearby locations, enabling them to reach customers faster and provide timely assistance.
  • Increased Customer Satisfaction: Businesses can deliver exceptional customer experiences with geofencing-enabled dispatching. Faster response times, reduced wait times, and timely services lead to higher customer satisfaction and loyalty.
  • Optimal Resource Utilization: Geofencing helps optimize resource utilization and reduces operational costs. By minimizing travel distances and time, businesses can lower fuel expenses and increase the number of tasks completed per day.

NextBillion.ai’s Geofence API: Key Features and Capabilities

NextBillion.ai’s Geofence API is a robust and versatile solution that empowers businesses to create, manage, and utilize custom geographical boundaries, known as geofences, on a digital map. This API offers a wide range of features and capabilities that cater to businesses involved in location-based services, fleet management, asset tracking, logistics, and more. Let’s delve into the key features and capabilities of NextBillion.ai’s Geofence API:

  • Geofence Creation and Customization: The Geofence API enables users to easily create, modify, and delete geofences of three types: circle, custom polygon, or isochrone-based geofences. Businesses can define these geofences on a digital map and customize them with unique names, tags, and boundary coordinates. This flexibility allows businesses to create geofences tailored to their specific needs and use cases.
  • Efficient Geofence Management: With the Geofence API, businesses can efficiently manage their geofences by retrieving details of existing geofences using their unique IDs. This facilitates the organization and retrieval of geofence information, making it easier for businesses to track, analyze, and update their geofences as needed.
  • Geofence Containment Check: NextBillion.ai’s Geofence API provides a method to determine if a specific location point falls within one or more geofences. This containment check is essential for location-based services such as delivery tracking, ride-hailing apps, and fleet management, ensuring that users or assets are within designated areas.
  • Automated Dispatching and Task Assignment: The Geofence API’s capabilities allow businesses to automate dispatching and task assignment based on geofence containment. Field technicians or assets located within a specific geofenced area can be assigned tasks automatically, streamlining operations and reducing response times.
  • Tag-Based Filtering and Batch Operations: NextBillion.ai’s Geofence API supports tag-based filtering to retrieve multiple geofences related to specific use cases or tags. This simplifies geofence organization and management, making it easier to handle geofences based on specific attributes or purposes. Additionally, businesses can perform batch operations to delete multiple geofences simultaneously, providing efficiency in geofence management.

Implementation Steps

This section covers the steps involved in integrating Nextbillion.ai’s Geofence API into existing applications using Node.js.

Please note that the following steps cover the steps of creating a basic web application that utilizes the Geofence API to demonstrate automated dispatch for a field technician.

Prerequisites

To include an automatic dispatch functionality for field technicians using Nextbillion.ai’s Geofence API and Node.js, you will need the following prerequisites:

  • Nextbillion.ai Geofence API Key: Obtain an API key from Nextbillion.ai to authenticate your requests to the Geofence API. You can sign up for an account on Nextbillion.ai and generate an API key from the developer dashboard.
  • Node.js Environment: Ensure you have Node.js installed on your system. You can download and install Node.js from the official Node.js website (https://nodejs.org/).
  • Geofence Creation: Before implementing the automatic dispatch functionality, you need to create geofences using Nextbillion.ai’s Geofence API. Geofences are custom geographical boundaries that define specific areas of interest for your field service management.
  • Dispatching System: Have a dispatching system or mechanism in place to handle the automatic dispatching of field technicians. This could be a field service management application, a database, or any other system that manages technician assignments and tasks.
  • Location Data: Ensure that you have access to accurate location data for your field technicians. This could be GPS data from mobile devices, location tracking systems, or any other reliable source.

Initialization

1. Set Up the Project: Create a new directory for your project and initialize a Node.js project by running the following commands in your terminal:


mkdir automated-dispatch-app
cd automated-dispatch-app
npm init -y    

2. Install Dependencies:  Install the required dependencies for the web application, including Express.js for building the server and Axios for making HTTP requests to the Geofence API:


    npm install express axios   

3. Create the Server Create a new file named server.js and set up the basic Express server:


const express = require('express');
const axios = require('axios');
    
const app = express();
const PORT = process.env.PORT || 3000;
    
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
    
// Define routes and API calls here
    
app.listen(PORT, () => {
   console.log(`Server is running on port ${PORT}`);
});

Geofence API Integration

Create a Geofence

To create a geofence in the field service management system using NextBillion.ai’s Geofence API in Node.js, you can use the following code. This code uses Axios library to make HTTP requests to the API:


const axios = require('axios');

// Replace 'YOUR_API_KEY' with your actual NextBillion.ai Geofencing API key
const API_KEY = 'YOUR_API_KEY';

// NextBillion.ai Geofencing API base URL
const API_BASE_URL = 'https://api.nextbillion.io/geofence';

// Function to create a geofence
async function createGeofence() {
  try {
    // Prepare the API endpoint
    const apiEndpoint = `${API_BASE_URL}?key=${API_KEY}`;

    // Replace the example data with your own geofence properties
    const geofenceData = {
      departure_time: 1684987502,
      custom_id: 'GEOFENCE123', // You can set your own unique ID for the geofence
      type: 'circle', // Allowed values: 'circle', 'polygon', 'isochrone'
      name: 'Los Angeles Downtown',
      tags: ['tags_1', 'O69Am2Y4KL8q5Y5JuD-Fy-tdtEpkTRQo_ZYIK7'],
      meta_data: {
        country: 'USA',
        state: 'California',
      },
      circle: {
        center: {
          latitude: 34.0522,
          longitude: -118.2437,
        },
        radius: 500, // Radius in meters, maximum allowed value is 50000 meters
      },
      // Add polygon or isochrone properties if required based on the type
      // polygon: {
      //   geojson: {
      //     type: 'Polygon',
      //     coordinates: [
      //       [
      //         [longitude1, latitude1],
      //         [longitude2, latitude2],
      //         [longitude3, latitude3],
      //         // Add more coordinates for the polygon's boundary
      //       ],
      //     ],
      //   },
      // },
      // isochrone: {
      //   coordinates: '13.25805884,77.91083661', // Starting point coordinates
      //   denoise: 1.0,
      //   mode: 'car',
      //   contours_meter: 100,
      //   contours_minute: 20,
      //   departure_time: 1684987502,
      // },
    };

    // Set the API key as an Authorization header
    const headers = {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    };

    // Make the API call to create the geofence
 const response = await axios.post(apiEndpoint, geofenceData, { headers });

    // Handle the API response
    if (response.data.status === 'Ok') {
      console.log('Geofence created successfully.');
      console.log('Geofence ID:', response.data.data.id);
    } else {
      console.log('Error creating geofence:', response.data.status);
    }
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

// Call the function to create the geofence
createGeofence();


Please note that in the `geofenceData`, you should replace the example data with your own geofence properties based on your requirements. Uncomment the polygon or isochrone properties if you want to create a geofence of type ‘polygon’ or ‘isochrone’, respectively. Make sure you provide the correct coordinates and other required parameters for each geofence type.

Fetch a Geofence

To get a geofence in the field service management system using NextBillion.ai’s Geofence API in Node.js, you can use the following code. This code uses Axios library to make an HTTP GET request to the API:


const axios = require('axios');

// Replace 'YOUR_API_KEY' with your actual NextBillion.ai Geofence API key
const API_KEY = 'YOUR_API_KEY';

// NextBillion.ai Geofence API base URL
const API_BASE_URL = 'https://api.nextbillion.io/geofence';

// Function to get a geofence by ID

async function getGeofenceById(geofenceId) {
  try {
    // Prepare the API endpoint with the geofence ID and API key
    const apiEndpoint = `${API_BASE_URL}/${geofenceId}?key=${API_KEY}`;

    // Set the API key as an Authorization header
    const headers = {
      'Authorization': `Bearer ${API_KEY}`,
    };

    // Make the API call to get the geofence by ID
    const response = await axios.get(apiEndpoint, { headers });

    // Handle the API response

    if (response.data.status === 'Ok') {
      const geofenceData = response.data.data.geofence;
      console.log('Geofence Details:');
      console.log('ID:', geofenceData.id);
      console.log('Name:', geofenceData.name);
      console.log('Type:', geofenceData.type);
      console.log('GeoJSON:', geofenceData.geojson);
      console.log('Tags:', geofenceData.tags);
      console.log('Created At:', new Date(geofenceData.created_at * 1000));
      console.log('Updated At:', new Date(geofenceData.updated_at * 1000));
      console.log('Meta Data:', geofenceData.meta_data);
      // Add more specific details based on the geofence type (circle, polygon, or isochrone)
      if (geofenceData.type === 'circle') {
        console.log('Circle Center:', geofenceData.circle_center);
        console.log('Circle Radius (meters):', geofenceData.circle_radius);
      } else if (geofenceData.type === 'polygon') {
        console.log('Polygon Coordinates:', geofenceData.coordinates);
      } else if (geofenceData.type === 'isochrone') {
        console.log('Isochrone Contours Meter:', geofenceData.ic_contours_meter);
        console.log('Isochrone Contours Minute:', geofenceData.ic_contours_minute);
        console.log('Isochrone Coordinates:', geofenceData.ic_coordinates);
        console.log('Isochrone Departure Time:', new Date(geofenceData.ic_departure_time * 1000));
        console.log('Isochrone Mode:', geofenceData.ic_mode);
        console.log('Isochrone Denoise:', geofenceData.ic_denoise);
      }
    } else {
      console.log('Error getting geofence:', response.data.status);
    }
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

// Call the function to get the geofence by ID
// Replace 'GEOFENCE_ID' with the actual ID of the geofence you want to fetch
getGeofenceById('GEOFENCE_ID');


Ensure you replace ‘YOUR_API_KEY’ with your actual NextBillion.ai Geofencing API key, and ‘GEOFENCE_ID’ with the ID of the geofence you want to fetch.

Update a Geofence

To update a geofence in the field service management system, you can use the following code. This code uses Axios library to make an HTTP PUT request to the API:


const axios = require('axios');

// Replace 'YOUR_API_KEY' with your actual NextBillion.ai Geofencing API key
const API_KEY = 'YOUR_API_KEY';

// NextBillion.ai Geofencing API base URL
const API_BASE_URL = 'https://api.nextbillion.io/geofence';

// Function to update a geofence by ID
async function updateGeofenceById(geofenceId, updateData) {
  try {
    // Prepare the API endpoint with the geofence ID and API key
    const apiEndpoint = `${API_BASE_URL}/${geofenceId}?key=${API_KEY}`;

    // Set the API key as an Authorization header
    const headers = {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    };

    // Make the API call to update the geofence by ID
    const response = await axios.put(apiEndpoint, updateData, { headers });

    // Handle the API response
    if (response.data.status === 'Ok') {
      console.log('Geofence updated successfully.');
      console.log('Updated Geofence Details:', response.data.data.geofence);
    } else {
      console.log('Error updating geofence:', response.data.status);
    }
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

// Call the function to update the geofence by ID
// Replace 'GEOFENCE_ID' with the actual ID of the geofence you want to update
const updateData = {
  type: 'circle', // Update the type to 'circle', 'polygon', or 'isochrone'
  name: 'Updated Geofence Name', // Update the name of the geofence
  tags: ['updated_tag1', 'updated_tag2'], // Update the tags associated with the geofence
  meta_data: {
    updated_key: 'updated_value', // Update any metadata associated with the geofence
  },
  // Provide the updated properties based on the geofence type (circle, polygon, or isochrone)
  // circle: {
  //   center: {
  //     lat: 34.0522, // Update the latitude of the circle center
  //     lon: -118.2437, // Update the longitude of the circle center
  //   },
  //   radius: 1000, // Update the radius of the circle in meters
  // },
  // polygon: {
  //   geojson: {
  //     type: 'Polygon',
  //     coordinates: [
  //       [
  //         [longitude1, latitude1],
  //         [longitude2, latitude2],
  //         [longitude3, latitude3],
  //         // Add more coordinates for the updated polygon's boundary
  //       ],
  //     ],
  //   },
  // },
  // isochrone: {
  //   coordinates: '13.25805884388484,77.91083661048299', // Update the isochrone starting point coordinates
  //   denoise: 0.8, // Update the denoise value
  //   mode: 'car', // Update the driving mode
  //   contours_meter: 200, // Update the distance in meters for isochrone contour
  //   contours_minute: 30, // Update the duration in minutes for isochrone contour
  //   departure_time: 1684987502, // Update the departure time
  // },
};

updateGeofenceById('GEOFENCE_ID', updateData);

Ensure you replace ‘YOUR_API_KEY’ with your actual NextBillion.ai Geofencing API key and ‘GEOFENCE_ID’ with the ID of the geofence you want to update.

In the `updateData` object, provide the properties that you want to update based on the geofence type (circle, polygon, or isochrone). Uncomment the respective section for the geofence type you want to update and provide the updated values accordingly.

Delete a geofence

To delete a single geofence or a batch of geofences from a field service management application using NextBillion.ai’s Geofence API in Node.js, you can use the following code. This code uses Axios library to make HTTP DELETE requests to the API:


const axios = require('axios');

// Replace 'YOUR_API_KEY' with your actual NextBillion.ai Geofencing API key
const API_KEY = 'YOUR_API_KEY';

// NextBillion.ai Geofencing API base URL
const API_BASE_URL = 'https://api.nextbillion.io/geofence';

// Function to delete a single geofence by ID
async function deleteGeofenceById(geofenceId) {
  try {
    // Prepare the API endpoint with the geofence ID and API key
    const apiEndpoint = `${API_BASE_URL}/${geofenceId}?key=${API_KEY}`;

    // Set the API key as an Authorization header
    const headers = {
      'Authorization': `Bearer ${API_KEY}`,
    };

    // Make the API call to delete the geofence by ID
    const response = await axios.delete(apiEndpoint, { headers });

    // Handle the API response
    if (response.data.status === 'Ok') {
      console.log('Geofence deleted successfully.');
    } else {
      console.log('Error deleting geofence:', response.data.status);
    }
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

// Function to delete a batch of geofences by IDs
async function deleteBatchGeofencesByIds(geofenceIds) {
  try {
    // Prepare the API endpoint with the API key
    const apiEndpoint = `${API_BASE_URL}/batch?key=${API_KEY}`;

    // Set the API key as an Authorization header
    const headers = {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    };
    // Make the API call to delete the batch of geofences
    const response = await axios.delete(apiEndpoint, { headers, data: { ids: geofenceIds } });

    // Handle the API response
    if (response.data.status === 'Ok') {
      console.log('Batch of geofences deleted successfully.');
    } else {
      console.log('Error deleting batch of geofences:', response.data.status);
    }
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

// Call the function to delete a single geofence by ID
// Replace 'GEOFENCE_ID' with the actual ID of the geofence you want to delete
deleteGeofenceById('GEOFENCE_ID');

// Call the function to delete a batch of geofences by IDs
// Replace the array elements with the actual IDs of the geofences you want to delete
deleteBatchGeofencesByIds(['GEOFENCE_ID_1', 'GEOFENCE_ID_2']);

Ensure that you replace `’YOUR_API_KEY’` with your actual NextBillion.ai Geofencing API key, `’GEOFENCE_ID’` with the actual ID of the single geofence you want to delete, and `’GEOFENCE_ID_1’`, `’GEOFENCE_ID_2’`, etc., with the actual IDs of the geofences you want to delete in the batch request.

The functions `deleteGeofenceById` and `deleteBatchGeofencesByIds` send DELETE requests to the API to delete a single geofence and a batch of geofences, respectively.

Get a List of Geofences

To get the list of geofences in a field service management application using NextBillion.ai’s Geofence API in Node.js, you can use the following code. This code uses Axios library to make an HTTP GET request to the API:


    const axios = require('axios');

    // Replace 'YOUR_API_KEY' with your actual NextBillion.ai Geofencing API key
    const API_KEY = 'YOUR_API_KEY';
    
    // NextBillion.ai Geofencing API base URL
    const API_BASE_URL = 'https://api.nextbillion.io/geofence/list';
    
    // Function to get the list of geofences with pagination and tag filtering
    async function getGeofenceList(tags = '', pageNumber = 1, pageSize = 1) {
      try {
        // Prepare the API endpoint with the API key and optional parameters
        const apiEndpoint = `${API_BASE_URL}?key=${API_KEY}&tags=${tags}&pn=${pageNumber}&ps=${pageSize}`;
    
        // Make the API call to get the list of geofences
        const response = await axios.get(apiEndpoint);
    
        // Handle the API response
        if (response.data.status === 'Ok') {
          const geofences = response.data.data.list;
          const pagination = response.data.data.page;
    
          console.log('Total number of geofences:', pagination.total);
          console.log('Current page number:', pagination.page);
          console.log('Maximum items per page:', pagination.size);
          console.log('Has more pages:', pagination.hasmore);
    
          if (geofences.length === 0) {
            console.log('No geofences found.');
          } else {
            console.log('List of geofences:');
            geofences.forEach((geofence) => {
              console.log('Geofence ID:', geofence.id);
              console.log('Geofence Name:', geofence.name);
              // Add more information you want to display for each geofence
              console.log('--------------------------------');
            });
          }
        } else {
          console.log('Error getting geofence list:', response.data.status);
        }
      } catch (error) {
        console.error('An error occurred:', error.message);
      }
    }
    
    // Call the function to get the list of geofences
    // Replace 'TAGS' with the comma-separated list of tags to filter geofences by tags
    // Replace 'PAGE_NUMBER' and 'PAGE_SIZE' with the desired pagination parameters
    getGeofenceList('TAGS', PAGE_NUMBER, PAGE_SIZE);
    

Ensure you replace ‘YOUR_API_KEY’ with your actual NextBillion.ai Geofencing API key, ‘TAGS’ with the comma-separated list of tags you want to use for filtering geofences (or leave it empty for no filtering), and ‘PAGE_NUMBER’ and ‘PAGE_SIZE’ with the desired pagination parameters.

The function `getGeofenceList` sends a GET request to the API to retrieve the list of geofences with optional tag filtering and pagination. The response will contain information about the geofences that match the provided tags and pagination settings.

Automating Dispatch

To automate dispatch using NextBillion.ai’s Geofence API in Node.js, you can create a script that fetches the list of geofences and then checks if a specific location falls within any of the geofences. ​​Let’s assume that when a point is found within a geofence, we want to automatically dispatch a field technician to that location.

Below is an example code to achieve this:


    const axios = require('axios');

    // Replace 'YOUR_API_KEY' with your actual NextBillion.ai Geofence API key
    const API_KEY = 'YOUR_API_KEY';
    
    // NextBillion.ai Geofencing API base URL
    const API_BASE_URL = 'https://api.nextbillion.io/geofence/contain';
    
    // Function to check if a specific point is contained in one or more geofences
    async function checkPointInGeofences(locations) {
      try {
       
     // Prepare the API endpoint with the API key and locations parameter
        const apiEndpoint = `${API_BASE_URL}?key=${API_KEY}&locations=${locations}`;
    
        // Make the API call to check if the locations are contained in the geofences
        const response = await axios.get(apiEndpoint);
    
        // Handle the API response
        if (response.data.status === 'Ok') {
          const result = response.data.data.result_list;
    
          if (result.length === 0) {
            console.log('No geofences contain the given locations.');
          } else {
            console.log('Geofences containing the locations:');
            result.forEach((geofence) => {
              console.log('Geofence ID:', geofence.id);
              console.log('Geofence Name:', geofence.name);
              // Add more information you want to display for each geofence
    
              // Perform automatic dispatching action here
              dispatchFieldTechnician(geofence);
            });
          }
        } else {
          console.log('Error checking geofence containment:', response.data.status);
        }
      } catch (error) {
        console.error('An error occurred:', error.message);
      }
    }
    
    // Function to dispatch a field technician to a geofence location
    
    function dispatchFieldTechnician(geofence) {
     
     // Replace this with your actual implementation of automatic dispatching
      // For this example, we will simply log a message indicating the dispatching action.
      console.log(`Dispatching field technician to Geofence ID: ${geofence.id}`);
      console.log(`Field Technician dispatched to: ${geofence.name}`);
      // You can add more actions here, such as sending notifications, updating the database, etc.
    }
    
    // Call the function to check if the locations are contained in the geofences
    // Replace 'LOCATION_COORDINATES' with the actual pipe-separated coordinates in [latitude,longitude] format
    // Example: '13.25805884388484,77.91083661048299|13.25805884388484,77.91083661048299'
    checkPointInGeofences('LOCATION_COORDINATES');
    

Ensure that you replace ‘YOUR_API_KEY’ with your actual NextBillion.ai API key, and ‘LOCATION_COORDINATES’ with the actual pipe-separated coordinates in [latitude,longitude] format of the location you want to check against the geofences.

The `checkPointInGeofences` function sends a GET request to the API to check if the specified locations are contained in the provided geofences. The response will contain information about the geofences that contain the given locations.

The `dispatchFieldTechnician(geofence)` function performs an automatic dispatch function for field technicians if a location coordinate is found within a geofence.

Please note that this is a basic example, and you can integrate this logic into your existing dispatch system or build a more comprehensive automation process as per your specific use case and requirements. Additionally, consider implementing proper error handling and logging to handle different scenarios effectively.

NextBillion.ai’s Geofence API offers a comprehensive set of features and capabilities that cater to businesses seeking to enhance their location-based services, fleet management, and dispatching operations. From creating, modifying, and deleting geofences to real-time location tracking and automated dispatching, this API empowers businesses to optimize their field service management processes, improve customer experiences, and increase operational efficiency. With NextBillion.ai’s Geofence API, businesses can leverage geofencing technology to its full potential and stay ahead in today’s dynamic and competitive landscape.

Click here to learn more about Geofence API documentation.

Ready to get started?

Talk to Sales

Lower fuel costs
by up to 20%

Blog Img

Ready to up your game in scheduling, dispatch, and routing?

Request a Demo