NAV Navbar
cURL (cmd) cURL (bash) C# Java Python VB.NET PHP Perl Go VBScript Delphi C++ Node C

Introduction

Welcome to the Route4Me API Reference! You can use our API to access and use Route4Me’s services for creating optimal and sequenced driving and maintenance routes. You can also use it to manage the various resources and features in your Route4Me account, such as address books, members, drivers, vehicles, tracking, avoidance zones, notes, etc.

Our unique routing engine is 100% RESTful and has portable algorithm backends that solve a variety of complex problems in a single HTTP request.

We have language bindings in C#, VB.NET, Python, Java, Node, C++, Ruby, PHP, Go, Erlang, Perl, cURL (using cmd and Bash), and VBScript. View the code examples of the respective languages at the right, and click the tabs to switch from one language to another.

Our API documentation is regularly updated. Kindly check back here often to see the revised and updated content. If you have any questions regarding this documentation, or any feedback or suggestion to improve it, please feel free to reach us at support@route4me.com.

Helper Libraries

Here are the helper libraries officially maintained and provided by Route4Me. Download the library for your preferred language and use it to follow the code examples provided in this documentation.

C# C++
Erlang Go
Java Node
Perl PHP
Python Ruby
VB.NET VBScript (WSH)
Delphi

HTTP Verbs

Our API uses the appropriate HTTP verb for these actions:

Verb Description
GET Used for retrieving resources
PUT Used for updating resources
POST Used for creating resources
DELETE Used for deleting resources

Making Requests

When making requests to our API, here are a few things to keep in mind:

Responses

Almost all of our API responses are JSON-encoded, and only a few are XML-encoded.

As a rule, a response contains:


Authentication

Every Route4Me SDK instance needs a unique API key. Your API key can be found inside your Route4Me.com account, by going to menu My Account > API.

In the code examples, make sure to replace the 11111111111111111111111111111111 (32 characters) demo API key with your API key.

Demo API Key Restrictions

The default demo API key 11111111111111111111111111111111 only permits you to test and optimize routes using a predefined list of latitude and longitude coordinates.

Also, Route4Me expects that the demo API key be included in all API requests to the server as part of the query string that looks like the following:


or

Platform API’s

Optimizations

An Optimization Problem refers to a collection of addresses that need to be visited.

The optimization problem takes into consideration all of the addresses that need to be visited and all the constraints associated with each address and depot.

It is preferable to create an optimization problem with as many orders in it as possible so that the optimization engine can consider the entire problem set.

This is different from a Route, which is a sequence of addresses that need to be visited by a single vehicle and driver in a fixed period. Solving an Optimization Problem results in many routes (possibly recurring in the future).

See the Optimization Response JSON Schema in our GitHub repository.

Optimization Properties

Attribute Type Description
optimization_problem_id string A unique ID
state integer state of optimization [1 - 6]
user_errors array User errors
sent_to_background boolean backgound computing
parameters array Route Parameters. See the Route Parameters JSON schema as a guide.
addresses array Route Addresses. See the Address JSON Schema as a guide.
routes array Routes. See the Route JSON Schema as a guide.
links array Links. See the Links JSON Schema as a guide.
tracking_history array Device tracking data. See the Tracking History JSON Schema as a guide.
directions array Directions. See the Direction JSON Schema as a guide.

Create an Optimization

a) Create a new optimization

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data POST data A valid JSON object string. See the Optimization Create JSON Schema as a guide.
<job id="Create New Optimization">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example demonstrates the process of creating a new optimization.

      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/optimization_problem.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="create_new_optimization_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest2 url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/optimization_problem.php
SET apikey=11111111111111111111111111111111

:: The example demonstrates the process of creating a new optimization.

ECHO ON

curl -o file1.txt -g -k -X POST -d "@create_new_optimization_data.json"  "%url%?api_key=%apikey%" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/optimization_problem.php
apikey=11111111111111111111111111111111

curl -o file1.txt -g -k -X POST -d "@create_new_optimization_data.json"  "$url?api_key=$apikey"

# The example demonstrates the process of creating a new optimization.

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public DataObject SingleDriverRoute10Stops()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Prepare the addresses
      Address[] addresses = new Address[]
      {
        #region Addresses

        new Address() { AddressString = "151 Arbor Way Milledgeville GA 31061",
                        // Indicate that this is a departure stop.
                        // Single depot routes can only have one departure depot.
                        IsDepot = true, 
                        
                        // Required coordinates for every departure and stop on the route.
                        Latitude = 33.132675170898,
                        Longitude = -83.244743347168,
                        
                        // The expected time on site, in seconds. This value is incorporated into the optimization engine.
                        // It also adjusts the estimated and dynamic ETA for a route.
                        Time = 0, 
                        
                        
                        // Input as many custom fields as needed. Custom data is passed through to mobile devices and to the manifest.
                        CustomFields = new Dictionary<string, string>() {{"color", "red"}, {"size", "huge"}}
        },

        new Address() { AddressString = "230 Arbor Way Milledgeville GA 31061",
                        Latitude = 33.129695892334,
                        Longitude = -83.24577331543,
                        Time = 0 },

        new Address() { AddressString = "148 Bass Rd NE Milledgeville GA 31061",
                        Latitude = 33.143497,
                        Longitude = -83.224487,
                        Time = 0 },

        new Address() { AddressString = "117 Bill Johnson Rd NE Milledgeville GA 31061",
                        Latitude = 33.141784667969,
                        Longitude = -83.237518310547,
                        Time = 0 },

        new Address() { AddressString = "119 Bill Johnson Rd NE Milledgeville GA 31061",
                        Latitude = 33.141086578369,
                        Longitude = -83.238258361816,
                        Time = 0 },

        new Address() { AddressString =  "131 Bill Johnson Rd NE Milledgeville GA 31061",
                        Latitude = 33.142036437988,
                        Longitude = -83.238845825195,
                        Time = 0 },

        new Address() { AddressString =  "138 Bill Johnson Rd NE Milledgeville GA 31061",
                        Latitude = 33.14307,
                        Longitude = -83.239334,
                        Time = 0 },

        new Address() { AddressString =  "139 Bill Johnson Rd NE Milledgeville GA 31061",
                        Latitude = 33.142734527588,
                        Longitude = -83.237442016602,
                        Time = 0 },

        new Address() { AddressString =  "145 Bill Johnson Rd NE Milledgeville GA 31061",
                        Latitude = 33.143871307373,
                        Longitude = -83.237342834473,
                        Time = 0 },

        new Address() { AddressString =  "221 Blake Cir Milledgeville GA 31061",
                        Latitude = 33.081462860107,
                        Longitude = -83.208511352539,
                        Time = 0 }

        #endregion
      };

      // Set parameters
      RouteParameters parameters = new RouteParameters()
      {
        AlgorithmType = AlgorithmType.TSP,
        StoreRoute = false,
        RouteName = "Single Driver Route 10 Stops",

        RouteDate    = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.Date.AddDays(1)),
        RouteTime    = 60 * 60 * 7,
        Optimize     = Optimize.Distance.Description(),
        DistanceUnit = DistanceUnit.MI.Description(),
        DeviceType   = DeviceType.Web.Description()
      };

      OptimizationParameters optimizationParameters = new OptimizationParameters()
      {
        Addresses = addresses,
        Parameters = parameters
      };

      // Run the query
      string errorString;
      DataObject dataObject = route4Me.RunOptimization(optimizationParameters, out errorString);

      // Output the result
      PrintExampleOptimizationResult("SingleDriverRoute10Stops", dataObject, errorString);

      return dataObject;
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Function SingleDriverRoute10Stops() As DataObject
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Prepare the addresses
            '#Region "Addresses"

            ' Indicate that this is a departure stop.
            ' Single depot routes can only have one departure depot. 

            ' Required coordinates for every departure and stop on the route.

            ' The expected time on site, in seconds. This value is incorporated into the optimization engine.
            ' It also adjusts the estimated and dynamic ETA for a route.

            ' Input as many custom fields as needed. Custom data is passed through to mobile devices and to the manifest.

            '#End Region
            Dim addresses As Address() = New Address() {New Address() With { _
                .AddressString = "151 Arbor Way Milledgeville GA 31061", _
                .IsDepot = True, _
                .Latitude = 33.132675170898, _
                .Longitude = -83.244743347168, _
                .Time = 0, _
                .CustomFields = New Dictionary(Of String, String)() From { _
                    {"color", "red"}, _
                    {"size", "huge"} _
                } _
            }, New Address() With { _
                .AddressString = "230 Arbor Way Milledgeville GA 31061", _
                .Latitude = 33.129695892334, _
                .Longitude = -83.24577331543, _
                .Time = 0 _
            }, New Address() With { _
                .AddressString = "148 Bass Rd NE Milledgeville GA 31061", _
                .Latitude = 33.143497, _
                .Longitude = -83.224487, _
                .Time = 0 _
            }, New Address() With { _
                .AddressString = "117 Bill Johnson Rd NE Milledgeville GA 31061", _
                .Latitude = 33.141784667969, _
                .Longitude = -83.237518310547, _
                .Time = 0 _
            }, New Address() With { _
                .AddressString = "119 Bill Johnson Rd NE Milledgeville GA 31061", _
                .Latitude = 33.141086578369, _
                .Longitude = -83.238258361816, _
                .Time = 0 _
            }, New Address() With { _
                .AddressString = "131 Bill Johnson Rd NE Milledgeville GA 31061", _
                .Latitude = 33.142036437988, _
                .Longitude = -83.238845825195, _
                .Time = 0 _
            }, _
                New Address() With { _
                .AddressString = "138 Bill Johnson Rd NE Milledgeville GA 31061", _
                .Latitude = 33.14307, _
                .Longitude = -83.239334, _
                .Time = 0 _
            }, New Address() With { _
                .AddressString = "139 Bill Johnson Rd NE Milledgeville GA 31061", _
                .Latitude = 33.142734527588, _
                .Longitude = -83.237442016602, _
                .Time = 0 _
            }, New Address() With { _
                .AddressString = "145 Bill Johnson Rd NE Milledgeville GA 31061", _
                .Latitude = 33.143871307373, _
                .Longitude = -83.237342834473, _
                .Time = 0 _
            }, New Address() With { _
                .AddressString = "221 Blake Cir Milledgeville GA 31061", _
                .Latitude = 33.081462860107, _
                .Longitude = -83.208511352539, _
                .Time = 0 _
            }}

            ' Set parameters

            Dim parameters As New RouteParameters() With { _
                .AlgorithmType = AlgorithmType.TSP, _
                .StoreRoute = False, _
                .RouteName = "Single Driver Route 10 Stops", _
                .RouteDate = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.[Date].AddDays(1)), _
                .RouteTime = 60 * 60 * 7, _
                .Optimize = EnumHelper.GetEnumDescription(Optimize.Distance), _
                .DistanceUnit = EnumHelper.GetEnumDescription(DistanceUnit.MI), _
                .DeviceType = EnumHelper.GetEnumDescription(DeviceType.Web) _
            }

            Dim optimizationParameters As New OptimizationParameters() With { _
                .Addresses = addresses, _
                .Parameters = parameters _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As DataObject = route4Me.RunOptimization(optimizationParameters, errorString)

            ' Output the result
            PrintExampleOptimizationResult("SingleDriverRoute10Stops", dataObject, errorString)

            Return dataObject
        End Function
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import (
    ALGORITHM_TYPE,
    OPTIMIZE,
    DEVICE_TYPE,
    TRAVEL_MODE,
    DISTANCE_UNIT,
)
from route4me.api_endpoints import ROUTE_HOST

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    optimization = route4me.optimization
    address = route4me.address
    optimization.algorithm_type(ALGORITHM_TYPE.TSP)
    optimization.share_route(0)
    optimization.store_route(0)
    optimization.route_time(0)
    optimization.route_max_duration(86400)
    optimization.vehicle_capacity(1)
    optimization.vehicle_max_distance_mi(10000)
    optimization.route_name('Optimization Example')
    optimization.optimize(OPTIMIZE.DISTANCE)
    optimization.distance_unit(DISTANCE_UNIT.MI)
    optimization.device_type(DEVICE_TYPE.WEB)
    optimization.travel_mode(TRAVEL_MODE.DRIVING)
    address.add_address(
        address='754 5th Ave New York, NY 10019',
        lat=40.7636197,
        lng=-73.9744388,
        alias='Bergdorf Goodman',
        is_depot=1,
        time=0
    )
    address.add_address(
        address='717 5th Ave New York, NY 10022',
        lat=40.7669692,
        lng=-73.9693864,
        alias='Giorgio Armani',
        time=0
    )
    address.add_address(
        address='888 Madison Ave New York, NY 10014',
        lat=40.7715154,
        lng=-73.9669241,
        alias='Ralph Lauren Women\'s and Home',
        time=0
    )
    address.add_address(
        address='1011 Madison Ave New York, NY 10075',
        lat=40.7772129,
        lng=-73.9669,
        alias='Yigal Azrou\u00ebl',
        time=0
    )
    address.add_address(
        address='440 Columbus Ave New York, NY 10024',
        lat=40.7808364,
        lng=-73.9732729,
        alias='Frank Stella Clothier',
        time=0
    )
    address.add_address(
        address='324 Columbus Ave #1 New York, NY 10023',
        lat=40.7803123,
        lng=-73.9793079,
        alias='Liana',
        time=0
    )
    address.add_address(
        address='110 W End Ave New York, NY 10023',
        lat=40.7753077,
        lng=-73.9861529,
        alias='Toga Bike Shop',
        time=0
    )
    address.add_address(
        address='555 W 57th St New York, NY 10019',
        lat=40.7718005,
        lng=-73.9897716,
        alias='BMW of Manhattan',
        time=0
    )
    address.add_address(
        address='57 W 57th St New York, NY 10019',
        lat=40.7558695,
        lng=-73.9862019,
        alias='Verizon Wireless',
        time=0
    )

    response = route4me.run_optimization()
    print 'Optimization Link: %s' % response.links.view
    for address in response.addresses:
        print 'Route %s link: %sroute_id=%s' % (address.address,
                                                ROUTE_HOST,
                                                address.route_id)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples;

import com.route4me.sdk.Route4Me;
import com.route4me.sdk.model.Address;
import com.route4me.sdk.model.DataObject;
import com.route4me.sdk.managers.OptimizationManager;
import com.route4me.sdk.model.Parameters;
import com.route4me.sdk.model.enums.Constants.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SingleDriverRoute10Stops {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        Route4Me route4me = new Route4Me(apiKey);
        OptimizationManager optimizationManager = route4me.getOptimizationManager();
        Map<String, String> params = new HashMap<>();
        optimizationManager.setParams(params);
        DataObject data = new DataObject();
        Parameters parameters = new Parameters();
        List<Address> addresses = new ArrayList<>();
        data.setParameters(parameters);
        data.setAddresses(addresses);
        parameters.setAlgorithm_type(AlgorithmType.TSP.getValue());
        parameters.setStore_route(Boolean.FALSE);
        parameters.setShare_route(Boolean.FALSE);
        parameters.setRoute_name("Single Driver Route 10 Stops");
        parameters.setOptimize(Optimize.DISTANCE.toString());
        parameters.setDistance_unit(DistanceUnit.MI.toString());
        parameters.setDevice_type(DeviceType.WEB.toString());
        addresses.add(new Address("1604 PARKRIDGE PKWY, Louisville, KY, 40214",Boolean.TRUE, 38.141598, -85.793846, 300, 29400, 30000));
        addresses.add(new Address("1407 MCCOY, Louisville, KY, 40215",38.202496,-85.786514,300,30000,30600));
        addresses.add(new Address("4805 BELLEVUE AVE, Louisville, KY, 40215",38.178844,-85.774864,300,30600,31200));
        addresses.add(new Address("730 CECIL AVENUE, Louisville, KY, 40211",38.248684,-85.821121,300,31200,31800));
        addresses.add(new Address("650 SOUTH 29TH ST UNIT 315, Louisville, KY, 40211",38.251923,-85.800034,300,31800,32400));
        addresses.add(new Address("4629 HILLSIDE DRIVE, Louisville, KY, 40216",38.176067,-85.824638,300,32400,33000));
        addresses.add(new Address("4738 BELLEVUE AVE, Louisville, KY, 40215",38.179806,-85.775558,300,33000,33600));
        addresses.add(new Address("318 SO. 39TH STREET, Louisville, KY, 40212",38.259335,-85.815094,300,33600,34200));
        addresses.add(new Address("1324 BLUEGRASS AVE, Louisville, KY, 40215",38.179253,-85.785118,300,34200,34800));
        addresses.add(new Address("7305 ROYAL WOODS DR, Louisville, KY, 40214",38.162472,-85.792854,300,34800,35400));
        addresses.add(new Address("1661 W HILL ST, Louisville, KY, 40210",38.229584,-85.783966,300,35400,36000));        
        optimizationManager.setData(data);
        DataObject responseObject = optimizationManager.runOptimization();
        System.out.println("Optimization Problem ID:" + responseObject.getOptimization_problem_id());
        System.out.println("State:" + OptimizationState.get(responseObject.getState().intValue()));
        if (responseObject.getAddresses() != null) {
            for (Address address : responseObject.getAddresses()) {
                System.out.println("Address:" + address.getAddress());
                System.out.println("Route ID:" + address.getRoute_id());
            }
        }
    }
}
package SingleDriverRoute10Stops;
use strict;
use warnings FATAL => 'all';
use JSON;

use Data::Dumper;

sub SingleDriverRoute10Stops {
    my $route4Me = Route4MeManager->new(ExamplesInfrastructure->ApiKey);

    my $addresses = [
        Address->new(address => "151 Arbor Way Milledgeville GA 31061", is_depot => 1, lat => 33.132675170898,
                        lng => -83.244743347168, time => 0, custom_fields => {'color' => 'red', 'size' => 'huge'}),
        Address->new(address => "230 Arbor Way Milledgeville GA 31061", lat => 33.129695892334, lng => -83.24577331543, time => 0),
        Address->new(address => "148 Bass Rd NE Milledgeville GA 31061", lat => 33.143497, lng => -83.224487, time => 0),
        Address->new(address => "117 Bill Johnson Rd NE Milledgeville GA 31061", lat => 33.141784667969, lng => -83.237518310547, time => 0),
        Address->new(address => "119 Bill Johnson Rd NE Milledgeville GA 31061", lat => 33.141086578369, lng => -83.238258361816, time => 0),
        Address->new(address => "131 Bill Johnson Rd NE Milledgeville GA 31061", lat => 33.142036437988, lng => -83.238845825195, time => 0),
        Address->new(address => "138 Bill Johnson Rd NE Milledgeville GA 31061", lat => 33.14307, lng => -83.239334, time => 0),
        Address->new(address => "139 Bill Johnson Rd NE Milledgeville GA 31061", lat => 33.142734527588, lng => -83.237442016602, time => 0),
        Address->new(address => "145 Bill Johnson Rd NE Milledgeville GA 31061", lat => 33.143871307373, lng => -83.237342834473, time => 0),
        Address->new(address => "221 Blake Cir Milledgeville GA 31061", lat => 33.081462860107, lng => -83.208511352539, time => 0)
    ];

    my $parameters = RouteParameters->new(

        algorithm_type => AlgorithmType->TSP,
        store_route => 0,
        route_name => "Single Driver Route 10 Stops",

        route_date    => time, # check! R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.Date.AddDays(1)),
        route_time    => 60 * 60 * 7,
        optimize     => Optimize->Distance,
        distance_unit => DistanceUnit->MI,
        device_type   => DeviceType->Web
    );

    my $optimizationParameters = OptimizationParameters->new(
        addresses => $addresses,
        parameters => $parameters
    );

    my $errorString = "";
    my $dataObject = $route4Me->runOptimization($optimizationParameters, \$errorString);

    ExamplesInfrastructure->PrintExampleOptimizationResult("SingleDriverRoute10Stops", $dataObject, $errorString);

    return $dataObject;
}
1;
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := &route4me.NewClient("11111111111111111111111111111111")
    service := &routing.Service{Client: client}
    addresses := []*routing.Address{&routing.Address{AddressString: "151 Arbor Way Milledgeville GA 31061",
        // Indicate that this is a departure stop.
        // Single depot routes can only have one departure depot.
        IsDepot: true,

        // Required coordinates for every departure and stop on the route.
        Latitude:  33.132675170898,
        Longitude: -83.244743347168,

        // The expected time on site, in seconds. This value is incorporated into the optimization engine.
        // It also adjusts the estimated and dynamic ETA for a route.
        Time: 0,

        // Input as many custom fields as needed. Custom data is passed through to mobile devices and to the manifest.
        CustomFields: map[string]string{{"color", "red"}, {"size", "huge"}},
    },

        &routing.Address{AddressString: "230 Arbor Way Milledgeville GA 31061",
            Latitude:  33.129695892334,
            Longitude: -83.24577331543,
            Time:      0},

        &routing.Address{AddressString: "148 Bass Rd NE Milledgeville GA 31061",
            Latitude:  33.143497,
            Longitude: -83.224487,
            Time:      0},

        &routing.Address{AddressString: "117 Bill Johnson Rd NE Milledgeville GA 31061",
            Latitude:  33.141784667969,
            Longitude: -83.237518310547,
            Time:      0},

        &routing.Address{AddressString: "119 Bill Johnson Rd NE Milledgeville GA 31061",
            Latitude:  33.141086578369,
            Longitude: -83.238258361816,
            Time:      0},

        &routing.Address{AddressString: "131 Bill Johnson Rd NE Milledgeville GA 31061",
            Latitude:  33.142036437988,
            Longitude: -83.238845825195,
            Time:      0},

        &routing.Address{AddressString: "138 Bill Johnson Rd NE Milledgeville GA 31061",
            Latitude:  33.14307,
            Longitude: -83.239334,
            Time:      0},

        &routing.Address{AddressString: "139 Bill Johnson Rd NE Milledgeville GA 31061",
            Latitude:  33.142734527588,
            Longitude: -83.237442016602,
            Time:      0},

        &routing.Address{AddressString: "145 Bill Johnson Rd NE Milledgeville GA 31061",
            Latitude:  33.143871307373,
            Longitude: -83.237342834473,
            Time:      0},

        &routing.Address{AddressString: "221 Blake Cir Milledgeville GA 31061",
            Latitude:  33.081462860107,
            Longitude: -83.208511352539,
            Time:      0},
    }
    routeParams := &routing.RouteParameters{
        AlgorithmType:        routing.TSP,
        StoreRoute:           false,
        Name:                 "Single Driver Route 10 Stops",
        RouteDate:            time.Now().Unix(),
        RouteTime:            60 * 60 * 7,
        Optimize:             routing.Distance,
        DistanceUnit:         routing.Miles,
        DeviceType:           routing.Web,
        TravelMode:           routing.Driving,
    }

    optParams := &routing.OptimizationParameters{
        Addresses:  addresses,
        Parameters: routeParams,
    }
    _, err := service.RunOptimization(optParams)
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\OptimizationType;
use Route4Me\OptimizationProblem;
use Route4Me\OptimizationProblemParams;
use Route4Me\Enum\AlgorithmType;
use Route4Me\Enum\DistanceUnit;
use Route4Me\Enum\DeviceType;
use Route4Me\Enum\TravelMode;
use Route4Me\Enum\Metric;
use Route4Me\RouteParameters;
use Route4Me\Address;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Huge list of addresses
$json = json_decode(file_get_contents('./addresses.json'), true);
$json = array_slice($json, 0, 10);

$addresses = array();

foreach($json as $address) {
    $addresses[] = Address::fromArray($address);
}

$parameters = RouteParameters::fromArray(array(
    "algorithm_type"          => AlgorithmType::TSP,
    "distance_unit"           => DistanceUnit::MILES,
    "device_type"             => DeviceType::WEB,
    "optimize"                => OptimizationType::DISTANCE,
    "travel_mode"             => TravelMode::DRIVING,
    "route_max_duration"      => 86400,
    "vehicle_capacity"        => 1,
    "vehicle_max_distance_mi" => 10000,
    "rt"                      => true
));

$optimizationParams = new OptimizationProblemParams;
$optimizationParams->setAddresses($addresses);
$optimizationParams->setParameters($parameters);

$problems = OptimizationProblem::optimize($optimizationParams);

foreach ($problems as $problem) {
    if (is_array($problem) || is_object($problem)) {
        foreach ($problem as $key => $value) {
            if (!is_object($value)) {
                echo $key." --> ".$value."<br>";
            }
        }
    }
}
unit SingleDriverRoute10StopsUnit;

interface

uses SysUtils, DataObjectUnit, BaseOptimizationExampleUnit;

type
  TSingleDriverRoute10Stops = class(TBaseOptimizationExample)
  public
    function Execute: TDataObject;
  end;

implementation

uses
  IOptimizationParametersProviderUnit, OptimizationParametersUnit,
  SingleDriverRoute10StopsTestDataProviderUnit;

function TSingleDriverRoute10Stops.Execute: TDataObject;
var
  DataProvider: IOptimizationParametersProvider;
  ErrorString: String;
  Parameters: TOptimizationParameters;
begin
  DataProvider := TSingleDriverRoute10StopsTestDataProvider.Create;

  Parameters := DataProvider.OptimizationParameters;
  try
    Result := Route4MeManager.Optimization.Run(Parameters, ErrorString);
  finally
    FreeAndNil(Parameters);
  end;

  PrintExampleOptimizationResult('SingleDriverRoute10Stops', Result, ErrorString);
end;
end.
////////////////////////////////////////////////////////////////////////////////
// Single driver route 10 stops
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("addr.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }

    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    Json::Value params(Json::objectValue);
    params["route_name"] = "Single driver route 10 stops";
    params["algorithm_type"] = CRoute4Me::TSP;
    params["share_route"] = 0;
    params["optimize"] = CRoute4Me::Distance;
    params["distance_unit"] = CRoute4Me::MI;
    params["device_type"] = CRoute4Me::Web;
    int ret = 0;
    Json::Value addr0, addr;
    inf >> addr0;
    for(int i = 0; i < 10; i++)
        addr[i] = addr0[i];
    if(route.run_optimization(addr, params) == 0)
    {
        // use Json::StyledWriter instead of Json::FastWriter for a human friendly output
        cout << "Single driver route 10 stops:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Err: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include <json.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 1);
    const char file_name[] = "new_optimization.json";
    char* data = NULL;

    if (deserialize(file_name, &data))
    {
        printf("Data file not found!\n");
        return -1;
    }

    if (!add_optimization(data))
    {
        json_object* opt_lst = getJSONResponse();
        printf("%s\n", json_object_to_json_string(opt_lst));
    }
    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}


HTTP Request

POST
/api.v4/optimization_problem.php?api_key=...


See the sample JSON response of this method.


b) Create a new optimization with callback URL

The callback URL is a URL that gets called when the optimization is solved, or if there is an error. The callback is called with a POST request. The POST data sent are: timestamp (seconds), optimization_problem_id, and the ID of the optimization state. The state can be one of these values: 4 = OPTIMIZATION_STATE_OPTIMIZED, which means the optimization was successful; or 5 = OPTIMIZATION_STATE_ERROR, which means there was an error in solving the optimization.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
optimized_callback_url string Callback URL
input data POST data A valid JSON object string. See the Optimization Create JSON Schema as a guide.
<job id="Create Optimization With Callback URL">
  <script language="VBScript" src="../../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example demonstrates the process of creating an optimization with a callback URL.

      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/optimization_problem.php"
      apikey="11111111111111111111111111111111"
      optimized_callback_url="https://requestb.in/1o6cgge1"
      
      url=url&"?api_key="&apikey
      url=url&"&optimized_callback_url="&optimized_callback_url
      
      jFile="create_new_optimization_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest2 url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/optimization_problem.php
SET apikey=11111111111111111111111111111111

SET "optimized_callback_url=https://requestb.in/1o6cgge1"

:: The example demonstrates the process of creating an optimization with a callback URL.

ECHO ON

curl -o create_new_optimization_RESPONSE.json -k -X POST -d "@create_new_optimization_data.json" "%url%?api_key=%apikey%&optimized_callback_url=%optimized_callback_url%"

timeout /t 30
#!/bin/bash

# The callback URL was created on this site: https://requestb.in
# This URL will expire in a few days.
# To run this, please update the optimized_callback_url creating
# one link in the page mentioned above.


url=https://api.route4me.com/api.v4/optimization_problem.php
api_key=11111111111111111111111111111111
optimized_callback_url=https://requestb.in/p59ihlp5


curl -o create_new_optimization_RESPONSE.json -k -X POST -d "@create_new_optimization_data.json" "$url?api_key=$api_key&optimized_callback_url=$optimized_callback_url"

echo "Finished..."

sleep 15
public DataObject OptimizationWithCallbackUrl()
{
  // Create the manager with the API key
  Route4MeManager route4Me = new Route4MeManager(c_ApiKey);
  
  // The example refers to the process of creating a new optimization with a callback URL.

  // Prepare the addresses
  Address[] addresses = new Address[]
  {
#region Addresses

new Address() { AddressString   = "3634 W Market St, Fairlawn, OH 44333",
        // All possible originating locations are depots and should be marked as true.
        // Stylistically, we recommend all depots should be at the top of the destinations list.
        IsDepot          = true,
        Latitude         = 41.135762259364,
        Longitude        = -81.629313826561,

        TimeWindowStart  = null,
        TimeWindowEnd    = null,
        TimeWindowStart2 = null,
        TimeWindowEnd2   = null,
        Time             = null
},

new Address() { AddressString   = "1218 Ruth Ave, Cuyahoga Falls, OH 44221",
        Latitude        = 41.135762259364,
        Longitude       = -81.629313826561,

        // Together, these two specify the time window of a destination.
        // Seconds offset relative to the route start time for the open availability of a destination
        TimeWindowStart  = 6 * 3600 + 00 * 60,
        // Seconds offset relative to the route end time for the open availability of a destination
        TimeWindowEnd    = 6 * 3600 + 30 * 60,

        // Second 'TimeWindowStart'
        TimeWindowStart2 = 7 * 3600 + 00 * 60,
        // Second 'TimeWindowEnd'
        TimeWindowEnd2   = 7 * 3600 + 20 * 60,

        // The number of seconds at the destination.
        Time             = 300
},

new Address() { AddressString    = "512 Florida Pl, Barberton, OH 44203",
        Latitude         = 41.003671512008,
        Longitude        = -81.598461046815,
        TimeWindowStart  = 7 * 3600 + 30 * 60,
        TimeWindowEnd    = 7 * 3600 + 40 * 60,
        TimeWindowStart2 = 8 * 3600 + 00 * 60,
        TimeWindowEnd2   = 8 * 3600 + 10 * 60,
        Time             = 300
},

new Address() { AddressString    = "512 Florida Pl, Barberton, OH 44203",
        Latitude         = 41.003671512008,
        Longitude        = -81.598461046815,
        TimeWindowStart  = 8 * 3600 + 30 * 60,
        TimeWindowEnd    = 8 * 3600 + 40 * 60,
        TimeWindowStart2 = 8 * 3600 + 50 * 60,
        TimeWindowEnd2   = 9 * 3600 + 00 * 60,
        Time             = 100
},

new Address() { AddressString    = "3495 Purdue St, Cuyahoga Falls, OH 44221",
        Latitude         = 41.162971496582,
        Longitude        = -81.479049682617,
        TimeWindowStart  = 9 * 3600 + 00 * 60,
        TimeWindowEnd    = 9 * 3600 + 15 * 60,
        TimeWindowStart2 = 9 * 3600 + 30 * 60,
        TimeWindowEnd2   = 9 * 3600 + 45 * 60,
        Time             = 300
},

new Address() { AddressString    = "1659 Hibbard Dr, Stow, OH 44224",
        Latitude         = 41.194505989552,
        Longitude        = -81.443351581693,
        TimeWindowStart  = 10 * 3600 + 00 * 60,
        TimeWindowEnd    = 10 * 3600 + 15 * 60,
        TimeWindowStart2 = 10 * 3600 + 30 * 60,
        TimeWindowEnd2   = 10 * 3600 + 45 * 60,
        Time             = 300
},

new Address() { AddressString    = "2705 N River Rd, Stow, OH 44224",
        Latitude         = 41.145240783691,
        Longitude        = -81.410247802734,
        TimeWindowStart  = 11 * 3600 + 00 * 60,
        TimeWindowEnd    = 11 * 3600 + 15 * 60,
        TimeWindowStart2 = 11 * 3600 + 30 * 60,
        TimeWindowEnd2   = 11 * 3600 + 45 * 60,
        Time             = 300
},

new Address() { AddressString    = "10159 Bissell Dr, Twinsburg, OH 44087",
        Latitude         = 41.340042114258,
        Longitude        = -81.421226501465,
        TimeWindowStart  = 12 * 3600 + 00 * 60,
        TimeWindowEnd    = 12 * 3600 + 15 * 60,
        TimeWindowStart2 = 12 * 3600 + 30 * 60,
        TimeWindowEnd2   = 12 * 3600 + 45 * 60,
        Time             = 300
},

new Address() { AddressString    = "367 Cathy Dr, Munroe Falls, OH 44262",
        Latitude         = 41.148578643799,
        Longitude        = -81.429229736328,
        TimeWindowStart  = 13 * 3600 + 00 * 60,
        TimeWindowEnd    = 13 * 3600 + 15 * 60,
        TimeWindowStart2 = 13 * 3600 + 30 * 60,
        TimeWindowEnd2   = 13 * 3600 + 45 * 60,
        Time             = 300
},

new Address() { AddressString    = "367 Cathy Dr, Munroe Falls, OH 44262",
        Latitude         = 41.148578643799,
        Longitude        = -81.429229736328,
        TimeWindowStart  = 14 * 3600 + 00 * 60,
        TimeWindowEnd    = 14 * 3600 + 15 * 60,
        TimeWindowStart2 = 14 * 3600 + 30 * 60,
        TimeWindowEnd2   = 14 * 3600 + 45 * 60,
        Time             = 300
},

new Address() { AddressString    = "512 Florida Pl, Barberton, OH 44203",
        Latitude         = 41.003671512008,
        Longitude        = -81.598461046815,
        TimeWindowStart  = 15 * 3600 + 00 * 60,
        TimeWindowEnd    = 15 * 3600 + 15 * 60,
        TimeWindowStart2 = 15 * 3600 + 30 * 60,
        TimeWindowEnd2   = 15 * 3600 + 45 * 60,
        Time             = 300
},

new Address() { AddressString    = "559 W Aurora Rd, Northfield, OH 44067",
        Latitude         = 41.315116882324,
        Longitude        = -81.558746337891,
        TimeWindowStart  = 16 * 3600 + 00 * 60,
        TimeWindowEnd    = 16 * 3600 + 15 * 60,
        TimeWindowStart2 = 16 * 3600 + 30 * 60,
        TimeWindowEnd2   = 17 * 3600 + 00 * 60,
        Time             = 50
}

#endregion
  };

  // Set parameters
  RouteParameters parameters = new RouteParameters()
  {
    AlgorithmType = AlgorithmType.TSP,
    StoreRoute = false,
    RouteName = "Single Driver Multiple TimeWindows 12 Stops",
    SharedPublicly = "true",

    RouteDate = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.Date.AddDays(1)),
    RouteTime = 5 * 3600 + 30 * 60,
    Optimize = Optimize.Distance.Description(),
    DistanceUnit = DistanceUnit.MI.Description(),
    DeviceType = DeviceType.Web.Description()
  };

  OptimizationParameters optimizationParameters = new OptimizationParameters()
  {
    Addresses = addresses,
    OptimizedCallbackURL = @"https://requestb.in/1o6cgge1",
    ShowDirections = true,
    Redirect = false,
    Parameters = parameters
  };

  // Run the query
  string errorString;
  DataObject dataObject = route4Me.RunOptimization(optimizationParameters, out errorString);

  // Output the result
  PrintExampleOptimizationResult("SingleDriverMultipleTimeWindows", dataObject, errorString);

  return dataObject;
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Function OptimizationWithCallbackUrl() As DataObject
            Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
			
			' The example refers to the process of creating a new optimization with a callback URL.
			
            Dim addresses As Address() = New Address() {New Address() With {
                .AddressString = "3634 W Market St, Fairlawn, OH 44333",
                .IsDepot = True,
                .Latitude = 41.135762259364,
                .Longitude = -81.629313826561,
                .TimeWindowStart = Nothing,
                .TimeWindowEnd = Nothing,
                .TimeWindowStart2 = Nothing,
                .TimeWindowEnd2 = Nothing,
                .Time = Nothing
            }, New Address() With {
                .AddressString = "1218 Ruth Ave, Cuyahoga Falls, OH 44221",
                .Latitude = 41.135762259364,
                .Longitude = -81.629313826561,
                .TimeWindowStart = 6 * 3600 + 0 * 60,
                .TimeWindowEnd = 6 * 3600 + 30 * 60,
                .TimeWindowStart2 = 7 * 3600 + 0 * 60,
                .TimeWindowEnd2 = 7 * 3600 + 20 * 60,
                .Time = 300
            }, New Address() With {
                .AddressString = "512 Florida Pl, Barberton, OH 44203",
                .Latitude = 41.003671512008,
                .Longitude = -81.598461046815,
                .TimeWindowStart = 7 * 3600 + 30 * 60,
                .TimeWindowEnd = 7 * 3600 + 40 * 60,
                .TimeWindowStart2 = 8 * 3600 + 0 * 60,
                .TimeWindowEnd2 = 8 * 3600 + 10 * 60,
                .Time = 300
            }, New Address() With {
                .AddressString = "512 Florida Pl, Barberton, OH 44203",
                .Latitude = 41.003671512008,
                .Longitude = -81.598461046815,
                .TimeWindowStart = 8 * 3600 + 30 * 60,
                .TimeWindowEnd = 8 * 3600 + 40 * 60,
                .TimeWindowStart2 = 8 * 3600 + 50 * 60,
                .TimeWindowEnd2 = 9 * 3600 + 0 * 60,
                .Time = 100
            }, New Address() With {
                .AddressString = "3495 Purdue St, Cuyahoga Falls, OH 44221",
                .Latitude = 41.162971496582,
                .Longitude = -81.479049682617,
                .TimeWindowStart = 9 * 3600 + 0 * 60,
                .TimeWindowEnd = 9 * 3600 + 15 * 60,
                .TimeWindowStart2 = 9 * 3600 + 30 * 60,
                .TimeWindowEnd2 = 9 * 3600 + 45 * 60,
                .Time = 300
            }, New Address() With {
                .AddressString = "1659 Hibbard Dr, Stow, OH 44224",
                .Latitude = 41.194505989552,
                .Longitude = -81.443351581693,
                .TimeWindowStart = 10 * 3600 + 0 * 60,
                .TimeWindowEnd = 10 * 3600 + 15 * 60,
                .TimeWindowStart2 = 10 * 3600 + 30 * 60,
                .TimeWindowEnd2 = 10 * 3600 + 45 * 60,
                .Time = 300
            }, New Address() With {
                .AddressString = "2705 N River Rd, Stow, OH 44224",
                .Latitude = 41.145240783691,
                .Longitude = -81.410247802734,
                .TimeWindowStart = 11 * 3600 + 0 * 60,
                .TimeWindowEnd = 11 * 3600 + 15 * 60,
                .TimeWindowStart2 = 11 * 3600 + 30 * 60,
                .TimeWindowEnd2 = 11 * 3600 + 45 * 60,
                .Time = 300
            }, New Address() With {
                .AddressString = "10159 Bissell Dr, Twinsburg, OH 44087",
                .Latitude = 41.340042114258,
                .Longitude = -81.421226501465,
                .TimeWindowStart = 12 * 3600 + 0 * 60,
                .TimeWindowEnd = 12 * 3600 + 15 * 60,
                .TimeWindowStart2 = 12 * 3600 + 30 * 60,
                .TimeWindowEnd2 = 12 * 3600 + 45 * 60,
                .Time = 300
            }, New Address() With {
                .AddressString = "367 Cathy Dr, Munroe Falls, OH 44262",
                .Latitude = 41.148578643799,
                .Longitude = -81.429229736328,
                .TimeWindowStart = 13 * 3600 + 0 * 60,
                .TimeWindowEnd = 13 * 3600 + 15 * 60,
                .TimeWindowStart2 = 13 * 3600 + 30 * 60,
                .TimeWindowEnd2 = 13 * 3600 + 45 * 60,
                .Time = 300
            }, New Address() With {
                .AddressString = "367 Cathy Dr, Munroe Falls, OH 44262",
                .Latitude = 41.148578643799,
                .Longitude = -81.429229736328,
                .TimeWindowStart = 14 * 3600 + 0 * 60,
                .TimeWindowEnd = 14 * 3600 + 15 * 60,
                .TimeWindowStart2 = 14 * 3600 + 30 * 60,
                .TimeWindowEnd2 = 14 * 3600 + 45 * 60,
                .Time = 300
            }, New Address() With {
                .AddressString = "512 Florida Pl, Barberton, OH 44203",
                .Latitude = 41.003671512008,
                .Longitude = -81.598461046815,
                .TimeWindowStart = 15 * 3600 + 0 * 60,
                .TimeWindowEnd = 15 * 3600 + 15 * 60,
                .TimeWindowStart2 = 15 * 3600 + 30 * 60,
                .TimeWindowEnd2 = 15 * 3600 + 45 * 60,
                .Time = 300
            }, New Address() With {
                .AddressString = "559 W Aurora Rd, Northfield, OH 44067",
                .Latitude = 41.315116882324,
                .Longitude = -81.558746337891,
                .TimeWindowStart = 16 * 3600 + 0 * 60,
                .TimeWindowEnd = 16 * 3600 + 15 * 60,
                .TimeWindowStart2 = 16 * 3600 + 30 * 60,
                .TimeWindowEnd2 = 17 * 3600 + 0 * 60,
                .Time = 50
            }}
            Dim parameters As RouteParameters = New RouteParameters() With {
                .AlgorithmType = AlgorithmType.TSP,
                .StoreRoute = False,
                .RouteName = "Single Driver Multiple TimeWindows 12 Stops",
                .SharedPublicly = "true",
                .RouteDate = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.Date.AddDays(1)),
                .RouteTime = 5 * 3600 + 30 * 60,
                .Optimize = Optimize.Distance.GetEnumDescription(),
                .DistanceUnit = DistanceUnit.MI.GetEnumDescription(),
                .DeviceType = DeviceType.Web.GetEnumDescription()
            }
            Dim optimizationParameters As OptimizationParameters = New OptimizationParameters() With {
                .Addresses = addresses,
                .OptimizedCallbackURL = "https://requestb.in/1o6cgge1",
                .ShowDirections = True,
                .Redirect = False,
                .Parameters = parameters
            }
            Dim errorString As String = ""
            Dim dataObject As DataObject = route4Me.RunOptimization(optimizationParameters, errorString)
            PrintExampleOptimizationResult("SingleDriverMultipleTimeWindows", dataObject, errorString)
            Return dataObject
        End Function
    End Class
End Namespace
from route4me import Route4Me
from route4me.api_endpoints import ROUTE_HOST
from route4me.constants import (
    ALGORITHM_TYPE,
    OPTIMIZE,
    DEVICE_TYPE,
    TRAVEL_MODE,
    DISTANCE_UNIT,
)

KEY = "11111111111111111111111111111111"

def main():
    callback_url = 'https://requestb.in/y8bybfy8'
    route4me = Route4Me(KEY)
    optimization = route4me.optimization
    address = route4me.address
    optimization.algorithm_type(ALGORITHM_TYPE.TSP)
    optimization.share_route(0)
    optimization.store_route(0)
    optimization.route_time(0)
    optimization.route_max_duration(86400)
    optimization.vehicle_capacity(1)
    optimization.vehicle_max_distance_mi(10000)
    optimization.route_name('Optimization Example')
    optimization.optimize(OPTIMIZE.DISTANCE)
    optimization.distance_unit(DISTANCE_UNIT.MI)
    optimization.device_type(DEVICE_TYPE.WEB)
    optimization.travel_mode(TRAVEL_MODE.DRIVING)
    optimization.optimized_callback_url(callback_url)
    address.add_address(
        address='754 5th Ave New York, NY 10019',
        lat=40.7636197,
        lng=-73.9744388,
        alias='Bergdorf Goodman',
        is_depot=1,
        time=0
    )
    address.add_address(
        address='717 5th Ave New York, NY 10022',
        lat=40.7669692,
        lng=-73.9693864,
        alias='Giorgio Armani',
        time=0
    )
    address.add_address(
        address='888 Madison Ave New York, NY 10014',
        lat=40.7715154,
        lng=-73.9669241,
        alias='Ralph Lauren Women\'s and Home',
        time=0
    )
    address.add_address(
        address='1011 Madison Ave New York, NY 10075',
        lat=40.7772129,
        lng=-73.9669,
        alias='Yigal Azrou\u00ebl',
        time=0
    )
    address.add_address(
        address='440 Columbus Ave New York, NY 10024',
        lat=40.7808364,
        lng=-73.9732729,
        alias='Frank Stella Clothier',
        time=0
    )
    address.add_address(
        address='324 Columbus Ave #1 New York, NY 10023',
        lat=40.7803123,
        lng=-73.9793079,
        alias='Liana',
        time=0
    )
    address.add_address(
        address='110 W End Ave New York, NY 10023',
        lat=40.7753077,
        lng=-73.9861529,
        alias='Toga Bike Shop',
        time=0
    )
    address.add_address(
        address='555 W 57th St New York, NY 10019',
        lat=40.7718005,
        lng=-73.9897716,
        alias='BMW of Manhattan',
        time=0
    )
    address.add_address(
        address='57 W 57th St New York, NY 10019',
        lat=40.7558695,
        lng=-73.9862019,
        alias='Verizon Wireless',
        time=0
    )

    response = route4me.run_optimization()
    print('Optimization Problem ID: {}'.format(response['optimization_problem_id']))
    print('Optimization Link: {}'.format(response['links']['view']))
    for address in response['addresses']:
        print('Route {0} \tlink: {1}route_id: {2}'.format(address['address'],
                                                          ROUTE_HOST,
                                                          address['route_id']))

    print('\nPlease open this URL {0}?inspect.')
    print('Verify that there is a POST request with this {1} \
           optimization_problem_id'.format(callback_url,
                                           response['optimization_problem_id']))

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\OptimizationType;
use Route4Me\OptimizationProblem;
use Route4Me\OptimizationProblemParams;
use Route4Me\Enum\AlgorithmType;
use Route4Me\Enum\DistanceUnit;
use Route4Me\Enum\DeviceType;
use Route4Me\Enum\TravelMode;
use Route4Me\Enum\Metric;
use Route4Me\RouteParameters;
use Route4Me\Address;
use Route4Me\Route;

// The example refers to the process of creating a new optimization with a callback URL.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Huge list of addresses
$json = json_decode(file_get_contents('../addresses.json'), true);

$addresses = array();
foreach ($json as $address) {
    $addresses[] = Address::fromArray($address);
}

$parameters = RouteParameters::fromArray(array(
    "algorithm_type"     => Algorithmtype::TSP,
    "store_route"        => FALSE,
    "route_name"         => "Single Driver Multiple TimeWindows 12 Stops",
    "shared_publicly"    => TRUE,
    "route_date"         => time() + 24 * 60 * 60,
    "route_time"         => 5 * 3600 + 30 * 60,
    "distance_unit"      => DistanceUnit::MILES,
    "device_type"        => DeviceType::WEB,
    "optimize"           => OptimizationType::DISTANCE
));

$optimizationParams = OptimizationProblemParams::fromArray(array(
    "addresses"               => $addresses,
    "parameters"              => $parameters,
    "optimized_callback_url"  => @"https://requestb.in/1o6cgge1",
    "show_directions"         => TRUE,
    "redirect"                => FALSE
));

$optimizationParams = new OptimizationProblemParams;
$optimizationParams->setAddresses($addresses);
$optimizationParams->setParameters($parameters);

$problem = OptimizationProblem::optimize($optimizationParams);

foreach ((array)$problem as $key => $value) {
    if (is_string($value)) {
        echo $key." --> ".$value."<br>";
    } else {
        echo "************ $key ************* <br>";
        Route4Me::simplePrint((array)$value, true);
        echo "******************************* <br>";
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/optimization_problem.php?api_key=...&optimized_callback_url=...


See the sample JSON response of this method.


c) Create a new optimization using separate depots section

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description  
api_key string API key of the user  
parameters array Route Parameters. See the Route Parameters JSON schema as a guide.  
depots array A valid JSON array of Depot objects. See the Depot JSON Schema as a guide. POST
addresses array A valid JSON array of Address objects. See the Address JSON Schema as a guide. POST
<job id="Multiple Depots Separate Section">
	<script language="VBScript" src="Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example refers to the process of creating an optimization using separate section of the depots in the route parameters.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/optimization_problem.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="multiple_separate_depots_data.json"
			
			Set r4m=New Route4Me
			r4m.OutputFile = "multiple_separate_depots_RESPONSE.json"
			
			r4m.HttpPostRequest2 url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

:: The example refers to the process of creating an optimization using separate section of the depots in the route parameters.

SET url=https://api.route4me.com/api.v4/optimization_problem.php
SET apikey=11111111111111111111111111111111

ECHO ON

curl -o multiple_separate_depots_RESPONSE.json -g -X POST -k -d "@multiple_separate_depots_data.json" "%url%?api_key=%apikey%" 

timeout /t 30
 #!/bin/bash

 # The example refers to the process of creating an optimization using separate section of the depots in the route parameters.

url=https://www.route4me.com/api.v4/optimization_problem.php
apikey=11111111111111111111111111111111

curl -o multiple_separate_depots_RESPONSE.json -g -X POST -k -d "@multiple_separate_depots_data.json" "$url?api_key=$apikey" 

echo "Finished..."

sleep 15
public void MultipleSeparateDepostMultipleDriverTest()
{
	if (skip == "yes") return;
	// Create the manager with the api key
	var route4Me = new Route4MeManager(c_ApiKey);

	#region Depots
	Address[] depots = new Address[]
	{
		new Address() { AddressString   = "3634 W Market St, Fairlawn, OH 44333",
			Latitude        = 41.135762259364,
			Longitude       = -81.629313826561 },

		new Address() { AddressString   = "2705 N River Rd, Stow, OH 44224",
			Latitude        = 41.145240783691,
			Longitude       = -81.410247802734 }
	};
	#endregion

	// Prepare the addresses
	Address[] addresses = new Address[]
	  {
		#region Addresses

		new Address() { AddressString   = "1218 Ruth Ave, Cuyahoga Falls, OH 44221",
						Latitude        = 41.135762259364,
						Longitude       = -81.629313826561,
						Time            = 300,
						TimeWindowStart = 29465,
						TimeWindowEnd   = 30529},

		new Address() { AddressString   = "512 Florida Pl, Barberton, OH 44203",
						Latitude        = 41.003671512008,
						Longitude       = -81.598461046815,
						Time            = 300,
						TimeWindowStart = 30529,
						TimeWindowEnd   = 33779},

		new Address() { AddressString   = "512 Florida Pl, Barberton, OH 44203",
						Latitude        = 41.003671512008,
						Longitude       = -81.598461046815,
						Time            = 100,
						TimeWindowStart = 33779,
						TimeWindowEnd   = 33944},

		new Address() { AddressString   = "3495 Purdue St, Cuyahoga Falls, OH 44221",
						Latitude        = 41.162971496582,
						Longitude       = -81.479049682617,
						Time            = 300,
						TimeWindowStart = 33944,
						TimeWindowEnd   = 34801},

		new Address() { AddressString   = "1659 Hibbard Dr, Stow, OH 44224",
						Latitude        = 41.194505989552,
						Longitude       = -81.443351581693,
						Time            = 300,
						TimeWindowStart = 34801,
						TimeWindowEnd   = 36366},

		new Address() { AddressString   = "10159 Bissell Dr, Twinsburg, OH 44087",
						Latitude        = 41.340042114258,
						Longitude       = -81.421226501465,
						Time            = 300,
						TimeWindowStart = 39173,
						TimeWindowEnd   = 41617},

		new Address() { AddressString   = "367 Cathy Dr, Munroe Falls, OH 44262",
						Latitude        = 41.148578643799,
						Longitude       = -81.429229736328,
						Time            = 300,
						TimeWindowStart = 41617,
						TimeWindowEnd   = 43660},

		new Address() { AddressString   = "367 Cathy Dr, Munroe Falls, OH 44262",
						Latitude        = 41.148578643799,
						Longitude       = -81.429229736328,
						Time            = 300,
						TimeWindowStart = 43660,
						TimeWindowEnd   = 46392},

		new Address() { AddressString   = "512 Florida Pl, Barberton, OH 44203",
						Latitude        = 41.003671512008,
						Longitude       = -81.598461046815,
						Time            = 300,
						TimeWindowStart = 46392,
						TimeWindowEnd   = 48389},

		new Address() { AddressString   = "559 W Aurora Rd, Northfield, OH 44067",
						Latitude        = 41.315116882324,
						Longitude       = -81.558746337891,
						Time            = 50,
						TimeWindowStart = 48389,
						TimeWindowEnd   = 48449},

		new Address() { AddressString   = "3933 Klein Ave, Stow, OH 44224",
						Latitude        = 41.169467926025,
						Longitude       = -81.429420471191,
						Time            = 300,
						TimeWindowStart = 48449,
						TimeWindowEnd   = 50152},

		new Address() { AddressString   = "2148 8th St, Cuyahoga Falls, OH 44221",
						Latitude        = 41.136692047119,
						Longitude       = -81.493492126465,
						Time            = 300,
						TimeWindowStart = 50152,
						TimeWindowEnd   = 51982},

		new Address() { AddressString   = "3731 Osage St, Stow, OH 44224",
						Latitude        = 41.161357879639,
						Longitude       = -81.42293548584,
						Time            = 100,
						TimeWindowStart = 51982,
						TimeWindowEnd   = 52180},

		new Address() { AddressString   = "3731 Osage St, Stow, OH 44224",
						Latitude        = 41.161357879639,
						Longitude       = -81.42293548584,
						Time            = 300,
						TimeWindowStart = 52180,
						TimeWindowEnd   = 54379}

		#endregion
	  };

	// Set parameters
	var parameters = new RouteParameters()
	{
		//specify capacitated vehicle routing with time windows and multiple depots, with multiple drivers
		AlgorithmType = AlgorithmType.CVRP_TW_MD,

		//set an arbitrary route name
		//this value shows up in the website, and all the connected mobile device
		RouteName = "Multiple Separate Depots, Multiple Driver",

		//the route start date in UTC, unix timestamp seconds (Tomorrow)
		RouteDate = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.Date.AddDays(1)),
		//the time in UTC when a route is starting (7AM)
		RouteTime = 60 * 60 * 7,

		//the maximum duration of a route
		RouteMaxDuration = 86400,
		VehicleCapacity = 1,
		VehicleMaxDistanceMI = 10000,

		Optimize = Optimize.Distance.Description(),
		DistanceUnit = DistanceUnit.MI.Description(),
		DeviceType = DeviceType.Web.Description(),
		TravelMode = TravelMode.Driving.Description(),
		Metric = Metric.Geodesic
	};

	var optimizationParameters = new OptimizationParameters()
	{
		Addresses = addresses,
		Parameters = parameters,
		Depots = depots
	};

	// Run the query
	dataObject = route4Me.RunOptimization(optimizationParameters, out string errorString);

	Assert.IsNotNull(dataObject, "MultipleSeparateDepostMultipleDriverTest failed. " + errorString);

	var optimizationDepots = dataObject.Addresses.Where(x => x.IsDepot == true);

	Assert.IsTrue(optimizationDepots.Count() == depots.Length, "The depots number is not "+ depots.Length);

	List<string> depotAddresses = depots.Select(x => x.AddressString).ToList();

	foreach (var depot in optimizationDepots)
	{
		Assert.IsTrue(depotAddresses.Contains(depot.AddressString), "The address "+ depot.AddressString+" is not depot");
	}

	tdr.RemoveOptimization(new string[] { dataObject.OptimizationProblemId });
}
Public Sub MultipleSeparateDepostMultipleDriverTest()
If skip = "yes" Then Return

Dim route4Me = New Route4MeManager(c_ApiKey)

Dim depots As Address() = New Address() {
	New Address() With {
		.AddressString = "3634 W Market St, Fairlawn, OH 44333",
		.Latitude = 41.135762259364,
		.Longitude = -81.629313826561
	},
	New Address() With {
		.AddressString = "2705 N River Rd, Stow, OH 44224",
		.Latitude = 41.145240783691,
		.Longitude = -81.410247802734
	}
}

#Region "Addresses"
Dim addresses As Address() = New Address() {
	New Address() With {
		.AddressString = "1218 Ruth Ave, Cuyahoga Falls, OH 44221",
		.Latitude = 41.135762259364,
		.Longitude = -81.629313826561,
		.Time = 300,
		.TimeWindowStart = 29465,
		.TimeWindowEnd = 30529
	},
	New Address() With {
		.AddressString = "512 Florida Pl, Barberton, OH 44203",
		.Latitude = 41.003671512008,
		.Longitude = -81.598461046815,
		.Time = 300,
		.TimeWindowStart = 30529,
		.TimeWindowEnd = 33779
	},
	New Address() With {
		.AddressString = "512 Florida Pl, Barberton, OH 44203",
		.Latitude = 41.003671512008,
		.Longitude = -81.598461046815,
		.Time = 100,
		.TimeWindowStart = 33779,
		.TimeWindowEnd = 33944
	},
	New Address() With {
		.AddressString = "3495 Purdue St, Cuyahoga Falls, OH 44221",
		.Latitude = 41.162971496582,
		.Longitude = -81.479049682617,
		.Time = 300,
		.TimeWindowStart = 33944,
		.TimeWindowEnd = 34801
	},
	New Address() With {
		.AddressString = "1659 Hibbard Dr, Stow, OH 44224",
		.Latitude = 41.194505989552,
		.Longitude = -81.443351581693,
		.Time = 300,
		.TimeWindowStart = 34801,
		.TimeWindowEnd = 36366
	},
	New Address() With {
		.AddressString = "10159 Bissell Dr, Twinsburg, OH 44087",
		.Latitude = 41.340042114258,
		.Longitude = -81.421226501465,
		.Time = 300,
		.TimeWindowStart = 39173,
		.TimeWindowEnd = 41617
	},
	New Address() With {
		.AddressString = "367 Cathy Dr, Munroe Falls, OH 44262",
		.Latitude = 41.148578643799,
		.Longitude = -81.429229736328,
		.Time = 300,
		.TimeWindowStart = 41617,
		.TimeWindowEnd = 43660
	},
	New Address() With {
		.AddressString = "367 Cathy Dr, Munroe Falls, OH 44262",
		.Latitude = 41.148578643799,
		.Longitude = -81.429229736328,
		.Time = 300,
		.TimeWindowStart = 43660,
		.TimeWindowEnd = 46392
	},
	New Address() With {
		.AddressString = "512 Florida Pl, Barberton, OH 44203",
		.Latitude = 41.003671512008,
		.Longitude = -81.598461046815,
		.Time = 300,
		.TimeWindowStart = 46392,
		.TimeWindowEnd = 48389
	},
	New Address() With {
		.AddressString = "559 W Aurora Rd, Northfield, OH 44067",
		.Latitude = 41.315116882324,
		.Longitude = -81.558746337891,
		.Time = 50,
		.TimeWindowStart = 48389,
		.TimeWindowEnd = 48449
	},
	New Address() With {
		.AddressString = "3933 Klein Ave, Stow, OH 44224",
		.Latitude = 41.169467926025,
		.Longitude = -81.429420471191,
		.Time = 300,
		.TimeWindowStart = 48449,
		.TimeWindowEnd = 50152
	},
	New Address() With {
		.AddressString = "2148 8th St, Cuyahoga Falls, OH 44221",
		.Latitude = 41.136692047119,
		.Longitude = -81.493492126465,
		.Time = 300,
		.TimeWindowStart = 50152,
		.TimeWindowEnd = 51982
	},
	New Address() With {
		.AddressString = "3731 Osage St, Stow, OH 44224",
		.Latitude = 41.161357879639,
		.Longitude = -81.42293548584,
		.Time = 100,
		.TimeWindowStart = 51982,
		.TimeWindowEnd = 52180
	},
	New Address() With {
		.AddressString = "3731 Osage St, Stow, OH 44224",
		.Latitude = 41.161357879639,
		.Longitude = -81.42293548584,
		.Time = 300,
		.TimeWindowStart = 52180,
		.TimeWindowEnd = 54379
	}}
#End Region
Dim parameters = New RouteParameters() With {
	.AlgorithmType = AlgorithmType.CVRP_TW_MD,
	.RouteName = "Multiple Separate Depots, Multiple Driver",
	.RouteDate = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.Date.AddDays(1)),
	.RouteTime = 60 * 60 * 7,
	.RouteMaxDuration = 86400,
	.VehicleCapacity = 1,
	.VehicleMaxDistanceMI = 10000,
	.Optimize = Optimize.Distance.GetEnumDescription(),
	.DistanceUnit = DistanceUnit.MI.GetEnumDescription(),
	.DeviceType = DeviceType.Web.GetEnumDescription(),
	.TravelMode = TravelMode.Driving.GetEnumDescription(),
	.Metric = Metric.Geodesic
}

Dim optimizationParameters = New OptimizationParameters() With {
	.Addresses = addresses,
	.Parameters = parameters,
	.Depots = depots
}

Dim errorString As String = Nothing

dataObject = route4Me.RunOptimization(optimizationParameters, errorString)

Assert.IsNotNull(dataObject, "MultipleSeparateDepostMultipleDriverTest failed. " & errorString)

Dim optimizationDepots = dataObject.Addresses.Where(Function(x) x.IsDepot = True)

Assert.IsTrue(optimizationDepots.Count() = depots.Length, "The depots number is not " & depots.Length)

Dim depotAddresses As List(Of String) = depots.[Select](Function(x) x.AddressString).ToList()

For Each depot In optimizationDepots
	Assert.IsTrue(depotAddresses.Contains(depot.AddressString), "The address " & depot.AddressString & " is not depot")
Next

tdr.RemoveOptimization(New String() {dataObject.OptimizationProblemId})
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php

namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../');
require $root.'/vendor/autoload.php';

use Route4Me\Enum\OptimizationType;
use Route4Me\Enum\AlgorithmType;
use Route4Me\Enum\DistanceUnit;
use Route4Me\Enum\DeviceType;
use Route4Me\Enum\TravelMode;
use Route4Me\Enum\Metric;

// Set the api key in the Route4me class
// This example is not available for demo API key
Route4Me::setApiKey('11111111111111111111111111111111');

// List of addresses
$jsonAddresses = json_decode(file_get_contents('./addresses_only.json'), true);

$addresses = [];
foreach ($jsonAddresses as $address) {
    $addresses[] = Address::fromArray($address);
}

$jsonDepots = json_decode(file_get_contents('./depots.json'), true);

// List of depots
$depots = [];
foreach ($jsonDepots as $depot) {
    $depots[] = Address::fromArray($depot);
}

$parameters = RouteParameters::fromArray([
    'route_name' => 'Multiple Depots Seprate Section '.date('Y-m-d H:i'),
    'algorithm_type' => AlgorithmType::CVRP_TW_MD,
    'distance_unit' => DistanceUnit::MILES,
    'device_type' => DeviceType::WEB,
    'optimize' => OptimizationType::TIME,
    'metric' => Metric::GEODESIC,
    'route_max_duration' => 86400 * 2,
    'travel_mode' => TravelMode::DRIVING,
    'vehicle_capacity' => 50,
    'vehicle_max_distance_mi' => 10000,
    'parts' => 50,
]);

$optimizationParams = new OptimizationProblemParams();
$optimizationParams->setAddresses($addresses);
$optimizationParams->setDepots($depots);
$optimizationParams->setParameters($parameters);

$problem = OptimizationProblem::optimize($optimizationParams);

Route4Me::simplePrint((array) $problem, true);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/optimization_problem.php?api_key=...


See the sample JSON response of this method.


Get an Optimization

Get a single optimization using the optimization_problem_id parameter.


PARAMETERS

Parameter Type Description
api_key string API key of the user
optimization_problem_id string Optimization Problem ID
<job id="GetOptimizationSingle">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of getting a single optimization problem.
      
      url="https://api.route4me.com/api.v4/optimization_problem.php"
      apikey="11111111111111111111111111111111"
      opi="07372F2CF3814EC6DFFAFE92E22771AA"
      
      url=url&"?api_key="&apikey
      url=url&"&optimization_problem_id="&opi
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetOptimization(string optimizationProblemID)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);
    
      OptimizationParameters optimizationParameters = new OptimizationParameters()
      {
        OptimizationProblemID = optimizationProblemID
      };

      // Run the query
      string errorString;
      DataObject dataObject = route4Me.GetOptimization(optimizationParameters, out errorString);

      Console.WriteLine("");

      if (dataObject != null)
      {
        Console.WriteLine("GetOptimization executed successfully");

        Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId);
        Console.WriteLine("State: {0}", dataObject.State);
      }
      else
      {
        Console.WriteLine("GetOptimization error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetOptimization(optimizationProblemID As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim optimizationParameters As New OptimizationParameters() With { _
                .OptimizationProblemID = optimizationProblemID _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As DataObject = route4Me.GetOptimization(optimizationParameters, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("GetOptimization executed successfully")

                Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId)
                Console.WriteLine("State: {0}", dataObject.State)
            Else
                Console.WriteLine("GetOptimization error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    optimization = route4me.optimization
    response = optimization.get_optimizations(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        optimizations = response.optimizations
        optimization_problem_id = optimizations[0].optimization_problem_id
        response = optimization.get_optimization(
            optimization_problem_id=optimization_problem_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            optimization_problem_id = response.optimization_problem_id
            print '\tOptimization ID: {}'.format(optimization_problem_id)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.optimizations;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.DataObject;
import com.route4me.sdk.services.routing.OptimizationParameters;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class GetOptimization {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager manager = new RoutingManager(apiKey);
        try {
            List<DataObject> data = manager.getOptimizations(10, 5);
            String optimizationProblemID = data.get(0).getOptimizationProblemId();
            DataObject optimization = manager.getOptimization(new OptimizationParameters().setProblemId(optimizationProblemID));
            System.out.println(optimization);
        } catch (APIException e) {
            // handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\OptimizationProblem;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random optimization problem ID
$optimization = new OptimizationProblem();

$optimizationProblemId = $optimization->getRandomOptimizationId(0, 10);

assert(!is_null($optimizationProblemId), "Can't retrieve a random optimization problem ID");

// Get an optimization problem
$optimizationProblemParams = array(
    "optimization_problem_id"  =>  $optimizationProblemId
);

$optimizationProblem = $optimization->get($optimizationProblemParams);

foreach ((array)$optimizationProblem as $probParts) {
    Route4Me::simplePrint((array)$probParts);
}
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}

  optimization, err = service.GetOptimization(&OptimizationParameters{ProblemID: optimizations[0].ProblemID})
  if err != nil {
    // handle errors
    return
  }
  // do something with optimization
}
package GetOptimization;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::DataTypes::OptimizationState;

sub GetOptimization {
    my ($self, $optimizationProblemID) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $optimizationParameters = OptimizationParameters->new(
        optimization_problem_id => $optimizationProblemID
    );

    my $errorString;
    my $dataObject = $route4Me->getOptimization($optimizationParameters, \$errorString);

    if ($dataObject) {
        print "GetOptimization executed successfully\n";
        printf "Optimization Problem ID:  %s\n", $dataObject->optimization_problem_id;
        printf "State: %s\n", OptimizationState->get_optimization_state($dataObject->state);

    } else {
        printf "GetOptimization error: %s\n", $errorString;
    }
}
1;
@ECHO OFF

SET url=https://api.route4me.com
SET apikey=11111111111111111111111111111111
SET optprobid=07372F2CF3814EC6DFFAFE92E22771AA

:: The example demonstrates the process of getting a single optimization problem.

ECHO ON
curl -o file1.txt -g -X GET -k "%URL%/api.v4/optimization_problem.php?api_key=%apikey%&optimization_problem_id=%optprobid%" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/optimization_problem.php
apikey=11111111111111111111111111111111
optprobid=07372F2CF3814EC6DFFAFE92E22771AA

# The example demonstrates the process of getting a single optimization problem.

curl -o file1.txt -g -X GET -k "$url?api_key=$apikey&optimization_problem_id=$optprobid" 

echo "Finished..."

sleep 15
unit GetOptimizationUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetOptimization = class(TBaseExample)
  public
    procedure Execute(OptimizationProblemId: String);
  end;

implementation

uses
  OptimizationParametersUnit, DataObjectUnit, EnumsUnit;

procedure TGetOptimization.Execute(OptimizationProblemId: String);
var
  Parameters: TOptimizationParameters;
  DataObject: TDataObject;
  ErrorString: String;
begin
  Parameters := TOptimizationParameters.Create;
  try
    Parameters.OptimizationProblemID := OptimizationProblemId;

    DataObject := Route4MeManager.Optimization.Get(Parameters, ErrorString);
    try
      WriteLn('');

      if (DataObject <> nil) then
      begin
          WriteLn('GetOptimization executed successfully');
          WriteLn(Format('Optimization Problem ID: %s',
            [DataObject.OptimizationProblemId]));
          WriteLn(Format('State: %s',
            [TOptimizationDescription[TOptimizationState(DataObject.State)]]));
      end
      else
        WriteLn(Format('GetOptimization error: "%s"', [ErrorString]));
    finally
      FreeAndNil(DataObject);
    end;
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *id = "2FB5F91365317758045DB9F19DF5A522";

    int ret = route.get_optimization(id);
    if (ret == 0)
       cout << "Optimization: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
       cout << "Optimization not found: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
"use strict"

const path = require("path")
const debug = require("debug")("route4me-node:examples")

require("../init-examples-suite")
const helper  = require("./../../test/helper")

helper.describeIntegration(helper.toSuiteName(__filename), function T() {
  this.timeout(5000)
  this.slow(3000)
  it(path.basename(__filename), (done) => {
    // const Route4Me = require("route4me-node")

    const apiKey   = "11111111111111111111111111111111"
    const route4me = new Route4Me(apiKey)
    const optimizationId = "07372F2CF3814EC6DFFAFE92E22771AA"
    route4me.Optimizations.get(optimizationId, (err, optimization) => {
      debug("error  ", err)
      debug("result ", optimization)

      // Expectations about result
      expect(err).is.null

      expect(optimization).has.property("optimization_problem_id", "07372F2CF3814EC6DFFAFE92E22771AA")

      // TODO: remove `done` call from examples
      done()
    })
  })
})
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char opt_id[] = "c46648541ca5d716a31ffae6f405a37d";
    init(key, 1);

    if (!get_optimization(opt_id))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}


HTTP Request

GET
/api.v4/optimization_problem.php?api_key=...&optimization_problem_id=...


See the sample JSON response of this method.


Get Optimizations

a) Get all optimizations belonging to a user.


PARAMETERS

Parameter Type Description
api_key string API key of the user
state string A comma-separated list of states.
limit integer The number of records to return.
offset integer Search starting position
<job id="GetOptimizations">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of getting a limited number of optimization problems.
      
      url="https://api.route4me.com/api.v4/optimization_problem.php"
      state="1,2,3"
      apikey="11111111111111111111111111111111"
      limit="10"
      offset="0"
      
      url=url&"?state="&state
      url=url&"&api_key="&apikey
      url=url&"&limit="&limit
      url=url&"&offset="&offset
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        public void GetOptimizations()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            RouteParametersQuery queryParameters = new RouteParametersQuery()
            {
                Limit = 10,
                Offset = 5
            };

            // Run the query
            string errorString;
            DataObject[] dataObjects = route4Me.GetOptimizations(queryParameters, out errorString);

            Console.WriteLine("");

            if (dataObjects != null)
            {
                Console.WriteLine("GetOptimizations executed successfully, {0} optimizations returned", dataObjects.Length);
                Console.WriteLine("");

                dataObjects.ForEach(optimization =>
                {
                    Console.WriteLine("Optimization Problem ID: {0}", optimization.OptimizationProblemId);
                    Console.WriteLine("");
                });
            }
            else
            {
                Console.WriteLine("GetOptimizations error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetOptimizations()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim queryParameters As New RouteParametersQuery() With { _
                .Limit = 10, _
                .Offset = 5 _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObjects As DataObject() = route4Me.GetOptimizations(queryParameters, errorString)

            Console.WriteLine("")

            If dataObjects IsNot Nothing Then
                Console.WriteLine("GetOptimizations executed successfully, {0} optimizations returned", dataObjects.Length)
                Console.WriteLine("")

                For Each optimization As DataObject In dataObjects
                    Console.WriteLine("Optimization Problem ID: {0}", optimization.OptimizationProblemId)
                    Console.WriteLine("")
                Next

            Else
                Console.WriteLine("GetOptimizations error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    optimization = route4me.optimization
    response = optimization.get_optimizations(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print response
        for i, optimization in enumerate(response.optimizations):
            optimization_problem_id = optimization.optimization_problem_id
            print 'Optimization #{}'.format(i + 1)
            print '\tOptimization ID: {}'.format(optimization_problem_id)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.optimizations;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.DataObject;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class GetOptimizations {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager manager = new RoutingManager(apiKey);
        try {
            List<DataObject> data = manager.getOptimizations(10, 5);
            for (DataObject optimization : data) {
                System.out.println(optimization);
            }
        } catch (APIException e) {
            // handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$routeParameters = array(
    'limit'  =>  5,
    'offset' =>  0
);

$optimizationProblem = new OptimizationProblem();

$optimizations = $optimizationProblem->get($routeParameters);

foreach ($optimizations as $optimization) {
    echo "Optimization problem ID -> ".$optimization->optimization_problem_id."<br>";
}
package GetOptimizations;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::QueryTypes::RouteParametersQuery;

sub GetOptimizations {
    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $queryParameters = RouteParametersQuery->new(
        limit  => 10,
        offset => 5
    );

    my $errorString;

    my $dataObjects = $route4Me->getOptimizations($queryParameters, $errorString);

    print "\n";

    if ($dataObjects) {
        printf "GetOptimizations executed successfully, %s optimizations returned\n\n", scalar @{$dataObjects->optimizations};

        foreach my $dataObject (@{$dataObjects->optimizations})
        {
            printf "Optimization Problem ID:  %s\n", $dataObject->optimization_problem_id;
        }

    } else {
        printf "GetOptimizations error: %s\n", $errorString;
    }
}
1;
@ECHO OFF

SET url=https://api.route4me.com
SET apikey=11111111111111111111111111111111

:: The example demonstrates the process of getting a limited number of optimization problems.

ECHO ON

curl -o file1.txt -g -X GET -k "%URL%/api.v4/optimization_problem.php?state=1,2,3&api_key=%apikey%&limit=10&offset=0" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/optimization_problem.php
apikey=11111111111111111111111111111111
state=1,2,3
limit=10
offset=0

# The example demonstrates the process of getting a limited number of optimization problems.

curl -o file1.txt -g -X GET -k "$url?state=$state&api_key=$apikey&limit=$limit&offset=$offset" 

echo "Finished..."

sleep 15
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}

  optimizations, err := service.GetOptimizations(&RouteQuery{Limit: 5})
  if err != nil {
    // handle errors
    return
  }
  // do something with optimizations
}
unit GetOptimizationsUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetOptimizations = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses RouteParametersQueryUnit, DataObjectUnit;

procedure TGetOptimizations.Execute;
var
  Parameters: TRouteParametersQuery;
  DataObjects: TArray<TDataObject>;
  DataObject: TDataObject;
  ErrorString: String;
  i: integer;
begin
  Parameters := TRouteParametersQuery.Create;
  try
    Parameters.Limit := 10;
    Parameters.Offset := 5;

    DataObjects := Route4MeManager.Optimization.Get(Parameters, ErrorString);
    try
      WriteLn('');

      if Length(DataObjects) > 0 then
      begin
          WriteLn(Format(
            'GetOptimizations executed successfully, %d optimizations returned',
            [Length(DataObjects)]));
          WriteLn('');

          for DataObject in DataObjects do
            WriteLn(Format('Optimization Problem ID: %s', [DataObject.OptimizationProblemId]));
      end
      else
        WriteLn(Format('GetOptimizations error: "%s"', [ErrorString]));
    finally
      for i := Length(DataObjects) - 1 downto 0 do
        FreeAndNil(DataObjects[i]);
    end;
  finally
    FreeAndNil(Parameters);
  end;
end;
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    int ret = route.get_optimizations("1,2,3", 10, 5);
    if (ret == 0)
       cout << "Optimizations: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
       cout << "Optimizations not found: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 1);

    if (!get_optimizations("states",0,10))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}


HTTP Request

GET
/api.v4/optimization_problem.php?api_key=...&limit=...&offset=...



See the sample JSON response of this method.


b) Get the optimizations scheduled for the specified date range.


PARAMETERS

Parameter Type Description
api_key string API key of the user
start_date string Start date (e.g. 2019-09-15)
end_date string Start date (e.g. 2019-09-20)
<job id="View Optimizations From Date Range">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example refers to the process of getting the optimizations scheduled for the specified date range.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/optimization_problem.php"
			apikey="11111111111111111111111111111111"
			start_date="2019-09-15"
			end_date="2019-09-20"
			
			url=url&"?api_key="&apikey
			url=url&"&strat_date="&start_date
			url=url&"&limit"&end_date
			
			Set r4m=New Route4Me
			r4m.OutputFile="get_optimizations_from_date_range_RESPONSE.json"
			
			r4m.HttpGetRequest url
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/optimization_problem.php
SET apikey=11111111111111111111111111111111
SET "start_date=2019-10-16"
SET "end_date=2019-10-20"

:: The example refers to the process of getting the optimizations scheduled for the specified date range.

ECHO ON
curl -o get_optimizations_from_date_range_RESPONSE.json -g -X GET -k "%url%?api_key=%apikey%&start_date=%start_date%&start_date=%start_date%" 

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/optimization_problem.php
apikey=11111111111111111111111111111111
start_date="2019-10-15"
end_date="2019-10-20"

 # The example refers to the process of getting the optimizations scheduled for the specified date range.

curl -o file1.txt -g -X GET -k "$url?state=$state&api_key=$apikey&start_date=$start_date&end_date=$end_date" 

echo "Finished..."

sleep 15
public void GetOptimizationsFromDateRangeTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	OptimizationParameters queryParameters = new OptimizationParameters()
	{
		StartDate = "2019-09-15",
		EndDate = "2019-09-20"
	};

	// Run the query
	string errorString;
	DataObject[] dataObjects = route4Me.GetOptimizations(queryParameters, out errorString);

	Assert.IsInstanceOfType(dataObjects, typeof(DataObject[]), "GetOptimizationsFromDateRangeTest failed... " + errorString);
}
Public Sub GetOptimizationsFromDateRangeTest()
	Dim route4Me As New Route4MeManager(c_ApiKey)

	Dim queryParameters As New RouteParametersQuery() With {
		.StartDate = "2019-09-15",
		.EndtDate = "2019-09-20"
	}

	' Run the query
	Dim errorString As String = ""
	Dim dataObjects As DataObject() = route4Me.GetOptimizations(queryParameters, errorString)

	Assert.IsInstanceOfType(dataObjects, GetType(DataObject()), "GetOptimizationsFromDateRangeTest failed... " & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;
$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';
// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');
$optimizationParameters = [
    'start_date' => '2019-10-15',
    'end_date' => '2019-10-20'
];
$optimizationProblem = new OptimizationProblem();
$optimizations = $optimizationProblem->get($optimizationParameters);
foreach ($optimizations as $optimization) {
    echo 'Optimization problem ID -> '.$optimization->optimization_problem_id.'<br>';
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/optimization_problem.php?api_key=...&start_date=...&end_date=...


See the sample JSON response of this method.


Remove an Optimization

Removes an existing optimization belonging to a user.


PARAMETERS

Parameter Type Description
api_key string API key of the user
optimization_problem_id string Optimization Problem ID
<job id="DeleteOptimization">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example demonstrates the removal of existing optimization problems.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/optimization_problem.php"
      apikey="11111111111111111111111111111111"
      redirect=0
      
      url=url&"?api_key="&apikey
      url=url&"&redirect="&redirect

      jFile="delete_optimization_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpDeleteRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/optimization_problem.php
SET apikey=11111111111111111111111111111111
SET optprobid=DE62B03510AB5A6A876093F30F6C7BF5
SET redirect=0

ECHO ON

:: The example demonstrates the removal of existing optimization problems.

curl -o file1.txt -g -k -X DELETE -d "@delete_optimization_data.json" "%url%?api_key=%apikey%&redirect=%redirect%" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/optimization_problem.php
apikey=11111111111111111111111111111111
optprobid=DE62B03510AB5A6A876093F30F6C7BF5
redirect=0

# The example demonstrates the removal of existing optimization problems.

curl -o file1.txt -g -k -X DELETE -d "@delete_optimization_data.json" "$url?api_key=$apikey&redirect=$redirect" 

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void RemoveOptimization(string optimizationProblemID)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Run the query
      string errorString;
      bool removed = route4Me.RemoveOptimization(optimizationProblemID, out errorString);

      Console.WriteLine("");

      if (removed)
      {
        Console.WriteLine("RemoveOptimization executed successfully");

        Console.WriteLine("Optimization Problem ID: {0}", optimizationProblemID);
      }
      else
      {
        Console.WriteLine("RemoveOptimization error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Remove Optimization
        ''' </summary>
        ''' <param name="optimizationProblemIDs"> Optimization Problem IDs </param>
        Public Sub RemoveOptimization(optimizationProblemIDs As String())
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim deleted As Boolean = route4Me.RemoveOptimization(optimizationProblemIDs, errorString)

            Console.WriteLine("")

            If deleted Then
                Console.WriteLine("RemoveOptimization executed successfully")

                Console.WriteLine("Optimization Problem ID: {0}", optimizationProblemIDs)
            Else
                Console.WriteLine("RemoveOptimization error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import (
    ALGORITHM_TYPE,
    OPTIMIZE,
    DISTANCE_UNIT,
    DEVICE_TYPE,
    TRAVEL_MODE
)

KEY = "11111111111111111111111111111111"

# codebeat:disable[LOC, ABC]

def main():
    route4me = Route4Me(KEY)
    optimization = route4me.optimization
    address = route4me.address
    optimization.algorithm_type(ALGORITHM_TYPE.TSP)
    optimization.share_route(0)
    optimization.store_route(0)
    optimization.route_time(0)
    optimization.route_max_duration(86400)
    optimization.vehicle_capacity(1)
    optimization.vehicle_max_distance_mi(10000)
    optimization.route_name('Optimization Example')
    optimization.optimize(OPTIMIZE.DISTANCE)
    optimization.distance_unit(DISTANCE_UNIT.MI)
    optimization.device_type(DEVICE_TYPE.WEB)
    optimization.travel_mode(TRAVEL_MODE.DRIVING)
    address.add_address(
        address='754 5th Ave New York, NY 10019',
        lat=40.7636197,
        lng=-73.9744388,
        alias='Bergdorf Goodman',
        is_depot=1,
        time=0
    )
    address.add_address(
        address='717 5th Ave New York, NY 10022',
        lat=40.7669692,
        lng=-73.9693864,
        alias='Giorgio Armani',
        time=0
    )
    address.add_address(
        address='888 Madison Ave New York, NY 10014',
        lat=40.7715154,
        lng=-73.9669241,
        alias='Ralph Lauren Women\'s and Home',
        time=0
    )
    address.add_address(
        address='1011 Madison Ave New York, NY 10075',
        lat=40.7772129,
        lng=-73.9669,
        alias='Yigal Azrou\u00ebl',
        time=0
    )
    address.add_address(
        address='440 Columbus Ave New York, NY 10024',
        lat=40.7808364,
        lng=-73.9732729,
        alias='Frank Stella Clothier',
        time=0
    )
    address.add_address(
        address='324 Columbus Ave #1 New York, NY 10023',
        lat=40.7803123,
        lng=-73.9793079,
        alias='Liana',
        time=0
    )
    address.add_address(
        address='110 W End Ave New York, NY 10023',
        lat=40.7753077,
        lng=-73.9861529,
        alias='Toga Bike Shop',
        time=0
    )
    address.add_address(
        address='555 W 57th St New York, NY 10019',
        lat=40.7718005,
        lng=-73.9897716,
        alias='BMW of Manhattan',
        time=0
    )
    address.add_address(
        address='57 W 57th St New York, NY 10019',
        lat=40.7558695,
        lng=-73.9862019,
        alias='Verizon Wireless',
        time=0
    )

    response = route4me.run_optimization()
    optimization_id = response.addresses[0].optimization_problem_id
    print 'Deleting Optimization Problem: {}'.format(optimization_id)
    response = route4me.optimization.delete_optimization(
        optimization_problem_ids=[optimization_id, ])
    print (response)
# codebeat:enable[LOC, ABC]

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}

  err = service.DeleteOptimization({optimizationId})
  if err != nil {
    // handle errors
    return
  }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\OptimizationProblem;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the removal of existing optimization problems.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random optimization problem ID
$optimization = new OptimizationProblem();

$optimizationProblemId = $optimization->getRandomOptimizationId(0, 10);

assert(!is_null($optimizationProblemId), "Can't retrieve a random optimization problem ID");

// Remove an optimization
$params = array (
    "optimization_problem_ids"  => array(
        "0" => $optimizationProblemId
    ),
    "redirect"  => 0
);

$result = $optimization->removeOptimization($params);

var_dump($result);
unit RemoveOptimizationUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TRemoveOptimization = class(TBaseExample)
  public
    procedure Execute(OptimizationProblemId: String);
  end;

implementation

procedure TRemoveOptimization.Execute(OptimizationProblemId: String);

var
  ErrorString: String;
  Removed: boolean;
begin
  Removed := Route4MeManager.Optimization.Remove(OptimizationProblemID, ErrorString);

  WriteLn('');

  if (Removed) then
  begin
    WriteLn('RemoveOptimization executed successfully');
    WriteLn(Format('Optimization Problem ID: %s', [OptimizationProblemID]));
  end
  else
    WriteLn(Format('RemoveOptimization error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    ifstream inf("delete_optimization_data.json");
    if(!inf.is_open()) {
      cout << "Can't find a file with route data" << endl;
      return -1;
    }
    Json::Value input_data;
    inf >> input_data;
    int ret = route.remove_optimization(input_data);

    if (ret == 0)
      cout << "Optimization removed: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
      cout << "Optimization not removed: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char file_name[] = "delete_optimization_data.json";
    char* data = NULL;

    if (0 != deserialize(file_name, &data))
    {
        printf("File delete_optimization_data.json not found!\n");
        return -1;
    }

    init(key, 1);

    if (!remove_optimization(data))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}


HTTP Request

DELETE
/api.v4/optimization_problem.php?api_key=...&optimization_problem_ids=[...]

You can expect this API response:

{
  "status":true,
  "removed":1
}

Insert an Address into an Optimization

Insert an address into an optimization, resulting in the recalculation of optimal routes.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
optimization_problem_id string Optimization Problem ID GET
reoptimize integer If 1, reoptimize. If 0, don’t. GET
addresses array A valid JSON array of Address objects. See the Address JSON Schema as a guide. POST
<job id="AddAddressToOptimization">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/optimization_problem.php"
      apikey="11111111111111111111111111111111"
      optprobid="07372F2CF3814EC6DFFAFE92E22771AA"
      
      url=url&"?api_key="&apikey&"&optimization_problem_id="&optprobid&"&reoptimize=1"
      
      jFile="address_for_optimization.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void AddDestinationToOptimization(string optimizationProblemID, bool andReOptimize)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Prepare the address that we are going to add to an existing route optimization
      Address[] addresses = new Address[]
      {
        new Address() { AddressString = "717 5th Ave New York, NY 10021",
                        Alias         = "Giorgio Armani",
                        Latitude      = 40.7669692,
                        Longitude     = -73.9693864,
                        Time          = 0
        }
      };

      // Optionally change any route parameters, such as maximum route duration, maximum cubic constraints, etc.
      OptimizationParameters optimizationParameters = new OptimizationParameters()
      {
        OptimizationProblemID = optimizationProblemID,
        Addresses = addresses,
        ReOptimize = andReOptimize
      };

      // Execute the optimization to re-optimize and rebalance all the routes in this optimization
      string errorString;
      DataObject dataObject = route4Me.UpdateOptimization(optimizationParameters, out errorString);

      Console.WriteLine("");

      if (dataObject != null)
      {
        Console.WriteLine("AddDestinationToOptimization executed successfully");

        Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId);
        Console.WriteLine("State: {0}", dataObject.State);
      }
      else
      {
        Console.WriteLine("AddDestinationToOptimization error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub AddDestinationToOptimization(optimizationProblemID As String, andReOptimize As Boolean)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Prepare the address that we are going to add to an existing route optimization
            Dim addresses As Address() = New Address() {New Address() With { _
                .AddressString = "717 5th Ave New York, NY 10021", _
                .[Alias] = "Giorgio Armani", _
                .Latitude = 40.7669692, _
                .Longitude = -73.9693864, _
                .Time = 0 _
            }}

            ' Optionally change any route parameters, such as maximum route duration, maximum cubic constraints, etc.
            Dim optimizationParameters As New OptimizationParameters() With { _
                .OptimizationProblemID = optimizationProblemID, _
                .Addresses = addresses, _
                .ReOptimize = andReOptimize _
            }

            ' Execute the optimization to re-optimize and rebalance all the routes in this optimization
            Dim errorString As String = ""
            Dim dataObject As DataObject = route4Me.UpdateOptimization(optimizationParameters, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("AddDestinationToOptimization executed successfully")

                Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId)
                Console.WriteLine("State: {0}", dataObject.State)
            Else
                Console.WriteLine("AddDestinationToOptimization error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
#!/usr/bin/python

from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    optimization = route4me.optimization
    response = optimization.get_optimizations(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        optimization_problem_id = response.optimizations[0].optimization_problem_id
        response = optimization.get_optimization(optimization_problem_id=optimization_problem_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Addresses to include'
            for i, address in enumerate(response.addresses):
                print 'Address #{}'.format(i+1)
                print '\tAddress: {}'.format(address.address)
                print '\tLatitude: {}'.format(address.lat)
                print '\tLongitude: {}'.format(address.lng)
                print '\tAlias: {}'.format(address.alias)
            addresses = [{'address': '555 W 57th St New York, NY 10019',
                          'lat': 40.7718005,
                          'lng': -73.9897716,
                          'alias': 'BMW of Manhattan',
                          'time': 0
                          },
                         {'address': '57 W 57th St New York, NY 10019',
                          'lat': 40.7558695,
                          'lng': -73.9862019,
                          'alias': 'Verizon Wireless',
                          'time': 0
                          }]
            print 'Addresses to include'
            for i, address in enumerate(addresses):
                print 'Address #{}'.format(i+1)
                print '\tAddress: {}'.format(address.get('address'))
                print '\tLatitude: {}'.format(address.get('lat'))
                print '\tLongitude: {}'.format(address.get('lng'))
                print '\tAlias: {}'.format(address.get('alias'))
            response = optimization.update_optimization(optimization_problem_id=optimization_problem_id,
                                                        addresses=addresses,
                                                        reoptimize=True)
            if hasattr(response, 'errors'):
                print '. '.join(response.errors)
            else:
                print 'Current Addresses'
                for i, address in enumerate(response.addresses):
                    print 'Address #{}'.format(i+1)
                    print '\tAddress: {}'.format(address.address)
                    print '\tLatitude: {}'.format(address.lat)
                    print '\tLongitude: {}'.format(address.lng)
                    print '\tAlias: {}'.format(address.alias)

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\OptimizationProblem;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route ID");

// Get random address ID from selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($routeId);
$optimization_problem_id = $addressRand['optimization_problem_id'];

assert(!is_null($optimization_problem_id), "Can't retrieve random address");

// Add an address to the optimization
$addresses = array();

$address1 = (array)Address::fromArray(array(
    'address'  =>  '717 5th Ave New York, NY 10021',
    'alias'    =>  'Giorgio Armani',
    'lat'      =>  40.7669692,
    'lng'      =>  73.9693864,
    'time'     =>  0
));

$addresses[0] = $address1;

$OptimizationParameters = (array)OptimizationProblem::fromArray(array(
    "optimization_problem_id"  => $optimization_problem_id,
    "addresses"                => $addresses,
    "reoptimize"               => 1,
));

$optimizationproblem = new OptimizationProblem();

$result = $optimizationproblem->update($OptimizationParameters);

Route4Me::simplePrint($result);
package AddDestinationToOptimization;
use strict;
use warnings FATAL => 'all';

use Route4MeSDK::DataTypes::OptimizationState;

sub AddDestinationToOptimization {

    my ($self, $optimizationProblemID, $andReOptimize) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $addresses = [
        Address->new( address => "717 5th Ave New York, NY 10021",
            alias             => "Giorgio Armani",
            lat               => 40.7669692,
            lng               => -73.9693864,
            time              => 0
        )
    ];

    my $optimizationParameters = OptimizationParameters->new({
            optimization_problem_id => $optimizationProblemID,
            reoptimize => $andReOptimize,
            addresses  => $addresses,
    });

    my $errorString = "";

    my $dataObject = $route4Me->updateOptimization( $optimizationParameters, \$errorString );

    print "\n";

    if ($dataObject) {
        print "AddDestinationToOptimization executed successfully\n";
        printf "Optimization Problem ID: %s\n", $optimizationProblemID;
        printf "State: %s\n", OptimizationState->get_optimization_state($dataObject->state);
    } else {
        printf "AddDestinationToOptimization error: %s\n", $errorString;
    }
}

1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/optimization_problem.php
SET apikey=11111111111111111111111111111111
SET optprobid=07372F2CF3814EC6DFFAFE92E22771AA

ECHO ON

:: You should insert real test data and use your API key for accurate testing.

curl -o file1.txt -g -X PUT -k -d "@address_for_reoptimization.json" "%url%?api_key=%apikey%&optimization_problem_id=%optprobid%&reoptimize=1" 

timeout /t 30
#!/bin/bash

url="https://api.route4me.com/api.v4/optimization_problem.php"
apikey=11111111111111111111111111111111
optprobid=07372F2CF3814EC6DFFAFE92E22771AA
opt=1

# Warning: The data in the JSON file isn't real. You should use real test data for accurate testing.

curl -o file1.txt -g -X PUT -k -d "@address_for_optimization.json" "$url?api_key=$apikey&optimization_problem_id=$optprobid&reoptimize=$opt" 

echo "Finished..."

sleep 15
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}

  addresses := []routing.Address{
    // address to be added
    routing.Address{
      AddressString: "717 5th Ave New York, NY 10021",
      Alias:         "Giorgio Armani",
      Latitude:      40.7669692,
      Longitude:     -73.9693864,
      Time:          0,
    },
  }

  updated, err := service.UpdateOptimization(&OptimizationParameters{ProblemID: "problem_id", Addresses: addresses, Reoptimize: true})
  if err != nil {
    // handle errors
    return
  }
  // do something with the updated optimization
}
unit AddDestinationToOptimizationUnit;

interface

uses SysUtils, BaseExampleUnit, DataObjectUnit;

type
  TAddDestinationToOptimization = class(TBaseExample)
  public
    function Execute(OptimizationId: String;
      AndReOptimize: boolean): TDataObject;
  end;

implementation

uses AddressUnit, OptimizationParametersUnit, EnumsUnit;

function TAddDestinationToOptimization.Execute(OptimizationId: String;

  AndReOptimize: boolean): TDataObject;
var
  Address: TAddress;
  Parameters: TOptimizationParameters;
  ErrorString: String;
begin
  Address := TAddress.Create;
  Address.AddressString := '717 5th Ave New York, NY 10021';
  Address.Alias := 'Giorgio Armani';
  Address.Latitude := 40.7669692;
  Address.Longitude := -73.9693864;
  Address.Time := 0;

  Parameters := TOptimizationParameters.Create;
  try
    Parameters.OptimizationProblemID := OptimizationId;
    Parameters.AddAddress(Address);
    Parameters.ReOptimize := AndReOptimize;

    Result := Route4MeManager.Optimization.Update(Parameters, ErrorString);

    WriteLn('');

    if (Result <> nil) then
    begin
      WriteLn('AddDestinationToOptimization executed successfully');
      WriteLn(Format('Optimization Problem ID: %s', [Result.OptimizationProblemId]));
      WriteLn(Format('State: %s',
        [TOptimizationDescription[TOptimizationState(Result.State)]]));
    end
    else
      WriteLn(Format('AddDestinationToOptimization error: %s', [ErrorString]));
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *opt_id = "07372F2CF3814EC6DFFAFE92E22771AA";

    ifstream inf("address_for_optimization.json");
    if(!inf.is_open()) {
      cout << "Can't find a file with address data" << endl;
      return -1;
    }
    Json::Value input_data;
    inf >> input_data;

    if (route.add_address_to_optimization(input_data, opt_id) == 0) {
       cout << "Route updated:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
       cout << "Error updating route: " << route.get_err_code() << ": " << route.get_err_msg() << endl;       
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char opt_id[] = "07372F2CF3814EC6DFFAFE92E22771AA";
    char file_name[] = "address_for_optimization.json";
    int reoptimize = 1;
    char* data = NULL;

    if (0 != deserialize(file_name, &data))
    {
        printf("File address_for_optimization.json not found!\n");
        return -1;
    }

    init(key, 1);

    if (!add_address_to_optimization(opt_id, data, reoptimize))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}



HTTP Request

PUT
/api.v4/optimization_problem.php?api_key=...&optimization_problem_id=...&reoptimize=...

You can expect this API response:

{
    "optimization_problem_id": "07372F2CF3814EC6DFFAFE92E22771AA",
    "user_errors": [],
    "optimization_errors": [],
    "state": 4,
    "created_timestamp": 1460240759,
    "scheduled_for": 1460260800,
    "optimization_completed_timestamp": 1475314595,
    "parameters": {
        "is_upload": false,
        "rt": true,
        "route_name": "Sunday 10th of April 2016 01:20 AM (+03:00)",
        "route_date": 1460246400,
        "route_time": 14400,
        "shared_publicly": false,
        "disable_optimization": false,
        "optimize": "Time",
        "lock_last": false,
        "vehicle_capacity": null,
        "vehicle_max_cargo_weight": null,
        "vehicle_max_cargo_volume": null,
        "vehicle_max_distance_mi": null,
        "subtour_max_revenue": null,
        "distance_unit": "mi",
        "travel_mode": "Driving",
        "avoid": "",
        "avoidance_zones": [],
        "vehicle_id": null,
        "driver_id": null,
        "dev_lat": null,
        "dev_lng": null,
        "route_max_duration": 36000,
        "route_email": "[email protected]",
        "store_route": true,
        "metric": 4,
        "algorithm_type": 3,
        "member_id": 1,
        "ip": 3584951549,
        "dm": 1,
        "dirm": 5,
        "parts": 99,
        "parts_min": 1,
        "device_id": null,
        "device_type": "web",
        "first_drive_then_wait_between_stops": false,
        "has_trailer": false,
        "trailer_weight_t": 0,
        "limited_weight_t": 36,
        "weight_per_axle_t": 0,
        "truck_height": 0,
        "truck_width": 0,
        "truck_length": 0,
        "truck_hazardous_goods": "",
        "optimization_quality": 2,
        "override_addresses": {},
        "max_tour_size": null,
        "min_tour_size": 0,
        "uturn": 1,
        "leftturn": 1,
        "rightturn": 1
    },
    "sent_to_background": false,
    "addresses": [
        {
            "route_destination_id": 154456307,
            "alias": "",
            "member_id": 1,
            "address": "US",
            "is_depot": false,
            "timeframe_violation_state": null,
            "timeframe_violation_time": 0,
            "timeframe_violation_rate": 0,
            "lat": 38.89037,
            "lng": -77.03196,
            "curbside_lat": 38.89037,
            "curbside_lng": -77.03196,
            "priority": null,
            "route_id": "1C9C05D3854FC30E82C942DC057B84DC",
            "original_route_id": "",
            "optimization_problem_id": "07372F2CF3814EC6DFFAFE92E22771AA",
            "sequence_no": 1,
            "geocoded": false,
            "preferred_geocoding": null,
            "failed_geocoding": false,
            "geocodings": [],
            "contact_id": 0,
            "order_id": null,
            "address_stop_type": "DELIVERY",
            "is_visited": false,
            "timestamp_last_visited": null,
            "visited_lat": null,
            "visited_lng": null,
            "is_departed": false,
            "departed_lat": null,
            "departed_lng": null,
            "timestamp_last_departed": null,
            "group": null,
            "customer_po": null,
            "invoice_no": null,
            "reference_no": null,
            "order_no": null,
            "weight": 0,
            "cost": 0,
            "revenue": 0,
            "cube": 0,
            "pieces": 0,
            "first_name": null,
            "last_name": null,
            "email": null,
            "phone": null,
            "destination_note_count": 0,
            "drive_time_to_next_destination": null,
            "abnormal_traffic_time_to_next_destination": null,
            "uncongested_time_to_next_destination": null,
            "traffic_time_to_next_destination": null,
            "distance_to_next_destination": null,
            "channel_name": "114678d00de3bf082ccf8d448427da0c",
            "generated_time_window_start": null,
            "generated_time_window_end": null,
            "time_window_start": null,
            "time_window_end": null,
            "time_window_start_2": null,
            "time_window_end_2": null,
            "geofence_detected_visited_timestamp": null,
            "geofence_detected_departed_timestamp": null,
            "geofence_detected_service_time": null,
            "geofence_detected_visited_lat": null,
            "geofence_detected_visited_lng": null,
            "geofence_detected_departed_lat": null,
            "geofence_detected_departed_lng": null,
            "time": 0,
            "tracking_number": "E1XVXL7R",
            "custom_fields": {
                "timeframe_violation_rate": "0",
                "notes": "",
                "client name": "Veronica  Hill",
                "address line 1": "5161 San Felipe #390",
                "city\/town": "Houston",
                "state\/province\/region": "TX",
                "zip\/postal code": "77056",
                "demand": "",
                "demand2": "",
                "demand3": "",
                "time of service": "5",
                "opening time 1": "",
                "closing time 1": "",
                "opening time 2": "",
                "closing time 2": "",
                "required skills": ""
            },
            "custom_fields_str_json": "{\"timeframe_violation_rate\":\"0\",\"notes\":\"\",\"client name\":\"Veronica  Hill\",\"address line 1\":\"5161 San Felipe #390\",\"city\\\/town\":\"Houston\",\"state\\\/province\\\/region\":\"TX\",\"zip\\\/postal code\":\"77056\",\"demand\":\"\",\"demand2\":\"\",\"demand3\":\"\",\"time of service\":\"5\",\"opening time 1\":\"\",\"closing time 1\":\"\",\"opening time 2\":\"\",\"closing time 2\":\"\",\"required skills\":\"\"}",
            "custom_fields_config": null,
            "custom_fields_config_str_json": "null",
            "notes": []
        }
    ],
    "routes": [
        {
            "route_id": "1C9C05D3854FC30E82C942DC057B84DC",
            "optimization_problem_id": "07372F2CF3814EC6DFFAFE92E22771AA",
            "user_route_rating": null,
            "member_id": 1,
            "member_email": "[email protected]",
            "member_first_name": "Administrator",
            "member_last_name": "Administrator",
            "channel_name": "e270dd0a5fa56bce2612fc56c37afabd",
            "vehicle_alias": "N\/A",
            "driver_alias": "N\/A",
            "trip_distance": 0,
            "is_unrouted": false,
            "route_cost": 0,
            "route_revenue": 0,
            "net_revenue_per_distance_unit": 0,
            "created_timestamp": 1475314596,
            "mpg": 10,
            "gas_price": 2,
            "route_duration_sec": null,
            "planned_total_route_duration": 0,
            "actual_travel_distance": 0,
            "actual_travel_time": 0,
            "actual_footsteps": 0,
            "working_time": 0,
            "driving_time": 0,
            "idling_time": 0,
            "paying_miles": 0,
            "geofence_polygon_type": "circle",
            "geofence_polygon_size": 200,
            "parameters": {
                "is_upload": false,
                "rt": true,
                "route_name": "Sunday 10th of April 2016 01:20 AM (+03:00)",
                "route_date": 1460246400,
                "route_time": 14400,
                "shared_publicly": false,
                "disable_optimization": false,
                "optimize": "Time",
                "lock_last": false,
                "vehicle_capacity": null,
                "vehicle_max_cargo_weight": null,
                "vehicle_max_cargo_volume": null,
                "vehicle_max_distance_mi": null,
                "subtour_max_revenue": null,
                "distance_unit": "mi",
                "travel_mode": "Driving",
                "avoid": "",
                "avoidance_zones": [],
                "vehicle_id": null,
                "driver_id": null,
                "dev_lat": null,
                "dev_lng": null,
                "route_max_duration": 36000,
                "route_email": null,
                "store_route": true,
                "metric": 4,
                "algorithm_type": 3,
                "member_id": 1,
                "ip": 3584951549,
                "dm": 1,
                "dirm": 5,
                "parts": 10,
                "parts_min": 1,
                "device_id": null,
                "device_type": "web",
                "first_drive_then_wait_between_stops": false,
                "has_trailer": false,
                "trailer_weight_t": 0,
                "limited_weight_t": 36,
                "weight_per_axle_t": 0,
                "truck_height": 0,
                "truck_width": 0,
                "truck_length": 0,
                "truck_hazardous_goods": "",
                "optimization_quality": 2,
                "override_addresses": {},
                "max_tour_size": null,
                "min_tour_size": 0,
                "uturn": 1,
                "leftturn": 1,
                "rightturn": 1
            },
            "addresses": [
                {
                    "route_destination_id": 154456307,
                    "alias": "",
                    "member_id": 1,
                    "address": "US",
                    "is_depot": false,
                    "timeframe_violation_state": null,
                    "timeframe_violation_time": 0,
                    "timeframe_violation_rate": 0,
                    "lat": 38.89037,
                    "lng": -77.03196,
                    "curbside_lat": 38.89037,
                    "curbside_lng": -77.03196,
                    "priority": null,
                    "route_id": "1C9C05D3854FC30E82C942DC057B84DC",
                    "original_route_id": "",
                    "optimization_problem_id": "07372F2CF3814EC6DFFAFE92E22771AA",
                    "sequence_no": 1,
                    "geocoded": false,
                    "preferred_geocoding": null,
                    "failed_geocoding": false,
                    "geocodings": [],
                    "contact_id": 0,
                    "order_id": null,
                    "address_stop_type": "DELIVERY",
                    "is_visited": false,
                    "timestamp_last_visited": null,
                    "visited_lat": null,
                    "visited_lng": null,
                    "is_departed": false,
                    "departed_lat": null,
                    "departed_lng": null,
                    "timestamp_last_departed": null,
                    "group": null,
                    "customer_po": null,
                    "invoice_no": null,
                    "reference_no": null,
                    "order_no": null,
                    "weight": 0,
                    "cost": 0,
                    "revenue": 0,
                    "cube": 0,
                    "pieces": 0,
                    "first_name": null,
                    "last_name": null,
                    "email": null,
                    "phone": null,
                    "destination_note_count": 0,
                    "drive_time_to_next_destination": null,
                    "abnormal_traffic_time_to_next_destination": null,
                    "uncongested_time_to_next_destination": null,
                    "traffic_time_to_next_destination": null,
                    "distance_to_next_destination": null,
                    "channel_name": "114678d00de3bf082ccf8d448427da0c",
                    "generated_time_window_start": null,
                    "generated_time_window_end": null,
                    "time_window_start": null,
                    "time_window_end": null,
                    "time_window_start_2": null,
                    "time_window_end_2": null,
                    "geofence_detected_visited_timestamp": null,
                    "geofence_detected_departed_timestamp": null,
                    "geofence_detected_service_time": null,
                    "geofence_detected_visited_lat": null,
                    "geofence_detected_visited_lng": null,
                    "geofence_detected_departed_lat": null,
                    "geofence_detected_departed_lng": null,
                    "time": 0,
                    "tracking_number": "E1XVXL7R",
                    "custom_fields": {
                        "timeframe_violation_rate": "0",
                        "notes": "",
                        "client name": "Veronica  Hill",
                        "address line 1": "5161 San Felipe #390",
                        "city\/town": "Houston",
                        "state\/province\/region": "TX",
                        "zip\/postal code": "77056",
                        "demand": "",
                        "demand2": "",
                        "demand3": "",
                        "time of service": "5",
                        "opening time 1": "",
                        "closing time 1": "",
                        "opening time 2": "",
                        "closing time 2": "",
                        "required skills": ""
                    },
                    "custom_fields_str_json": "{\"timeframe_violation_rate\":\"0\",\"notes\":\"\",\"client name\":\"Veronica  Hill\",\"address line 1\":\"5161 San Felipe #390\",\"city\\\/town\":\"Houston\",\"state\\\/province\\\/region\":\"TX\",\"zip\\\/postal code\":\"77056\",\"demand\":\"\",\"demand2\":\"\",\"demand3\":\"\",\"time of service\":\"5\",\"opening time 1\":\"\",\"closing time 1\":\"\",\"opening time 2\":\"\",\"closing time 2\":\"\",\"required skills\":\"\"}",
                    "custom_fields_config": null,
                    "custom_fields_config_str_json": "null",
                    "notes": [],
                    "wait_time_to_next_destination": null,
                    "manifest": {
                        "running_service_time": 0,
                        "running_travel_time": 0,
                        "running_wait_time": 0,
                        "running_distance": 0,
                        "fuel_from_start": 0,
                        "fuel_cost_from_start": 0,
                        "projected_arrival_time_ts": 1460260800,
                        "projected_departure_time_ts": 1460260800,
                        "actual_arrival_time_ts": null,
                        "actual_departure_time_ts": null,
                        "estimated_arrival_time_ts": 1460260800,
                        "estimated_departure_time_ts": 1460260800,
                        "time_impact": null
                    }
                }
            ],
            "links": {
                "route": "http:\/\/api.route4me.com\/api.v4\/route.php?route_id=1C9C05D3854FC30E82C942DC057B84DC&api_key=11111111111111111111111111111111&member_id=44143&device_tracking_history=0&original=0&notes=0",
                "optimization_problem_id": "http:\/\/api.route4me.com\/api.v4\/optimization_problem.php?optimization_problem_id=07372F2CF3814EC6DFFAFE92E22771AA&api_key=11111111111111111111111111111111&member_id=44143"
            },
            "notes": []
        }
    ],
    "links": {
        "view": "http:\/\/api.route4me.com\/api.v4\/optimization_problem.php?optimization_problem_id=07372F2CF3814EC6DFFAFE92E22771AA&api_key=11111111111111111111111111111111&member_id=1"
    }
}

Remove an Address from an Optimization

Removes a destination (an address) with specified route_destination_id from an optimization problem with specified optimization_problem_id.


PARAMETERS

Parameter Type Description
api_key string API key of the user
optimization_problem_id string Optimization problem ID
route_destination_id string Route destination ID
<job id="DeleteDestinationFromOptimization">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address.php"
      apikey="11111111111111111111111111111111"
      opi="123974C887534E84B6114F18A65847E3"
      rdi="154456307"
      
      url=url&"?api_key="&apikey
      url=url&"&optimization_problem_id="&opi
      url=url&"&route_destination_id="&rdi

      jFile=""
      
      Set r4m=New Route4Me
      
      r4m.HttpDeleteRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF
SET url=https://api.route4me.com
SET apikey=11111111111111111111111111111111
SET optprobid=123974C887534E84B6114F18A65847E3
SET routedestinationid=154456307

ECHO ON

curl -o file1.txt -g -X DELETE -k "%url%/api.v4/address.php?api_key=%apikey%&optimization_problem_id=%optprobid%&route_destination_id=%routedestinationid%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address.php
apikey=11111111111111111111111111111111
optprobid=123974C887534E84B6114F18A65847E3
routedestinationid=154456307

curl -o file1.txt -g -X DELETE -k "$url?api_key=$apikey&optimization_problem_id=$optprobid&route_destination_id=$routedestinationid"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void RemoveDestinationFromOptimization(string optimizationId, int destinationId, bool andReOptimize)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Run the query
      string errorString;
      bool removed = route4Me.RemoveDestinationFromOptimization(optimizationId, destinationId, out errorString);

      Console.WriteLine("");

      if (removed)
      {
        Console.WriteLine("RemoveAddressFromOptimization executed successfully");

        Console.WriteLine("Optimization Problem ID: {0}, Destination ID: {1}", optimizationId, destinationId);
      }
      else
      {
        Console.WriteLine("RemoveAddressFromOptimization error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub RemoveAddressFromOptimization(optimizationId As String, destinationId As Integer)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim deleted As Boolean = route4Me.RemoveAddressFromOptimization(optimizationId, destinationId, errorString)

            Console.WriteLine("")

            If deleted Then
                Console.WriteLine("RemoveAddressFromOptimization executed successfully")

                Console.WriteLine("Destination ID: {0}", destinationId)
            Else
                Console.WriteLine("RemoveRouteDestination error: {0}", errorString)
            End If

        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import (
    ALGORITHM_TYPE,
    OPTIMIZE,
    DISTANCE_UNIT,
    DEVICE_TYPE,
    TRAVEL_MODE
)

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    optimization = route4me.optimization
    address = route4me.address
    optimization.algorithm_type(ALGORITHM_TYPE.TSP)
    optimization.share_route(0)
    optimization.store_route(0)
    optimization.route_time(0)
    optimization.route_max_duration(86400)
    optimization.vehicle_capacity(1)
    optimization.vehicle_max_distance_mi(10000)
    optimization.route_name('Optimization Example')
    optimization.optimize(OPTIMIZE.DISTANCE)
    optimization.distance_unit(DISTANCE_UNIT.MI)
    optimization.device_type(DEVICE_TYPE.WEB)
    optimization.travel_mode(TRAVEL_MODE.DRIVING)
    address.add_address(
        address='754 5th Ave New York, NY 10019',
        lat=40.7636197,
        lng=-73.9744388,
        alias='Bergdorf Goodman',
        is_depot=1,
        time=0
    )
    address.add_address(
        address='717 5th Ave New York, NY 10022',
        lat=40.7669692,
        lng=-73.9693864,
        alias='Giorgio Armani',
        time=0
    )
    address.add_address(
        address='888 Madison Ave New York, NY 10014',
        lat=40.7715154,
        lng=-73.9669241,
        alias='Ralph Lauren Women\'s and Home',
        time=0
    )
    address.add_address(
        address='1011 Madison Ave New York, NY 10075',
        lat=40.7772129,
        lng=-73.9669,
        alias='Yigal Azrou\u00ebl',
        time=0
    )
    address.add_address(
        address='440 Columbus Ave New York, NY 10024',
        lat=40.7808364,
        lng=-73.9732729,
        alias='Frank Stella Clothier',
        time=0
    )
    address.add_address(
        address='324 Columbus Ave #1 New York, NY 10023',
        lat=40.7803123,
        lng=-73.9793079,
        alias='Liana',
        time=0
    )
    address.add_address(
        address='110 W End Ave New York, NY 10023',
        lat=40.7753077,
        lng=-73.9861529,
        alias='Toga Bike Shop',
        time=0
    )
    address.add_address(
        address='555 W 57th St New York, NY 10019',
        lat=40.7718005,
        lng=-73.9897716,
        alias='BMW of Manhattan',
        time=0
    )
    address.add_address(
        address='57 W 57th St New York, NY 10019',
        lat=40.7558695,
        lng=-73.9862019,
        alias='Verizon Wireless',
        time=0
    )

    response = route4me.run_optimization()
    optimization_id = response.addresses[0].optimization_problem_id
    route_destination_id = response.addresses[1].route_destination_id
    print 'Deleting Address: {0}  from Optimization Problem: {1}'.format(
        route_destination_id,
        optimization_id
    )
    response = route4me.optimization.delete_address_from_optimization(
        optimization_problem_id=optimization_id,
        route_destination_id=route_destination_id
    )
    print(response)

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}

  deletedRouteDestinationID, err := service.DeleteAddress(optimizationProblemId,routeID)
  if err != nil {
    // handle errors
    return
  }
  // do 
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Address;
use Route4Me\OptimizationProblem;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random optimization problem from test optimization problems
$optimization = new OptimizationProblem();

$optimization_problem_id = $optimization->getRandomOptimizationId(0, 10);

assert(!is_null($optimization_problem_id), "Can't retrieve a random optimization problem ID");

// Get random destination from selected optimization above
$addressRand = (array)$optimization->getRandomAddressFromOptimization($optimization_problem_id);

assert(!is_null($addressRand), "Can't retrieve random address");

if (isset($addressRand['is_depot'])) {
    if ($addressRand['is_depot']) {
        echo "This address is a depot! Try again.";
        return;
    }
}

$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

// Remove the destination from the optimization
$params = array (
    "optimization_problem_id"  => $optimization_problem_id,
    "route_destination_id"     => $route_destination_id
);

$result = $optimization->removeAddress($params);

var_dump($result);
unit RemoveDestinationFromOptimizationUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TRemoveDestinationFromOptimization = class(TBaseExample)
  public
    procedure Execute(
      OptimizationId: String; DestinationId: integer; AndReOptimize: boolean);
  end;

implementation

procedure TRemoveDestinationFromOptimization.Execute(

  OptimizationId: String; DestinationId: integer; AndReOptimize: boolean);

var
  ErrorString: String;
  Removed: boolean;
begin
  Removed := Route4MeManager.Optimization.RemoveDestination(
    OptimizationId, DestinationId, ErrorString);

  WriteLn('');

  if (Removed) then
  begin
    WriteLn('RemoveAddressFromOptimization executed successfully');
    WriteLn(Format('Optimization Problem ID: %s, Destination ID: %d',
      [OptimizationId, DestinationId]));
  end
  else
    WriteLn(Format('RemoveAddressFromOptimization error: %s', [ErrorString]));
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char opt_id[] = "123974C887534E84B6114F18A65847E3";
    char address[] = "154456307";
    init(key, 1);

    if (!remove_address_from_optimization(address, opt_id))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}

HTTP Request

DELETE
/api.v4/address.php.php?api_key=...&optimization_problem_id=...&route_destination_id=...


You can expect this API response:

{
    "deleted": true,
    "route_destination_id": 154456307
}

Re-Optimize an Optimization

Re-optimize existing optimizations by changing some parameters or addresses.

See the sample input JSON data for this method.

Parameter Type Description
api_key string API key of the user
reoptimize integer If equal to 1, it will be reoptimized. If 0, then no reoptimization.
optimization_problem_id string Optimization problem ID
input data POST data A valid JSON object string. See the Optimization Create JSON Schema as a guide.
<job id="Reoptimization">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/optimization_problem.php"
      apikey="11111111111111111111111111111111"
      opi="07372F2CF3814EC6DFFAFE92E22771AA"
      
      url=url&"?api_key="&apikey
      url=url&"&optimization_problem_id="&opi
      url=url&"&reoptimize=1"
      
      jFile="addresses_for_reoptimization.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void ReOptimization(string optimizationProblemID)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);
    
      OptimizationParameters optimizationParameters = new OptimizationParameters()
      {
        OptimizationProblemID = optimizationProblemID,
        ReOptimize = true
      };

      // Run the query
      string errorString;
      DataObject dataObject = route4Me.UpdateOptimization(optimizationParameters, out errorString);

      Console.WriteLine("");

      if (dataObject != null)
      {
        Console.WriteLine("ReOptimization executed successfully");

        Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId);
        Console.WriteLine("State: {0}", dataObject.State);
      }
      else
      {
        Console.WriteLine("ReOptimization error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub ReOptimization(optimizationProblemID As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim optimizationParameters As New OptimizationParameters() With { _
                .OptimizationProblemID = optimizationProblemID, _
                .ReOptimize = True _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As DataObject = route4Me.UpdateOptimization(optimizationParameters, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("ReOptimization executed successfully")

                Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId)
                Console.WriteLine("State: {0}", dataObject.State)
            Else
                Console.WriteLine("ReOptimization error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import OPTIMIZATION_STATE

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    optimization = route4me.optimization
    response = optimization.get_optimizations(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        optimizations = response.optimizations
        optimization_problem_id = optimizations[0].optimization_problem_id
        print 'Reoptimization problem ID: {}'.format(optimization_problem_id)
        response = route4me.reoptimization(optimization_problem_id)
        print 'Reoptimization status: %s' % \
              OPTIMIZATION_STATE.reverse_mapping.get(response.state)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.optimizations;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.DataObject;
import com.route4me.sdk.services.routing.OptimizationParameters;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class ReOptimization {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager manager = new RoutingManager(apiKey);
        try {
            List<DataObject> data = manager.getOptimizations(10, 5);
            DataObject obj = data.get(0);
            OptimizationParameters parameters = new OptimizationParameters();
            parameters.setProblemId(obj.getOptimizationProblemId());
            parameters.setReoptimize(true);
            DataObject updated = manager.updateOptimization(parameters);
            System.out.println(updated);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\OptimizationProblem;
use Route4Me\Route4Me;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

Route4Me::setApiKey('11111111111111111111111111111111');

// Get random optimization problem ID
$optimization = new OptimizationProblem();

$optimizationProblemId = $optimization->getRandomOptimizationId(0, 10);

assert(!is_null($optimizationProblemId), "Can't retrieve a random optimization problem ID");

// Reoptimize an optimization
$problemParams = array(
    'optimization_problem_id'  =>  $optimizationProblemId
);

$problem = OptimizationProblem::reoptimize($problemParams);

Route4Me::simplePrint($problem);
package routing

import (
  "math/rand"
  "reflect"
  "strconv"
  "testing"
  "time"

  "github.com/route4me/route4me-go-sdk"
)

var client = route4me.NewClient("11111111111111111111111111111111")
var service = &Service{Client: client}

func TestIntegrationUpdateOptimization(t *testing.T) {
  if testing.Short() {
    t.Skip("Skipping integration tests in short mode.")
  }
  optimizations, err := service.GetOptimizations(&RouteQuery{Limit: 1})
  if err != nil {
    t.Error("Error in external function (getOptimizations): ", err)
    return
  }
  if len(optimizations) < 1 {
    t.Skip("Not enough optimizations in the getOptimizations")
  }
  updated, err := service.UpdateOptimization(&OptimizationParameters{ProblemID: optimizations[0].ProblemID, Reoptimize: true})
  if err != nil {
    t.Error(err)
    return
  }
  get, err := service.GetOptimization(&OptimizationParameters{ProblemID: optimizations[0].ProblemID})
  if err != nil {
    t.Error(err)
    return
  }
  updated.SentToBackground = false
  if !reflect.DeepEqual(get, updated) {
    t.Error("Optimizations do not match")
  }
}
package ReOptimization;
use strict;
use warnings FATAL => 'all';
sub ReOptimization {
    my ($self, $optimizationProblemID) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $optimizationParameters = OptimizationParameters->new({
            optimization_problem_id => $optimizationProblemID,
            reoptimize => 1
        });

    my $errorString = "";

    my $dataObject = $route4Me->updateOptimization( $optimizationParameters, \$errorString );

    print "\n";

    if ($dataObject) {
        print "ReOptimization executed successfully\n";
        printf "Optimization Problem ID: %s\n", $optimizationProblemID;
        printf "State: %s\n", OptimizationState->get_optimization_state($dataObject->state);
    } else {
        printf "ReOptimization error: %s\n", $errorString;
    }

1;
@ECHO OFF

SET url=https://api.route4me.com
SET apikey=11111111111111111111111111111111
SET optprobid=07372F2CF3814EC6DFFAFE92E22771AA

:: The example demonstrates how to reoptimize an existing optimization.

ECHO ON

curl -o file1.txt -g -X PUT -k -d "@addresses_for_reoptimization.json" "%URL%/api.v4/optimization_problem.php?api_key=%apikey%&optimization_problem_id=%optprobid%&reoptimize=1" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/optimization_problem.php
apikey=11111111111111111111111111111111
optprobid=07372F2CF3814EC6DFFAFE92E22771AA

# The example demonstrates how to reoptimize an existing optimization.

curl -o file1.txt -g -X PUT -k -d "@addresses_for_reoptimization.json" "$url?api_key=$apikey&optimization_problem_id=$optprobid&reoptimize=1" 

echo "Finished.."

sleep 15
unit ReOptimizationUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TReOptimization = class(TBaseExample)
  public
    procedure Execute(OptimizationProblemId: String);
  end;

implementation

uses OptimizationParametersUnit, DataObjectUnit, EnumsUnit;

procedure TReOptimization.Execute(OptimizationProblemId: String);

var
  Parameters: TOptimizationParameters;
  ErrorString: String;
  DataObject: TDataObject;
begin
  Parameters := TOptimizationParameters.Create;
  try
    Parameters.OptimizationProblemID := OptimizationProblemId;
    Parameters.ReOptimize := True;

    DataObject := Route4MeManager.Optimization.Update(Parameters, ErrorString);

    WriteLn('');
    try
      if (DataObject <> nil) then
      begin
        WriteLn('ReOptimization executed successfully');
        WriteLn(Format('Optimization Problem ID: %s',
          [DataObject.OptimizationProblemId]));
        WriteLn(Format('State: %s',
          [TOptimizationDescription[TOptimizationState(DataObject.State)]]));
      end
      else
        WriteLn(Format('ReOptimization error: "%s"', [ErrorString]));
    finally
      FreeAndNil(DataObject);
    end;
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("addr.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }

    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    Json::Value params(Json::objectValue);
    params["route_name"] = "Single Driver Round Trip";
    params["algorithm_type"] = CRoute4Me::TSP;
    params["remote_ip"] = 0;
    params["member_id"] = 1;
    params["route_time"] = 0;
    params["route_max_duration"] = 86400;
    params["optimize"] = CRoute4Me::Distance;
    params["distance_unit"] = CRoute4Me::MI;
    params["travel_mode"] = CRoute4Me::Driving;
    params["store_route"] = 1;
    params["device_type"] = CRoute4Me::Web;
    params["vehicle_capacity"] = 1;
    params["vehicle_max_distance_mi"] = 10000;
    params["directions"] = 1;
    int ret = 0;
    Json::Value addr;
    inf >> addr;
    if(route.run_optimization(addr, params) == 0)
    {
        Json::Value id = route.get_json_resp()["optimization_problem_id"];
        if(!id.isNull())
        {
            cout << "Optimized problem ID is " << id.asString() << " => reoptimizing..." << endl;
            if(route.reoptimize(id.asCString()) == 0)
            {
                cout << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
                Json::Value state = route.get_json_resp()["state"];
                if(state.isNull())
                    cout << "Unknown response format" << endl;
                else
                    cout << "The problem is reoptimized Ok; state is " << state;
            }
            else
            {
                cout << "Err: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
                ret = -1;
            }
        }
    }
    else
    {
        cout << "Err: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include <json.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 1);
    const char file_name[] = "new_optimization.json";
    char* data = NULL;
    char id[100] = "";

    if (deserialize(file_name, &data))
    {
        printf("Data file not found!\n");
        return -1;
    }

    if (!add_optimization(data))
    {
       json_object* opt_lst = getJSONResponse();
       json_object* opt_problem = json_object_object_get(opt_lst, "optimization_problem_id");
       printf("Optimization problem created: %s\n", json_object_to_json_string(opt_problem));
       strip_quotes(id, json_object_to_json_string(opt_problem));
       printf("ID = %s\n", id);
       if (!reoptimize(id))
       {
           json_object* opt_lst = getJSONResponse();
           printf("%s\n", json_object_to_json_string(opt_lst));
       }
    }

    cleanUp();
    return 0;
}


PUT
/api.v4/optimization_problem.php?api_key=...&optimization_problem_id=...&reoptimize=...


See the sample JSON response of this method.


Routes

A Route refers to a collection of addresses usually sorted in the most optimal sequence. A route can have many addresses. Each address can have attributes, constraints, and metadata which influence the way the route is sequenced.

For usage details, see the cURL examples in the Route folder.

See the Route JSON Schema in our GitHub repository.

Route Properties

Attribute Type Description
route_id string Route ID
optimization_problem_id string Optimization ID
vehicle_alias string Vehicle alias
driver_alias string Driver alias
trip_distance double Route length
udu_distance_unit string Distance unit specified by a user in the offcial Route4Me web application
udu_trip_distance double Route length in the user unit
mpg integer Miles per gallon
gas_price double The price of gas.
route_duration_sec integer Estimated drive time of the route (in seconds).
planned_total_route_duration integer Planned route duration.
total_wait_time integer Total wait time during route trip.
udu_actual_travel_distance number Actual travel distance in the user distance unit.
parameters Route Parameters Route Parameters. See the Route Parameters JSON Schema as a guide.
addresses array Route Addresses. See the Address JSON Schema as a guide.
links array Links. See the Links JSON Schema as a guide.
directions array Directions. See the Direction JSON Schema as a guide.
path path Path. See the Path JSON Schema as a guide.
tracking_history TrackingHistory Tracking history. See the Tracking History JSON Schema as a guide.

Create a Route

Creates a new route with an optimization problem solution.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
optimization_problem_id string Optimization problem ID
input data POST data A valid JSON object string. See the Optimization Create JSON Schema as a guide.
<job id="CreateRoute">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of creating a new route.
      
      url="https://api.route4me.com/api.v4/optimization_problem.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="new_route_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/optimization_problem.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of creating a new route.

curl -o file1.txt -g -k -X POST -H "Content-Type: application/json" -d "@new_route_data.json" "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/optimization_problem.php
apikey=11111111111111111111111111111111

# The example demonstrates the process of creating a new route.

curl -o file1.txt -g -X POST -H "Content-Type: application/json" -d "@new_route_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public DataObject MultipleDepotMultipleDriver()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Prepare the addresses
      Address[] addresses = new Address[]
      {
        #region Addresses

        new Address() { AddressString   = "3634 W Market St, Fairlawn, OH 44333",
                        // All possible originating locations are depots and should be marked as true.
                        // Stylistically, we recommend all depots should be at the top of the destinations list.
                        IsDepot         = true, 
                        Latitude        = 41.135762259364,
                        Longitude       = -81.629313826561,
                        
                        // The number of seconds at the destination.
                        Time            = 300,
                        
                        // Together these two specify the time window of a destination.
                        // Seconds offset relative to the route start time for the open availability of a destination.
                        TimeWindowStart = 28800,  
                        
                        // Seconds offset relative to the route end time for the open availability of a destination.
                        TimeWindowEnd   = 29465},

        new Address() { AddressString   = "1218 Ruth Ave, Cuyahoga Falls, OH 44221",
                        Latitude        = 41.135762259364,
                        Longitude       = -81.629313826561,
                        Time            = 300,
                        TimeWindowStart = 29465,
                        TimeWindowEnd   = 30529},

        new Address() { AddressString   = "512 Florida Pl, Barberton, OH 44203",
                        Latitude        = 41.003671512008,
                        Longitude       = -81.598461046815,
                        Time            = 300,
                        TimeWindowStart = 30529,
                        TimeWindowEnd   = 33779},

        new Address() { AddressString   = "512 Florida Pl, Barberton, OH 44203",
                        Latitude        = 41.003671512008,
                        Longitude       = -81.598461046815,
                        Time            = 100,
                        TimeWindowStart = 33779,
                        TimeWindowEnd   = 33944},

        new Address() { AddressString   = "3495 Purdue St, Cuyahoga Falls, OH 44221",
                        Latitude        = 41.162971496582,
                        Longitude       = -81.479049682617,
                        Time            = 300,
                        TimeWindowStart = 33944,
                        TimeWindowEnd   = 34801},

        new Address() { AddressString   = "1659 Hibbard Dr, Stow, OH 44224",
                        Latitude        = 41.194505989552,
                        Longitude       = -81.443351581693,
                        Time            = 300,
                        TimeWindowStart = 34801,
                        TimeWindowEnd   = 36366},

        new Address() { AddressString   = "2705 N River Rd, Stow, OH 44224",
                        Latitude        = 41.145240783691,
                        Longitude       = -81.410247802734,
                        Time            = 300,
                        TimeWindowStart = 36366,
                        TimeWindowEnd   = 39173},

        new Address() { AddressString   = "10159 Bissell Dr, Twinsburg, OH 44087",
                        Latitude        = 41.340042114258,
                        Longitude       = -81.421226501465,
                        Time            = 300,
                        TimeWindowStart = 39173,
                        TimeWindowEnd   = 41617},

        new Address() { AddressString   = "367 Cathy Dr, Munroe Falls, OH 44262",
                        Latitude        = 41.148578643799,
                        Longitude       = -81.429229736328,
                        Time            = 300,
                        TimeWindowStart = 41617,
                        TimeWindowEnd   = 43660},

        new Address() { AddressString   = "367 Cathy Dr, Munroe Falls, OH 44262",
                        Latitude        = 41.148578643799,
                        Longitude       = -81.429229736328,
                        Time            = 300,
                        TimeWindowStart = 43660,
                        TimeWindowEnd   = 46392},

        new Address() { AddressString   = "512 Florida Pl, Barberton, OH 44203",
                        Latitude        = 41.003671512008,
                        Longitude       = -81.598461046815,
                        Time            = 300,
                        TimeWindowStart = 46392,
                        TimeWindowEnd   = 48389},

        new Address() { AddressString   = "559 W Aurora Rd, Northfield, OH 44067",
                        Latitude        = 41.315116882324,
                        Longitude       = -81.558746337891,
                        Time            = 50,
                        TimeWindowStart = 48389,
                        TimeWindowEnd   = 48449},

        new Address() { AddressString   = "3933 Klein Ave, Stow, OH 44224",
                        Latitude        = 41.169467926025,
                        Longitude       = -81.429420471191,
                        Time            = 300,
                        TimeWindowStart = 48449,
                        TimeWindowEnd   = 50152},

        new Address() { AddressString   = "2148 8th St, Cuyahoga Falls, OH 44221",
                        Latitude        = 41.136692047119,
                        Longitude       = -81.493492126465,
                        Time            = 300,
                        TimeWindowStart = 50152,
                        TimeWindowEnd   = 51982},

        new Address() { AddressString   = "3731 Osage St, Stow, OH 44224",
                        Latitude        = 41.161357879639,
                        Longitude       = -81.42293548584,
                        Time            = 100,
                        TimeWindowStart = 51982,
                        TimeWindowEnd   = 52180},

        new Address() { AddressString   = "3731 Osage St, Stow, OH 44224",
                        Latitude        = 41.161357879639,
                        Longitude       = -81.42293548584,
                        Time            = 300,
                        TimeWindowStart = 52180,
                        TimeWindowEnd   = 54379}
        #endregion
      };

      // Set parameters
      RouteParameters parameters = new RouteParameters()
      {
        // Specify capacitated vehicle routing with time windows and multiple depots, with multiple drivers
        AlgorithmType = AlgorithmType.CVRP_TW_MD,
        
        // Set an arbitrary route name
        // This value shows up on the website and all connected mobile devices.
        RouteName     = "Multiple Depot, Multiple Driver",

        // The route start date in UTC, Unix timestamp seconds (Tomorrow)
        RouteDate     = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.Date.AddDays(1)),
        // The time in UTC when a route is starting (7 AM)
        RouteTime     = 60 * 60 * 7,
        
        // The maximum duration of a route
        RouteMaxDuration     = 86400,
        VehicleCapacity      = "1",
        VehicleMaxDistanceMI = "10000",

        Optimize     = Optimize.Distance.Description(),
        DistanceUnit = DistanceUnit.MI.Description(),
        DeviceType   = DeviceType.Web.Description(),
        TravelMode   = TravelMode.Driving.Description(),
        Metric       = Metric.Geodesic
      };

      OptimizationParameters optimizationParameters = new OptimizationParameters()
      {
        Addresses = addresses,
        Parameters = parameters
      };

      // Run the query
      string errorString;
      DataObject dataObject = route4Me.RunOptimization(optimizationParameters, out errorString);

      // Output the result
      PrintExampleOptimizationResult("MultipleDepotMultipleDriver", dataObject, errorString);

      return dataObject;
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Function MultipleDepotMultipleDriver() As DataObject
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Prepare the addresses

            Dim addresses As Address() = New Address() {New Address() With { _
                .AddressString = "3634 W Market St, Fairlawn, OH 44333", _
                .IsDepot = True, _
                .Latitude = 41.135762259364, _
                .Longitude = -81.629313826561, _
                .Time = 300, _
                .TimeWindowStart = 28800, _
                .TimeWindowEnd = 29465 _
            }, New Address() With { _
                .AddressString = "1218 Ruth Ave, Cuyahoga Falls, OH 44221", _
                .Latitude = 41.135762259364, _
                .Longitude = -81.629313826561, _
                .Time = 300, _
                .TimeWindowStart = 29465, _
                .TimeWindowEnd = 30529 _
            }, New Address() With { _
                .AddressString = "512 Florida Pl, Barberton, OH 44203", _
                .Latitude = 41.003671512008, _
                .Longitude = -81.598461046815, _
                .Time = 300, _
                .TimeWindowStart = 30529, _
                .TimeWindowEnd = 33779 _
            }, New Address() With { _
                .AddressString = "512 Florida Pl, Barberton, OH 44203", _
                .Latitude = 41.003671512008, _
                .Longitude = -81.598461046815, _
                .Time = 100, _
                .TimeWindowStart = 33779, _
                .TimeWindowEnd = 33944 _
            }, New Address() With { _
                .AddressString = "3495 Purdue St, Cuyahoga Falls, OH 44221", _
                .Latitude = 41.162971496582, _
                .Longitude = -81.479049682617, _
                .Time = 300, _
                .TimeWindowStart = 33944, _
                .TimeWindowEnd = 34801 _
            }, New Address() With { _
                .AddressString = "1659 Hibbard Dr, Stow, OH 44224", _
                .Latitude = 41.194505989552, _
                .Longitude = -81.443351581693, _
                .Time = 300, _
                .TimeWindowStart = 34801, _
                .TimeWindowEnd = 36366 _
            }, _
                New Address() With { _
                .AddressString = "2705 N River Rd, Stow, OH 44224", _
                .Latitude = 41.145240783691, _
                .Longitude = -81.410247802734, _
                .Time = 300, _
                .TimeWindowStart = 36366, _
                .TimeWindowEnd = 39173 _
            }, New Address() With { _
                .AddressString = "10159 Bissell Dr, Twinsburg, OH 44087", _
                .Latitude = 41.340042114258, _
                .Longitude = -81.421226501465, _
                .Time = 300, _
                .TimeWindowStart = 39173, _
                .TimeWindowEnd = 41617 _
            }, New Address() With { _
                .AddressString = "367 Cathy Dr, Munroe Falls, OH 44262", _
                .Latitude = 41.148578643799, _
                .Longitude = -81.429229736328, _
                .Time = 300, _
                .TimeWindowStart = 41617, _
                .TimeWindowEnd = 43660 _
            }, New Address() With { _
                .AddressString = "367 Cathy Dr, Munroe Falls, OH 44262", _
                .Latitude = 41.148578643799, _
                .Longitude = -81.429229736328, _
                .Time = 300, _
                .TimeWindowStart = 43660, _
                .TimeWindowEnd = 46392 _
            }, New Address() With { _
                .AddressString = "512 Florida Pl, Barberton, OH 44203", _
                .Latitude = 41.003671512008, _
                .Longitude = -81.598461046815, _
                .Time = 300, _
                .TimeWindowStart = 46392, _
                .TimeWindowEnd = 48389 _
            }, New Address() With { _
                .AddressString = "559 W Aurora Rd, Northfield, OH 44067", _
                .Latitude = 41.315116882324, _
                .Longitude = -81.558746337891, _
                .Time = 50, _
                .TimeWindowStart = 48389, _
                .TimeWindowEnd = 48449 _
            }, _
                New Address() With { _
                .AddressString = "3933 Klein Ave, Stow, OH 44224", _
                .Latitude = 41.169467926025, _
                .Longitude = -81.429420471191, _
                .Time = 300, _
                .TimeWindowStart = 48449, _
                .TimeWindowEnd = 50152 _
            }, New Address() With { _
                .AddressString = "2148 8th St, Cuyahoga Falls, OH 44221", _
                .Latitude = 41.136692047119, _
                .Longitude = -81.493492126465, _
                .Time = 300, _
                .TimeWindowStart = 50152, _
                .TimeWindowEnd = 51982 _
            }, New Address() With { _
                .AddressString = "3731 Osage St, Stow, OH 44224", _
                .Latitude = 41.161357879639, _
                .Longitude = -81.42293548584, _
                .Time = 100, _
                .TimeWindowStart = 51982, _
                .TimeWindowEnd = 52180 _
            }, New Address() With { _
                .AddressString = "3731 Osage St, Stow, OH 44224", _
                .Latitude = 41.161357879639, _
                .Longitude = -81.42293548584, _
                .Time = 300, _
                .TimeWindowStart = 52180, _
                .TimeWindowEnd = 54379 _
            }}

            ' Set parameters
            ' Specify capacitated vehicle routing with time windows and multiple depots, with multiple drivers.

            ' Set an arbitrary route name.
            ' This value shows up on the website and all connected mobile devices.

            ' The route start date in UTC, Unix timestamp seconds (Tomorrow).
            ' The time in UTC when a route is starting (7 AM).

            ' The maximum duration of a route.

            Dim parameters As New RouteParameters() With { _
                .AlgorithmType = AlgorithmType.CVRP_TW_MD, _
                .RouteName = "Multiple Depot, Multiple Driver", _
                .RouteDate = R4MeUtils.ConvertToUnixTimestamp(DateTime.UtcNow.[Date].AddDays(1)), _
                .RouteTime = 60 * 60 * 7, _
                .RouteMaxDuration = 86400, _
                .VehicleCapacity = "1", _
                .VehicleMaxDistanceMI = "10000", _
                .Optimize = EnumHelper.GetEnumDescription(Optimize.Distance), _
                .DistanceUnit = EnumHelper.GetEnumDescription(DistanceUnit.MI), _
                .DeviceType = EnumHelper.GetEnumDescription(DeviceType.Web), _
                .TravelMode = EnumHelper.GetEnumDescription(TravelMode.Driving), _
                .Metric = Metric.Geodesic _
            }

            Dim optimizationParameters As New OptimizationParameters() With { _
                .Addresses = addresses, _
                .Parameters = parameters _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As DataObject = route4Me.RunOptimization(optimizationParameters, errorString)

            ' Output the result
            PrintExampleOptimizationResult("MultipleDepotMultipleDriver", dataObject, errorString)

            Return dataObject
        End Function
    End Class
End Namespace
#!/usr/bin/python

import json

from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    optimization = route4me.optimization
    address = route4me.address
    optimization.algorithm_type(ALGORITHM_TYPE.CVRP_TW_MD)
    optimization.share_route(0)
    optimization.store_route(0)
    optimization.route_time(0)
    optimization.parts(20)
    optimization.route_max_duration(86400)
    optimization.vehicle_capacity(1)
    optimization.vehicle_max_distance_mi(10000)
    optimization.route_name('Multiple Depot, Multiple Driver')
    optimization.optimize(OPTIMIZE.DISTANCE)
    optimization.distance_unit(DISTANCE_UNIT.MI)
    optimization.device_type(DEVICE_TYPE.WEB)
    optimization.travel_mode(TRAVEL_MODE.DRIVING)
    optimization.metric(METRIC.ROUTE4ME_METRIC_GEODESIC)

    address.add_address(
            address="455 S 4th St, Louisville, KY 40202",
            lat=38.251698,
            lng=-85.757308,
            is_depot=1,
            time=300,
            time_window_start=28800,
            time_window_end=29400
    )
    address.add_address(
            address="1604 PARKRIDGE PKWY, Louisville, KY, 40214",
            lat=38.141598,
            lng=-85.793846,
            is_depot=1,
            time=300,
            time_window_start=29400,
            time_window_end=30000
    )
    address.add_address(
            address="1407 MCCOY, Louisville, KY, 40215",
            lat=38.202496,
            lng=-85.786514,
            is_depot=0,
            time=300,
            time_window_start=30000,
            time_window_end=30600
    )
    address.add_address(
            address="4805 BELLEVUE AVE, Louisville, KY, 40215",
            lat=38.178844,
            lng=-85.774864,
            is_depot=0,
            time=300,
            time_window_start=30600,
            time_window_end=31200
    )
    address.add_address(
            address="730 CECIL AVENUE, Louisville, KY, 40211",
            lat=38.248684,
            lng=-85.821121,
            is_depot=0,
            time=300,
            time_window_start=31200,
            time_window_end=31800
    )
    address.add_address(
            address="650 SOUTH 29TH ST UNIT 315, Louisville, KY, 40211",
            lat=38.251923,
            lng=-85.800034,
            is_depot=0,
            time=300,
            time_window_start=31800,
            time_window_end=32400
    )
    address.add_address(
            address="4629 HILLSIDE DRIVE, Louisville, KY, 40216",
            lat=38.176067,
            lng=-85.824638,
            is_depot=0,
            time=300,
            time_window_start=32400,
            time_window_end=33000
    )
    address.add_address(
            address="4738 BELLEVUE AVE, Louisville, KY, 40215",
            lat=38.179806,
            lng=-85.775558,
            is_depot=0,
            time=300,
            time_window_start=33000,
            time_window_end=33600
    )
    address.add_address(
            address="318 SO. 39TH STREET, Louisville, KY, 40212",
            lat=38.259335,
            lng=-85.815094,
            is_depot=0,
            time=300,
            time_window_start=33600,
            time_window_end=34200
    )
    address.add_address(
            address="1324 BLUEGRASS AVE, Louisville, KY, 40215",
            lat=38.179253,
            lng=-85.785118,
            is_depot=0,
            time=300,
            time_window_start=34200,
            time_window_end=34800
    )
    address.add_address(
            address="7305 ROYAL WOODS DR, Louisville, KY, 40214",
            lat=38.162472,
            lng=-85.792854,
            is_depot=0,
            time=300,
            time_window_start=34800,
            time_window_end=35400
    )
    address.add_address(
            address="1661 W HILL ST, Louisville, KY, 40210",
            lat=38.229584,
            lng=-85.783966,
            is_depot=0,
            time=300,
            time_window_start=35400,
            time_window_end=36000
    )
    address.add_address(
            address="3222 KINGSWOOD WAY, Louisville, KY, 40216",
            lat=38.210606,
            lng=-85.822594,
            is_depot=0,
            time=300,
            time_window_start=36000,
            time_window_end=36600
    )
    address.add_address(
            address="1922 PALATKA RD, Louisville, KY, 40214",
            lat=38.153767,
            lng=-85.796783,
            is_depot=0,
            time=300,
            time_window_start=36600,
            time_window_end=37200
    )
    print optimization.data

    response = route4me.run_optimization()
    print 'Optimization Link: %s' % response.links.view
    for address in response.addresses:
        print 'Route %s link: %sroute_id=%s' % (address.address,
                                                route4me.route_url(),
                                                address.route_id)
    route4me.export_result_to_json('multiple_depot_multiple_driver.json')

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples;

import com.route4me.sdk.Route4Me;
import com.route4me.sdk.model.Address;
import com.route4me.sdk.model.DataObject;
import com.route4me.sdk.managers.OptimizationManager;
import com.route4me.sdk.model.Parameters;
import com.route4me.sdk.model.Response;
import com.route4me.sdk.model.enums.Constants.*;
import com.route4me.sdk.serdes.DataObjectDeserializer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MultipleDepotMultipleDriver {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        Route4Me route4me = new Route4Me(apiKey);
        OptimizationManager optimizationManager = route4me.getOptimizationManager();
        Map<String, String> params = new HashMap<>();
        optimizationManager.setParams(params);
        DataObject data = new DataObject();
        Parameters parameters = new Parameters();
        List<Address> addresses = new ArrayList<>();
        data.setParameters(parameters);
        data.setAddresses(addresses);
        parameters.setAlgorithm_type(AlgorithmType.CVRP_TW_MD.getValue());
        parameters.setStore_route(Boolean.FALSE);
        parameters.setShare_route(Boolean.FALSE);
        parameters.setRoute_time(0);
        parameters.setParts(20);
        parameters.setRoute_max_duration(86400);
        parameters.setVehicle_capacity("9999");
        parameters.setVehicle_max_distance_mi("10000");
        parameters.setRoute_name("Multiple Depot, Multiple Driver");
        parameters.setOptimize(Optimize.DISTANCE.toString());
        parameters.setDistance_unit(DistanceUnit.MI.toString());
        parameters.setDevice_type(DeviceType.WEB.toString());
        parameters.setTravel_mode(TravelMode.DRIVING.toString());
        parameters.setMetric(Metric.ROUTE4ME_METRIC_GEODESIC.getValue());
        addresses.add(new Address("455 S 4th St, Louisville, KY 40202",Boolean.TRUE, 38.251698, -85.757308, 300, 28800, 29400));
        addresses.add(new Address("1604 PARKRIDGE PKWY, Louisville, KY, 40214",Boolean.TRUE, 38.141598, -85.793846, 300, 29400, 30000));
        addresses.add(new Address("1407 MCCOY, Louisville, KY, 40215",38.202496,-85.786514,300,30000,30600));
        addresses.add(new Address("4805 BELLEVUE AVE, Louisville, KY, 40215",38.178844,-85.774864,300,30600,31200));
        addresses.add(new Address("730 CECIL AVENUE, Louisville, KY, 40211",38.248684,-85.821121,300,31200,31800));
        addresses.add(new Address("650 SOUTH 29TH ST UNIT 315, Louisville, KY, 40211",38.251923,-85.800034,300,31800,32400));
        addresses.add(new Address("4629 HILLSIDE DRIVE, Louisville, KY, 40216",38.176067,-85.824638,300,32400,33000));
        addresses.add(new Address("4738 BELLEVUE AVE, Louisville, KY, 40215",38.179806,-85.775558,300,33000,33600));
        addresses.add(new Address("318 SO. 39TH STREET, Louisville, KY, 40212",38.259335,-85.815094,300,33600,34200));
        addresses.add(new Address("1324 BLUEGRASS AVE, Louisville, KY, 40215",38.179253,-85.785118,300,34200,34800));
        addresses.add(new Address("7305 ROYAL WOODS DR, Louisville, KY, 40214",38.162472,-85.792854,300,34800,35400));
        addresses.add(new Address("1661 W HILL ST, Louisville, KY, 40210",38.229584,-85.783966,300,35400,36000));
        addresses.add(new Address("3222 KINGSWOOD WAY, Louisville, KY, 40216",38.210606,-85.822594,300,36000,36600));
        addresses.add(new Address("1922 PALATKA RD, Louisville, KY, 40214",38.153767,-85.796783,300,36600,37200));
        addresses.add(new Address("1314 SOUTH 26TH STREET, Louisville, KY, 40210",38.235847,-85.796852,300,37200,37800));
        addresses.add(new Address("2135 MCCLOSKEY AVENUE, Louisville, KY, 40210",38.218662,-85.789032,300,37800,38400));
        addresses.add(new Address("1409 PHYLLIS AVE, Louisville, KY, 40215",38.206154,-85.781387,300,38400,39000));
        addresses.add(new Address("4504 SUNFLOWER AVE, Louisville, KY, 40216",38.187511,-85.839149,300,39000,39600));
        addresses.add(new Address("2512 GREENWOOD AVE, Louisville, KY, 40210",38.241405,-85.795059,300,39600,40200));
        addresses.add(new Address("5500 WILKE FARM AVE, Louisville, KY, 40216",38.166065,-85.863319,300,40200,40800));
        addresses.add(new Address("3640 LENTZ AVE, Louisville, KY, 40215",38.193283,-85.786201,300,40800,41400));
        addresses.add(new Address("1020 BLUEGRASS AVE, Louisville, KY, 40215",38.17952,-85.780037,300,41400,42000));
        addresses.add(new Address("123 NORTH 40TH ST, Louisville, KY, 40212",38.26498,-85.814156,300,42000,42600));
        addresses.add(new Address("7315 ST ANDREWS WOODS CIRCLE UNIT 104, Louisville, KY, 40214",38.151072,-85.802867,300,42600,43200));
        addresses.add(new Address("3210 POPLAR VIEW DR, Louisville, KY, 40216",38.182594,-85.849937,300,43200,43800));
        addresses.add(new Address("4519 LOUANE WAY, Louisville, KY, 40216",38.1754,-85.811447,300,43800,44400));
        addresses.add(new Address("6812 MANSLICK RD, Louisville, KY, 40214",38.161839,-85.798279,300,44400,45000));
        addresses.add(new Address("1524 HUNTOON AVENUE, Louisville, KY, 40215",38.172031,-85.788353,300,45000,45600));
        addresses.add(new Address("1307 LARCHMONT AVE, Louisville, KY, 40215",38.209663,-85.779816,300,45600,46200));
        addresses.add(new Address("434 N 26TH STREET #2, Louisville, KY, 40212",38.26844,-85.791962,300,46200,46800));
        addresses.add(new Address("678 WESTLAWN ST, Louisville, KY, 40211",38.250397,-85.80629,300,46800,47400));
        addresses.add(new Address("2308 W BROADWAY, Louisville, KY, 40211",38.248882,-85.790421,300,47400,48000));
        addresses.add(new Address("2332 WOODLAND AVE, Louisville, KY, 40210",38.233579,-85.794257,300,48000,48600));
        addresses.add(new Address("1706 WEST ST. CATHERINE, Louisville, KY, 40210",38.239697,-85.783928,300,48600,49200));
        addresses.add(new Address("1699 WATHEN LN, Louisville, KY, 40216",38.216465,-85.792397,300,49200,49800));
        addresses.add(new Address("2416 SUNSHINE WAY, Louisville, KY, 40216",38.186245,-85.831787,300,49800,50400));
        addresses.add(new Address("6925 MANSLICK RD, Louisville, KY, 40214",38.158466,-85.798355,300,50400,51000));
        addresses.add(new Address("2707 7TH ST, Louisville, KY, 40215",38.212438,-85.785082,300,51000,51600));
        addresses.add(new Address("2014 KENDALL LN, Louisville, KY, 40216",38.179394,-85.826668,300,51600,52200));
        addresses.add(new Address("612 N 39TH ST, Louisville, KY, 40212",38.273354,-85.812012,300,52200,52800));
        addresses.add(new Address("2215 ROWAN ST, Louisville, KY, 40212",38.261703,-85.786781,300,52800,53400));
        addresses.add(new Address("1826 W. KENTUCKY ST, Louisville, KY, 40210",38.241611,-85.78653,300,53400,54000));
        addresses.add(new Address("1810 GREGG AVE, Louisville, KY, 40210",38.224716,-85.796211,300,54000,54600));
        addresses.add(new Address("4103 BURRRELL DRIVE, Louisville, KY, 40216",38.191753,-85.825836,300,54600,55200));
        addresses.add(new Address("359 SOUTHWESTERN PKWY, Louisville, KY, 40212",38.259903,-85.823463,300,55200,55800));
        addresses.add(new Address("2407 W CHESTNUT ST, Louisville, KY, 40211",38.252781,-85.792109,300,55800,56400));
        addresses.add(new Address("225 S 22ND ST, Louisville, KY, 40212",38.257616,-85.786658,300,56400,57000));
        addresses.add(new Address("1404 MCCOY AVE, Louisville, KY, 40215",38.202122,-85.786072,300,57000,57600));
        addresses.add(new Address("117 FOUNT LANDING CT, Louisville, KY, 40212",38.270061,-85.799438,300,57600,58200));
        addresses.add(new Address("5504 SHOREWOOD DRIVE, Louisville, KY, 40214",38.145851,-85.7798,300,58200,58800));
        optimizationManager.setData(data);
        DataObject responseObject = optimizationManager.runOptimization();
        System.out.println("Optimization Problem ID:" + responseObject.getOptimization_problem_id());
        System.out.println("State:" + OptimizationState.get(responseObject.getState().intValue()));
        if (responseObject.getAddresses() != null) {
            for (Address address : responseObject.getAddresses()) {
                System.out.println("Address:" + address.getAddress());
                System.out.println("Route ID:" + address.getRoute_id());
            }
        }
    }
}
package MultipleDepotMultipleDriver;
use strict;
use warnings FATAL => 'all';

sub MultipleDepotMultipleDriver {

    # Create the manager with the API key
    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $addresses = [
        Address->new( address => "3634 W Market St, Fairlawn, OH 44333",

            # All possible originating locations are depots and should be marked as true.
            # Stylistically, we recommend all depots should be at the top of the destinations list.
            is_depot          => 1,
            lat               => 41.135762259364,
            lng               => -81.629313826561,

            # The number of seconds at a destination.
            time              => 300,

            # Together these two specify the time window of a destination.
            # Seconds offset relative to the route start time for the open availability of a destination.
            time_window_start => 28800,

            # Seconds offset relative to the route end time for the open availability of a destination.
            time_window_end   => 29465
        ),
        Address->new( address => "1218 Ruth Ave, Cuyahoga Falls, OH 44221",
            lat               => 41.135762259364,
            lng               => -81.629313826561,
            time              => 300,
            time_window_start => 29465,
            time_window_end   => 30529 ),

        Address->new( address => "512 Florida Pl, Barberton, OH 44203",
            lat               => 41.003671512008,
            lng               => -81.598461046815,
            time              => 300,
            time_window_start => 30529,
            time_window_end   => 33779 ),

        Address->new( address => "512 Florida Pl, Barberton, OH 44203",
            lat               => 41.003671512008,
            lng               => -81.598461046815,
            time              => 100,
            time_window_start => 33779,
            time_window_end   => 33944 ),

        Address->new( address => "3495 Purdue St, Cuyahoga Falls, OH 44221",
            lat               => 41.162971496582,
            lng               => -81.479049682617,
            time              => 300,
            time_window_start => 33944,
            time_window_end   => 34801 ),

        Address->new( address => "1659 Hibbard Dr, Stow, OH 44224",
            lat               => 41.194505989552,
            lng               => -81.443351581693,
            time              => 300,
            time_window_start => 34801,
            time_window_end   => 36366 ),

        Address->new( address => "2705 N River Rd, Stow, OH 44224",
            lat               => 41.145240783691,
            lng               => -81.410247802734,
            time              => 300,
            time_window_start => 36366,
            time_window_end   => 39173 ),

        Address->new( address => "10159 Bissell Dr, Twinsburg, OH 44087",
            lat               => 41.340042114258,
            lng               => -81.421226501465,
            time              => 300,
            time_window_start => 39173,
            time_window_end   => 41617 ),

        Address->new( address => "367 Cathy Dr, Munroe Falls, OH 44262",
            lat               => 41.148578643799,
            lng               => -81.429229736328,
            time              => 300,
            time_window_start => 41617,
            time_window_end   => 43660 ),

        Address->new( address => "367 Cathy Dr, Munroe Falls, OH 44262",
            lat               => 41.148578643799,
            lng               => -81.429229736328,
            time              => 300,
            time_window_start => 43660,
            time_window_end   => 46392 ),

        Address->new( address => "512 Florida Pl, Barberton, OH 44203",
            lat               => 41.003671512008,
            lng               => -81.598461046815,
            time              => 300,
            time_window_start => 46392,
            time_window_end   => 48389 ),

        Address->new( address => "559 W Aurora Rd, Northfield, OH 44067",
            lat               => 41.315116882324,
            lng               => -81.558746337891,
            time              => 50,
            time_window_start => 48389,
            time_window_end   => 48449 ),

        Address->new( address => "3933 Klein Ave, Stow, OH 44224",
            lat               => 41.169467926025,
            lng               => -81.429420471191,
            time              => 300,
            time_window_start => 48449,
            time_window_end   => 50152 ),

        Address->new( address => "2148 8th St, Cuyahoga Falls, OH 44221",
            lat               => 41.136692047119,
            lng               => -81.493492126465,
            time              => 300,
            time_window_start => 50152,
            time_window_end   => 51982 ),

        Address->new( address => "3731 Osage St, Stow, OH 44224",
            lat               => 41.161357879639,
            lng               => -81.42293548584,
            time              => 100,
            time_window_start => 51982,
            time_window_end   => 52180 ),

        Address->new( address => "3731 Osage St, Stow, OH 44224",
            lat               => 41.161357879639,
            lng               => -81.42293548584,
            time              => 300,
            time_window_start => 52180,
            time_window_end   => 54379 )
    ];

    my $parameters = RouteParameters->new(
        # Specify capacitated vehicle routing with time windows and multiple depots, with multiple drivers.
        algorithm_type          => AlgorithmType->CVRP_TW_MD,

        # Set an arbitrary route name.
        # This value shows up on the website and all connected mobile devices.
        route_name              => "Multiple Depot, Multiple Driver",

        # The route start date in UTC, Unix timestamp seconds (Tomorrow).
        route_date              => time + 3600,

        # The time in UTC when a route is starting (7 AM).
        route_time              => 60 * 60 * 7,

        # The maximum duration of a route.
        route_max_duration      => 86400,
        vehicle_capacity        => "1",
        vehicle_max_distance_mi => "10000",

        optimize                => Optimize->Distance,
        distance_unit           => DistanceUnit->MI,
        device_type             => DeviceType->Web,
        travel_mode             => TravelMode->Driving,
        metric                  => Metric->Geodesic
        );

    my $optimizationParameters = OptimizationParameters->new(
        addresses  => $addresses,
        parameters => $parameters
    );

    my $errorString = "";

    my $dataObject = $route4Me->runOptimization( $optimizationParameters, \$errorString );

    ExamplesInfrastructure->PrintExampleOptimizationResult( "MultipleDepotMultipleDriver", $dataObject, $errorString );

    return $dataObject;
}
1;
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    routeParams := &routing.RouteParameters{
        AlgorithmType:        routing.CVRP_TW_MD,
        Name:                 "Multiple Depot, Multiple Driver",
        RouteDate:            time.Now().Unix(),
        RouteTime:            60 * 60 * 7,
        RouteMaxDuration:     86400,
        VehicleCapacity:      1,
        VehicleMaxDistanceMI: 1000,
        Optimize:             routing.Distance,
        DistanceUnit:         routing.Miles,
        DeviceType:           routing.Web,
        TravelMode:           routing.Driving,
    }
    optParams := &routing.OptimizationParameters{
        Addresses:  addresses,
        Parameters: routeParams,
    }
    optimization, err := service.RunOptimization(optParams)
    if err != nil {
        // handle errors
        return
    }
    // do something with optimization
}
<?php
namespace Route4Me;

$root=realpath(dirname(__FILE__).'/../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\OptimizationType;
use Route4Me\OptimizationProblem;
use Route4Me\OptimizationProblemParams;
use Route4Me\Enum\AlgorithmType;
use Route4Me\Enum\DistanceUnit;
use Route4Me\Enum\DeviceType;
use Route4Me\Enum\TravelMode;
use Route4Me\Enum\Metric;
use Route4Me\RouteParameters;
use Route4Me\Address;
use Route4Me\Route;

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Huge list of addresses
$json = json_decode(file_get_contents('./addresses.json'), true);

$addresses = array();
foreach($json as $address) {
    $addresses[] = Address::fromArray($address);
}

$parameters = RouteParameters::fromArray(array(
    "algorithm_type"          => AlgorithmType::CVRP_TW_SD,
    "distance_unit"           => DistanceUnit::MILES,
    "device_type"             => DeviceType::WEB,
    "optimize"                => OptimizationType::DISTANCE,
    "metric"                  => Metric::GEODESIC,
    "route_max_duration"      => 86400 * 2,
    "travel_mode"             => TravelMode::DRIVING,
    "vehicle_capacity"        => 50,
    "vehicle_max_distance_mi" => 10000,
    "parts"                   => 50
));

$optimizationParams = new OptimizationProblemParams;
$optimizationParams->setAddresses($addresses);
$optimizationParams->setParameters($parameters);

$problem = OptimizationProblem::optimize($optimizationParams);

Route4Me::simplePrint((array)$problem, true);
unit MultipleDepotMultipleDriverUnit;

interface

uses SysUtils, DataObjectUnit, BaseOptimizationExampleUnit;

type
  TMultipleDepotMultipleDriver = class(TBaseOptimizationExample)
  public
    function Execute: TDataObject;
  end;

implementation

uses
  IOptimizationParametersProviderUnit, OptimizationParametersUnit,
  MultipleDepotMultipleDriverTestDataProviderUnit;

function TMultipleDepotMultipleDriver.Execute: TDataObject;
var
  DataProvider: IOptimizationParametersProvider;
  ErrorString: String;
  Parameters: TOptimizationParameters;
begin
  DataProvider := TMultipleDepotMultipleDriverTestDataProvider.Create;

  Parameters := DataProvider.OptimizationParameters;
  try
    Result := Route4MeManager.Optimization.Run(Parameters, ErrorString);
  finally
    FreeAndNil(Parameters);
  end;

  PrintExampleOptimizationResult('MultipleDepotMultipleDriver', Result, ErrorString);
end;
end.
////////////////////////////////////////////////////////////////////////////////
// Multiple Depot, Multiple Driver
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("addr.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }

    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    Json::Value params(Json::objectValue);
    params["route_name"] = "Multiple Depot, Multiple Driver";
    params["algorithm_type"] = CRoute4Me::CVRP_TW_MD;
    params["route_time"] = 0;
    params["route_max_duration"] = 2*86400;
    params["optimize"] = "Time";
    params["distance_unit"] = CRoute4Me::MI;
    params["travel_mode"] = CRoute4Me::Driving;
    params["store_route"] = 1;
    params["device_type"] = CRoute4Me::Web;
    params["vehicle_capacity"] = 99;
    params["vehicle_max_distance_mi"] = 99999;
    params["share_route"] = 0;
    params["metric"] = CRoute4Me::ROUTE4ME_METRIC_GEODESIC;
    params["parts"] = 10;
    params["rt"] = 1;
    int ret = 0;
    Json::Value addr;
    inf >> addr;
    if(route.run_optimization(addr, params) == 0)
    {
        // use Json::StyledWriter instead of Json::FastWriter for a human friendly output
        cout << "Multiple Depot, Multiple Driver:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Err: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include <json.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

#define ADD_ADDRESS(x) json_object_array_add(addrs, point##x)

int main(int argc, char* argv[])
{
    int i;
    init(key, 1);

    json_object* point1 = json_object_new_object();
    json_object_object_add(point1, "address", json_object_new_string("455 S 4th St, Louisville, KY 40202"));
    json_object_object_add(point1, "lng", json_object_new_double(-85.757308));
    json_object_object_add(point1, "lat", json_object_new_double(38.251698));
    json_object_object_add(point1, "is_depot", json_object_new_boolean(TRUE));
    json_object_object_add(point1, "time", json_object_new_int(300));
    json_object_object_add(point1, "time_window_start", json_object_new_int(28800));
    json_object_object_add(point1, "time_window_end", json_object_new_int(30477));

    json_object* point2 = json_object_new_object();
    json_object_object_add(point2, "address", json_object_new_string("1604 PARKRIDGE PKWY, Louisville, KY, 40214"));
    json_object_object_add(point2, "lng", json_object_new_double(-85.793846));
    json_object_object_add(point2, "lat", json_object_new_double(38.141598));
    json_object_object_add(point2, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point2, "time", json_object_new_int(300));
    json_object_object_add(point2, "time_window_start", json_object_new_int(30477));
    json_object_object_add(point2, "time_window_end", json_object_new_int(33406));

    json_object* point3 = json_object_new_object();
    json_object_object_add(point3, "address", json_object_new_string("1407 א53MCCOY, Louisville, KY, 40215"));
    json_object_object_add(point3, "lng", json_object_new_double(-85.786514));
    json_object_object_add(point3, "lat", json_object_new_double(38.202496));
    json_object_object_add(point3, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point3, "time", json_object_new_int(300));
    json_object_object_add(point3, "time_window_start", json_object_new_int(33406));
    json_object_object_add(point3, "time_window_end", json_object_new_int(36228));

    json_object* point4 = json_object_new_object();
    json_object_object_add(point4, "address", json_object_new_string("4805 BELLEVUE AVE, Louisville, KY, 40215"));
    json_object_object_add(point4, "lng", json_object_new_double(-85.774864));
    json_object_object_add(point4, "lat", json_object_new_double(38.178844));
    json_object_object_add(point4, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point4, "time", json_object_new_int(300));
    json_object_object_add(point4, "time_window_start", json_object_new_int(36228));
    json_object_object_add(point4, "time_window_end", json_object_new_int(37518));

    json_object* point5 = json_object_new_object();
    json_object_object_add(point5, "address", json_object_new_string("730 CECIL AVENUE, Louisville, KY, 40211"));
    json_object_object_add(point5, "lng", json_object_new_double(-85.821121));
    json_object_object_add(point5, "lat", json_object_new_double(38.248684));
    json_object_object_add(point5, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point5, "time", json_object_new_int(300));
    json_object_object_add(point5, "time_window_start", json_object_new_int(37518));
    json_object_object_add(point5, "time_window_end", json_object_new_int(39550));

    json_object* point6 = json_object_new_object();
    json_object_object_add(point6, "address", json_object_new_string("650 SOUTH 29TH ST UNIT 315, Louisville, KY, 40211"));
    json_object_object_add(point6, "lng", json_object_new_double(-85.800034));
    json_object_object_add(point6, "lat", json_object_new_double(38.251923));
    json_object_object_add(point6, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point6, "time", json_object_new_int(300));
    json_object_object_add(point6, "time_window_start", json_object_new_int(39550));
    json_object_object_add(point6, "time_window_end", json_object_new_int(41348));

    json_object* point7 = json_object_new_object();
    json_object_object_add(point7, "address", json_object_new_string("4629 HILLSIDE DRIVE, Louisville, KY, 40216"));
    json_object_object_add(point7, "lng", json_object_new_double(-85.824638));
    json_object_object_add(point7, "lat", json_object_new_double(38.176067));
    json_object_object_add(point7, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point7, "time", json_object_new_int(300));
    json_object_object_add(point7, "time_window_start", json_object_new_int(41348));
    json_object_object_add(point7, "time_window_end", json_object_new_int(42261));

    json_object* point8 = json_object_new_object();
    json_object_object_add(point8, "address", json_object_new_string("4738 BELLEVUE AVE, Louisville, KY, 40215"));
    json_object_object_add(point8, "lng", json_object_new_double(-85.775558));
    json_object_object_add(point8, "lat", json_object_new_double(38.179806));
    json_object_object_add(point8, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point8, "time", json_object_new_int(300));
    json_object_object_add(point8, "time_window_start", json_object_new_int(42261));
    json_object_object_add(point8, "time_window_end", json_object_new_int(45195));

    json_object* point9 = json_object_new_object();
    json_object_object_add(point9, "address", json_object_new_string("318 SO. 39TH STREET, Louisville, KY, 40212"));
    json_object_object_add(point9, "lng", json_object_new_double(-85.815094));
    json_object_object_add(point9, "lat", json_object_new_double(38.259335));
    json_object_object_add(point9, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point9, "time", json_object_new_int(300));
    json_object_object_add(point9, "time_window_start", json_object_new_int(45195));
    json_object_object_add(point9, "time_window_end", json_object_new_int(46549));

    json_object* point10 = json_object_new_object();
    json_object_object_add(point10, "address", json_object_new_string("1324 BLUEGRASS AVE, Louisville, KY, 40215"));
    json_object_object_add(point10, "lng", json_object_new_double(-85.785118));
    json_object_object_add(point10, "lat", json_object_new_double(38.179253));
    json_object_object_add(point10, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point10, "time", json_object_new_int(300));
    json_object_object_add(point10, "time_window_start", json_object_new_int(46549));
    json_object_object_add(point10, "time_window_end", json_object_new_int(47353));

    json_object* point11 = json_object_new_object();
    json_object_object_add(point11, "address", json_object_new_string("7305 ROYAL WOODS DR, Louisville, KY, 40214"));
    json_object_object_add(point11, "lng", json_object_new_double(-85.792854));
    json_object_object_add(point11, "lat", json_object_new_double(38.162472));
    json_object_object_add(point11, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point11, "time", json_object_new_int(300));
    json_object_object_add(point11, "time_window_start", json_object_new_int(47353));
    json_object_object_add(point11, "time_window_end", json_object_new_int(50924));

    json_object* point12 = json_object_new_object();
    json_object_object_add(point12, "address", json_object_new_string("1661 W HILL ST, Louisville, KY, 40210"));
    json_object_object_add(point12, "lng", json_object_new_double(-85.783966));
    json_object_object_add(point12, "lat", json_object_new_double(38.229584));
    json_object_object_add(point12, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point12, "time", json_object_new_int(300));
    json_object_object_add(point12, "time_window_start", json_object_new_int(50924));
    json_object_object_add(point12, "time_window_end", json_object_new_int(51392));

    json_object* point13 = json_object_new_object();
    json_object_object_add(point13, "address", json_object_new_string("3222 KINGSWOOD WAY, Louisville, KY, 40216"));
    json_object_object_add(point13, "lng", json_object_new_double(-85.822594));
    json_object_object_add(point13, "lat", json_object_new_double(38.210606));
    json_object_object_add(point13, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point13, "time", json_object_new_int(300));
    json_object_object_add(point13, "time_window_start", json_object_new_int(51392));
    json_object_object_add(point13, "time_window_end", json_object_new_int(52451));

    json_object* point14 = json_object_new_object();
    json_object_object_add(point14, "address", json_object_new_string("1922 PALATKA RD, Louisville, KY, 40214"));
    json_object_object_add(point14, "lng", json_object_new_double(-85.796783));
    json_object_object_add(point14, "lat", json_object_new_double(38.153767));
    json_object_object_add(point14, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point14, "time", json_object_new_int(300));
    json_object_object_add(point14, "time_window_start", json_object_new_int(52451));
    json_object_object_add(point14, "time_window_end", json_object_new_int(55631));

    json_object* point15 = json_object_new_object();
    json_object_object_add(point15, "address", json_object_new_string("1314 SOUTH 26TH STREET, Louisville, KY, 40210"));
    json_object_object_add(point15, "lng", json_object_new_double(-85.796852));
    json_object_object_add(point15, "lat", json_object_new_double(38.235847));
    json_object_object_add(point15, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point15, "time", json_object_new_int(300));
    json_object_object_add(point15, "time_window_start", json_object_new_int(55631));
    json_object_object_add(point15, "time_window_end", json_object_new_int(58516));

    json_object* point16 = json_object_new_object();
    json_object_object_add(point16, "address", json_object_new_string("2135 MCCLOSKEY AVENUE, Louisville, KY, 40210"));
    json_object_object_add(point16, "lng", json_object_new_double(-85.789032));
    json_object_object_add(point16, "lat", json_object_new_double(38.218662));
    json_object_object_add(point16, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point16, "time", json_object_new_int(300));
    json_object_object_add(point16, "time_window_start", json_object_new_int(58516));
    json_object_object_add(point16, "time_window_end", json_object_new_int(61080));

    json_object* point17 = json_object_new_object();
    json_object_object_add(point17, "address", json_object_new_string("1409 PHYLLIS AVE, Louisville, KY, 40215"));
    json_object_object_add(point17, "lng", json_object_new_double(-85.781387));
    json_object_object_add(point17, "lat", json_object_new_double(38.206154));
    json_object_object_add(point17, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point17, "time", json_object_new_int(100));
    json_object_object_add(point17, "time_window_start", json_object_new_int(61080));
    json_object_object_add(point17, "time_window_end", json_object_new_int(61504));

    json_object* point18 = json_object_new_object();
    json_object_object_add(point18, "address", json_object_new_string("4504 SUNFLOWER AVE, Louisville, KY, 40216"));
    json_object_object_add(point18, "lng", json_object_new_double(-85.839149));
    json_object_object_add(point18, "lat", json_object_new_double(38.187511));
    json_object_object_add(point18, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point18, "time", json_object_new_int(300));
    json_object_object_add(point18, "time_window_start", json_object_new_int(61504));
    json_object_object_add(point18, "time_window_end", json_object_new_int(62061));

    json_object* point19 = json_object_new_object();
    json_object_object_add(point19, "address", json_object_new_string("2512 GREENWOOD AVE, Louisville, KY, 40210"));
    json_object_object_add(point19, "lng", json_object_new_double(-85.795059));
    json_object_object_add(point19, "lat", json_object_new_double(38.241405));
    json_object_object_add(point19, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point19, "time", json_object_new_int(300));
    json_object_object_add(point19, "time_window_start", json_object_new_int(62061));
    json_object_object_add(point19, "time_window_end", json_object_new_int(65012));

    json_object* point20 = json_object_new_object();
    json_object_object_add(point20, "address", json_object_new_string("5500 WILKE FARM AVE, Louisville, KY, 40216"));
    json_object_object_add(point20, "lng", json_object_new_double(-85.863319));
    json_object_object_add(point20, "lat", json_object_new_double(38.166065));
    json_object_object_add(point20, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point20, "time", json_object_new_int(300));
    json_object_object_add(point20, "time_window_start", json_object_new_int(65012));
    json_object_object_add(point20, "time_window_end", json_object_new_int(67541));

    json_object* point21 = json_object_new_object();
    json_object_object_add(point21, "address", json_object_new_string("3640 LENTZ AVE, Louisville, KY, 40215"));
    json_object_object_add(point21, "lng", json_object_new_double(-85.786201));
    json_object_object_add(point21, "lat", json_object_new_double(38.193283));
    json_object_object_add(point21, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point21, "time", json_object_new_int(300));
    json_object_object_add(point21, "time_window_start", json_object_new_int(67541));
    json_object_object_add(point21, "time_window_end", json_object_new_int(69120));

    json_object* point22 = json_object_new_object();
    json_object_object_add(point22, "address", json_object_new_string("1020 BLUEGRASS AVE, Louisville, KY, 40215"));
    json_object_object_add(point22, "lng", json_object_new_double(-85.780037));
    json_object_object_add(point22, "lat", json_object_new_double(38.17952));
    json_object_object_add(point22, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point22, "time", json_object_new_int(300));
    json_object_object_add(point22, "time_window_start", json_object_new_int(69120));
    json_object_object_add(point22, "time_window_end", json_object_new_int(70572));

    json_object* point23 = json_object_new_object();
    json_object_object_add(point23, "address", json_object_new_string("123 NORTH 40TH ST, Louisville, KY, 40212"));
    json_object_object_add(point23, "lng", json_object_new_double(-85.814156));
    json_object_object_add(point23, "lat", json_object_new_double(38.26498));
    json_object_object_add(point23, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point23, "time", json_object_new_int(300));
    json_object_object_add(point23, "time_window_start", json_object_new_int(70572));
    json_object_object_add(point23, "time_window_end", json_object_new_int(73177));

    json_object* point24 = json_object_new_object();
    json_object_object_add(point24, "address", json_object_new_string("7315 ST ANDREWS WOODS CIRCLE UNIT 104, Louisville, KY, 40214"));
    json_object_object_add(point24, "lng", json_object_new_double(-85.802867));
    json_object_object_add(point24, "lat", json_object_new_double(38.151072));
    json_object_object_add(point24, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point24, "time", json_object_new_int(300));
    json_object_object_add(point24, "time_window_start", json_object_new_int(73177));
    json_object_object_add(point24, "time_window_end", json_object_new_int(75231));

    json_object* point25 = json_object_new_object();
    json_object_object_add(point25, "address", json_object_new_string("3210 POPLAR VIEW DR, Louisville, KY, 40216"));
    json_object_object_add(point25, "lng", json_object_new_double(-85.849937));
    json_object_object_add(point25, "lat", json_object_new_double(38.182594));
    json_object_object_add(point25, "is_depot", json_object_new_boolean(FALSE));
    json_object_object_add(point25, "time", json_object_new_int(300));
    json_object_object_add(point25, "time_window_start", json_object_new_int(75231));
    json_object_object_add(point25, "time_window_end", json_object_new_int(77663 ));

    json_object* addrs = json_object_new_array();    

    ADD_ADDRESS(1);
    ADD_ADDRESS(2);
    ADD_ADDRESS(3);
    ADD_ADDRESS(4);
    ADD_ADDRESS(5);
    ADD_ADDRESS(6);
    ADD_ADDRESS(7);
    ADD_ADDRESS(8);
    ADD_ADDRESS(9);
    ADD_ADDRESS(10);
    ADD_ADDRESS(11);
    ADD_ADDRESS(12);
    ADD_ADDRESS(13);
    ADD_ADDRESS(14);
    ADD_ADDRESS(15);
    ADD_ADDRESS(16);
    ADD_ADDRESS(17);
    ADD_ADDRESS(18);
    ADD_ADDRESS(19);
    ADD_ADDRESS(20);
    ADD_ADDRESS(21);
    ADD_ADDRESS(22);
    ADD_ADDRESS(23);
    ADD_ADDRESS(24);
    ADD_ADDRESS(25);

    json_object* params = json_object_new_object();
    json_object_object_add(params, "route_name", json_object_new_string("Multiple Depots Multiple Drivers Trip"));
    json_object_object_add(params, "algorithm_type", json_object_new_int(TSP));
    json_object_object_add(params, "remote_ip", json_object_new_int(0));
    json_object_object_add(params, "member_id", json_object_new_int(1));
    json_object_object_add(params, "route_time", json_object_new_int(0));
    json_object_object_add(params, "route_max_duration", json_object_new_int(86400));
    json_object_object_add(params, "optimize", json_object_new_string("Distance"));
    json_object_object_add(params, "distance_unit", json_object_new_string("mi"));
    json_object_object_add(params, "travel_mode", json_object_new_string("Driving"));
    json_object_object_add(params, "store_route", json_object_new_int(1));
    json_object_object_add(params, "device_type", json_object_new_string("web"));
    json_object_object_add(params, "vehicle_capacity", json_object_new_int(1));
    json_object_object_add(params, "vehicle_max_distance_mi", json_object_new_int(10000));
    json_object_object_add(params, "directions", json_object_new_int(1));

    if (!run_optimization(addrs, params))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

POST
/api.v4/optimization_problem.php?api_key=...&optimization_problem_id=...



See the sample JSON response of this method.


Add Addresses to Routes

a) Add an address to the specified position

Inserts an address into a route with a specific sequence number.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_id string Route ID GET
addresses array A valid JSON array of Address objects. See the Address JSON Schema as a guide. POST
optimal_position boolean If true, an address will be inserted at the optimal position of a route. POST
<job id="Insert Address Into Route Specific Destination">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of inserting an address to a specified position in the route.
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      
      jFile="insert_address_into_route_specific_destination_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
public void AddRouteDestinationInSpecificPositionTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	string route_id = tdr.SDRT_route_id;

	Assert.IsNotNull(route_id, "route_id is null...");

	// Prepare the addresses
	#region Addresses
	Address[] addresses = new Address[]
	{
		new Address() { AddressString =  "146 Bill Johnson Rd NE Milledgeville GA 31061",
						Latitude =  33.143526,
						Longitude = -83.240354,
						SequenceNo = 3,
						Time = 0 }
	};
	#endregion

	// Run the query
	bool optimalPosition = false;
	string errorString;
	int[] destinationIds = route4Me.AddRouteDestinations(route_id, addresses, optimalPosition, out errorString);

	Assert.IsInstanceOfType(destinationIds, typeof(System.Int32[]), "AddRouteDestinationsTest failed...");
}
Public Sub AddRouteDestinationInSpecificPositionTest()
	Dim route4Me As New Route4MeManager(c_ApiKey)

	Dim route_id As String = tdr.SDRT_route_id

	Assert.IsNotNull(route_id, "route_id is null...")

	' Prepare the addresses

	Dim addresses As Address() = New Address() {New Address() With { _
		.AddressString = "146 Bill Johnson Rd NE Milledgeville GA 31061", _
		.Latitude = 33.143526, _
		.Longitude = -83.240354, _
		.SequenceNo = 3, _
		.Time = 0 _
	}}

	' Run the query
	Dim optimalPosition As Boolean = False
	Dim errorString As String = ""
	Dim destinationIds As Integer() = route4Me.AddRouteDestinations(route_id, addresses, errorString)

	Assert.IsInstanceOfType(destinationIds, GetType(System.Int32()), "AddRouteDestinationsTest failed...")

End Sub
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    optimization = r4m.optimization
    address = r4m.address
    optimization.algorithm_type(ALGORITHM_TYPE.TSP)
    optimization.share_route(0)
    optimization.store_route(0)
    optimization.route_time(0)
    optimization.route_max_duration(86400)
    optimization.vehicle_capacity(1)
    optimization.vehicle_max_distance_mi(10000)
    optimization.route_name('Single Driver Round Trip')
    optimization.optimize(OPTIMIZE.DISTANCE)
    optimization.distance_unit(DISTANCE_UNIT.MI)
    optimization.device_type(DEVICE_TYPE.WEB)
    optimization.travel_mode(TRAVEL_MODE.DRIVING)
    address.add_address(
        address='754 5th Ave New York, NY 10019',
        lat=40.7636197,
        lng=-73.9744388,
        alias='Bergdorf Goodman',
        is_depot=1,
        time=0
    )
    address.add_address(
        address='717 5th Ave New York, NY 10022',
        lat=40.7669692,
        lng=-73.9693864,
        alias='Giorgio Armani',
        time=0
    )
    address.add_address(
        address='888 Madison Ave New York, NY 10014',
        lat=40.7715154,
        lng=-73.9669241,
        alias='Ralph Lauren Women\'s and Home',
        time=0
    )
    address.add_address(
        address='1011 Madison Ave New York, NY 10075',
        lat=40.7772129,
        lng=-73.9669,
        alias='Yigal Azrou\u00ebl',
        time=0
    )
    address.add_address(
        address='440 Columbus Ave New York, NY 10024',
        lat=40.7808364,
        lng=-73.9732729,
        alias='Frank Stella Clothier',
        time=0
    )
    address.add_address(
        address='324 Columbus Ave #1 New York, NY 10023',
        lat=40.7803123,
        lng=-73.9793079,
        alias='Liana',
        time=0
    )
    address.add_address(
        address='110 W End Ave New York, NY 10023',
        lat=40.7753077,
        lng=-73.9861529,
        alias='Toga Bike Shop',
        time=0
    )

    response = r4m.run_optimization()

    print 'Current Addresses'
    for i, address in enumerate(response.addresses):
        print 'Number {}:'.format(i)
        print '\taddress: {}'.format(address.address)
        print '\t'
    addresses = {'addresses': [{'address': '555 W 57th St New York, NY 10019',
                                'lat': 40.7718005,
                                'lng': -73.9897716,
                                'alias': 'BMW of Manhattan',
                                'time': 0
                                },
                               {'address': '57 W 57th St New York, NY 10019',
                                'lat': 40.7558695,
                                'lng': -73.9862019,
                                'alias': 'Verizon Wireless',
                                'time': 0
                                }]
                 }

    route_id = response.addresses[1].route_id

    print 'Inserting addresses in Route: {}'.format(route_id)

    response = r4m.address.insert_address_into_route(addresses, route_id)
    print 'Addresses after insert'
    for i, address in enumerate(response.addresses):
        print 'Number {}:'.format(i)
        print '\taddress: {}'.format(address.address)
        print '\t'

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.addresses;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.DataObject;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class AddAddressToRoute {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager manager = new RoutingManager(apiKey);
        try {
            List<Route> routes = manager.getRoutes(new RoutesRequest().setLimit(10));
            Route route = manager.getRoute(new RoutesRequest().setId(routes.get(0).getId()));
            DataObject obj = manager.addAddressesToRoute(routes.get(1).getId(), route.getAddresses());
            System.out.println(obj);
        } catch (APIException e) {
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the process of inserting an address to a specified position in the route.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route_id");

// Insert the address into the route's optimal position
$addresses = array();

$params = array(
    "route_id"  => $routeId,
    "addresses" => array(
        "0" => array(
            "address"      => "Cabo Rojo, Cabo Rojo 00623, Puerto Rico",
            "alias"        => "",
            "lat"          => 18.086627,
            "lng"          => -67.145735,
            "curbside_lat" => 18.086627,
            "curbside_lng" => -67.145735,
            "is_departed"  => false,
            "is_visited"   => false,
            "sequence_no" => 3
        )
    ),
    "optimal_position" => false
);

$route1 = new Route();

$result = $route1->insertAddressOptimalPosition($params);

assert(!is_null($result), "Can't insert a destination into the route");

echo " Route ID -> $routeId <br><br>";

assert(isset($result->addresses), "Can't insert a destination into the route");

foreach ($result->addresses as $address) {
    echo "Address -> ".$address->address, ", Sequence number -> ".$address->sequence_no."<br>";
}
package AddRouteDestinations;
use strict;
use warnings FATAL => 'all';
use Data::Dumper;

sub AddRouteDestinations {
    my ( $self, $routeId) = @_;

    my $route4Me = Route4MeManager->new(ExamplesInfrastructure->ApiKey);

    my $addresses = [
        Address->new(address => "146 Bill Johnson Rd NE Milledgeville GA 31061", lat => 33.143526, lng => -83.240354, time => 0, curbside_lat => undef, curbside_lng => undef),
        Address->new(address => "222 Blake Cir Milledgeville GA 31061", lat => 33.177852, lng => -83.263535, time => 0, curbside_lat => undef, curbside_lng => undef)
    ];

    my $errors;
    my @destinationIds = $route4Me->addRouteDestinations($routeId, $addresses, \$errors);

    if (@destinationIds) {
        print "AddRouteDestinations executed successfully";
        print "\n";
        printf ( "Destination IDs: %s", join( ", ", @destinationIds ) );
        print "\n";
        print "\n";
    } else {
        printf ( "AddRouteDestinations error: %s", $errors);
        print "\n";
        print "\n";
    }

    return @destinationIds;
}
1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php

SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7

:: The example demonstrates the process of inserting an address to a specified position in the route.

ECHO ON

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@insert_address_into_route_specific_destination_data.json" "%url%?route_id=%routeid%&api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php

apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7

# The example demonstrates the process of inserting an address to a specified position in the route.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@insert_address_into_route_specific_destination_data.json" "$url?route_id=$routeid&api_key=$apikey"

echo "Finished..."

sleep 15
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  addresses := []routing.Address{
    // address to be added
    routing.Address{
      AddressString: "717 5th Ave New York, NY 10021",
      Alias:         "Giorgio Armani",
      Latitude:      40.7669692,
      Longitude:     -73.9693864,
      Time:          0,
    },
  }

  do, err = service.AddRouteDestinations("route-id", addresses)
  if err != nil {
    // handle errors
    return
  }
  // do is DataObject
}
unit AddRouteDestinationsUnit;

interface

uses SysUtils, BaseOptimizationExampleUnit;

type
  TAddRouteDestinations = class(TBaseOptimizationExample)
  public
    function Execute(RouteId: String): TArray<integer>;
  end;

implementation

uses
  AddressUnit, CommonTypesUnit;

function TAddRouteDestinations.Execute(RouteId: String): TArray<integer>;
var
  Addresses: TAddressesArray;
  OptimalPosition: boolean;
  ErrorString: String;
  AddressIds: TStringArray;
  i: integer;
begin
  SetLength(Addresses, 1);
  try
    Addresses[0] := TAddress.Create(
      '146 Bill Johnson Rd NE Milledgeville GA 31061',
      33.143526, -83.240354, 0);
    Addresses[0].SequenceNo := 4;

    OptimalPosition := False;
    Result := Route4MeManager.Route.AddAddresses(
      RouteId, Addresses, OptimalPosition, ErrorString);

    WriteLn('');

    if (Length(Result) > 0) then
    begin
      WriteLn('AddRouteDestinations executed successfully');

      SetLength(AddressIds, Length(Result));
      for i := 0 to Length(Result) - 1 do
        AddressIds[i] := IntToStr(Result[i]);
      WriteLn(Format('Destination IDs: %s', [String.Join(' ', AddressIds)]));
    end
    else
      WriteLn(Format('AddRouteDestinations error: "%s"', [errorString]));
  finally
    for i := Length(Addresses) - 1 downto 0 do
      FreeAndNil(Addresses[i]);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/route.php?api_key=...&route_id=...


See the sample JSON response of this method.


b) add addresses into optimal positions

Adds an address to a route’s optimal position.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_id string Route ID GET
addresses array A valid JSON array of Address objects. See the Address JSON Schema as a guide. POST
optimal_position boolean If true, an address will be inserted at the optimal position of a route. POST
<job id="Insert Address Into Optimal Position">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of inserting an address into a route's optimal position.
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      
      jFile="insert_address_into_route_optimal_position_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php

SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7

:: The example demonstrates the process of inserting an address into a route's optimal position.

ECHO ON

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@insert_address_into_route_optimal_position_data.json" "%url%?route_id=%routeid%&api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php

apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7

# The example demonstrates the process of inserting an address into a route's optimal position.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@insert_address_into_route_optimal_position_data.json" "$url?route_id=$routeid&api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public int[] AddRouteDestinations(string routeId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Prepare the addresses
      Address[] addresses = new Address[]
      {
        #region Addresses

        new Address() { AddressString =  "146 Bill Johnson Rd NE Milledgeville GA 31061",
                        Latitude =  33.143526,
                        Longitude = -83.240354,
                        Time = 0 },

        new Address() { AddressString =  "222 Blake Cir Milledgeville GA 31061",
                        Latitude =  33.177852,
                        Longitude = -83.263535,
                        Time = 0 }

        #endregion
      };

      // Run the query
      bool optimalPosition = true;
      string errorString;
      int[] destinationIds = route4Me.AddRouteDestinations(routeId, addresses, optimalPosition, out errorString);

      Console.WriteLine("");

      if (destinationIds != null)
      {
        Console.WriteLine("AddRouteDestinations executed successfully");

        Console.WriteLine("Destination IDs: {0}", string.Join(" ", destinationIds));
      }
      else
      {
        Console.WriteLine("AddRouteDestinations error: {0}", errorString);
      }

      return destinationIds;
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Function InsertAddressIntoRouteOptimalPosition(routeId As String) As Integer()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Prepare the addresses

            Dim addresses As Address() = New Address() {New Address() With { _
                .AddressString = "Cabo Rojo, Cabo Rojo 00623, Puerto Rico", _
                .Alias = "", _
                .Latitude = 18.086627, _
                .Longitude = -67.145735, _
                .CurbsideLatitude = 18.086627, _
                .CurbsideLongitude = -67.145735, _
                .ContactId = Nothing, _
                .IsDeparted = False, _
                .IsVisited = False
            }}

            Dim OptimalPosition As Boolean = True

            ' Run the query
            Dim errorString As String = ""

            Dim destinationIds As Integer() = route4Me.InsertAddressIntoRouteOptimalPosition(routeId, addresses, OptimalPosition, errorString)

            Console.WriteLine("")

            If destinationIds IsNot Nothing Then
                Console.WriteLine("AddRouteDestinations executed successfully")

                Console.WriteLine("Destination IDs: {0}", String.Join(" ", destinationIds))
            Else
                Console.WriteLine("AddRouteDestinations error: {0}", errorString)
            End If

            Return destinationIds
        End Function
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    route = r4m.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Route ID: {}'.format(response.route_id)
            data = {"addresses": [{"address": "Cabo Rojo, Cabo Rojo 00623, Puerto Rico",
                                   "alias": "",
                                   "lat": 18.086627,
                                   "lng": -67.145735,
                                   "curbside_lat": 18.086627,
                                   "curbside_lng": -67.145735,
                                   "contact_id": False,
                                   "is_departed": False,
                                   "is_visited": False
                                   }],
                    "optimal_position": True,
                    "route_id": response.route_id}
            response = route.insert_address_into_route_optimal_position(**data)
            print 'Optimization Problem ID: {}'.format(response.optimization_problem_id)
            print 'Route ID: {}'.format(response.route_id)
            for i, address in enumerate(response.addresses):
                print 'Address #{}'.format(i)
                print '\tAddress: {0}'.format(address.address)
                print '\tRoute Destination ID: {0}'.format(address.route_destination_id)

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    updated, err := service.UpdateRoute(&routing.Route{
        ID:        "route-id",
        Addresses: []Address{
        // addresses to add
        },
        OptimalPosition: true,
    })
    if err != nil {
        // handle errors
        return
    }
    // do something with the updated route
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the process of inserting an address into a route's optimal position.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route_id");

// Insert the address into the route's optimal position
$addresses = array();

$params = array(
    "route_id"  => $routeId,
    "addresses" => array(
        "0" => array(
            "address"      => "Cabo Rojo, Cabo Rojo 00623, Puerto Rico",
            "alias"        => "",
            "lat"          => 18.086627,
            "lng"          => -67.145735,
            "curbside_lat" => 18.086627,
            "curbside_lng" => -67.145735,
            "is_departed"  => false,
            "is_visited"   => false
        )
    ),
    "optimal_position" => true
);

$route1 = new Route();

$result = $route1->insertAddressOptimalPosition($params);

assert(!is_null($result), "Can't insert a destination into the route");

echo " Route ID -> $routeId <br><br>";

assert(isset($result->addresses), "Can't insert a destination into the route");

foreach ($result->addresses as $address) {
  echo "Address -> ".$address->address , ", Sequence number -> ".$address->sequence_no."<br>";
}
unit AddRouteDestinationsOptimallyUnit;

interface

uses SysUtils, BaseOptimizationExampleUnit;

type
  TAddRouteDestinationsOptimally = class(TBaseOptimizationExample)
  public
    function Execute(RouteId: String): TArray<integer>;
  end;

implementation

uses
  AddressUnit, CommonTypesUnit;

function TAddRouteDestinationsOptimally.Execute(RouteId: String): TArray<integer>;
var
  Addresses: TAddressesArray;
  OptimalPosition: boolean;
  ErrorString: String;
  AddressIds: TStringArray;
  i: integer;
begin
  SetLength(Addresses, 2);
  try
    Addresses[0] := TAddress.Create(
      '146 Bill Johnson Rd NE Milledgeville GA 31061',
      33.143526, -83.240354, 0);
    Addresses[1] := TAddress.Create(
      '222 Blake Cir Milledgeville GA 31061',
      33.177852, -83.263535, 0);

    OptimalPosition := True;
    Result := Route4MeManager.Route.AddAddresses(
      RouteId, Addresses, OptimalPosition, ErrorString);

    WriteLn('');

    if (Length(Result) > 0) then
    begin
      WriteLn('AddRouteDestinations executed successfully');

      SetLength(AddressIds, Length(Result));
      for i := 0 to Length(Result) - 1 do
        AddressIds[i] := IntToStr(Result[i]);
      WriteLn(Format('Destination IDs: %s', [String.Join(' ', AddressIds)]));
    end
    else
      WriteLn(Format('AddRouteDestinations error: "%s"', [errorString]));
  finally
    for i := Length(Addresses) - 1 downto 0 do
      FreeAndNil(Addresses[i]);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("add_address_to_route.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";
    const char *route_destination_id = "174405709A";

    Json::Value addr;
    inf >> addr;

    int ret = route.add_route_destinations(route_id, addr);
    if (ret == 0)
      cout << "Address added" << endl;
    else
      cout << "Error adding address" << endl;

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/route.php?api_key=...&route_id=...


See the sample JSON response of this method.


Remove Addresses from Routes

Removes an address from a route.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
route_destination_id integer Route destination ID
<job id="RemoveDestinationFromRoute">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address.php"
      apikey="11111111111111111111111111111111"
      ri="5C15E83A4BE005BCD1537955D28D51D7"
      rdi="154456307"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&ri
      url=url&"&route_destination_id="&rdi

      jFile=""
      
      Set r4m=New Route4Me
      
      r4m.HttpDeleteRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF
SET url=https://api.route4me.com
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET routedestinationid=160955262

ECHO ON

curl -o file1.txt -g -X DELETE -k "%url%/api.v4/address.php?api_key=%apikey%&route_id=%torouteid%&route_destination_id=%routedestinationid%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
routedestinationid=160955262

curl -o file1.txt -g -X DELETE -k "$url?api_key=$apikey&route_id=$torouteid&route_destination_id=$routedestinationid"

echo "Finished.."

sleep 15
package com.route4me.sdk.examples.addresses;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Address;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class DeleteAddress {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager manager = new RoutingManager(apiKey);
        try {
            Address addr = null;
            List<Route> routes = manager.getRoutes(new RoutesRequest().setLimit(64));
            for (Route r : routes) {
                Route full = manager.getRoute(new RoutesRequest().setId(r.getId()));
                if (full.getAddresses().isEmpty()) {
                    continue;
                }
                for (Address add : full.getAddresses()) {
                    if (!add.getDepot()) {
                        addr = add;
                        break;
                    }
                }
                if (addr == null) {
                    throw new RuntimeException("Can't find an address for delete operation");
                }
            }
            manager.deleteAddress(addr.getOptimizationProblemId(), addr.getRouteDestinationId());
        } catch (APIException e) {
            // handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\OptimizationProblem;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route from test routes
$route = new Route();

$route_id = $route->getRandomRouteId(0, 10);

assert(!is_null($route_id), "Can't retrieve random route_id");

// Get random destination from selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($route_id);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

echo "route_destination_id = $route_destination_id <br>";

// Remove the destination from the route
$address = new Address();

$address->route_id = $route_id;
$address->route_destination_id = $route_destination_id;
$result = $address->deleteAddress();

var_dump($result);
package RemoveRouteDestination;
use strict;
use warnings FATAL => 'all';
use Data::Dumper;

sub RemoveRouteDestination {
    my ( $self, $routeId, $destinationId, $errors ) = @_;

    my $route4Me = Route4MeManager->new(ExamplesInfrastructure->ApiKey);

    my $errorString = "";

    my $deleted = $route4Me->removeRouteDestination($routeId, $destinationId, $errorString);

    if ($deleted) {
        print "RemoveRouteDestination executed successfully";
        print "\n";
        printf "Destination ID: %s", $destinationId;
        print "\n";
    } else {
        printf "RemoveRouteDestination error: %s", $errorString;
        print "\n";
    }
    print "\n";
}
1;
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void RemoveRouteDestination(string routeId, int destinationId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Run the query
      string errorString;
      bool deleted = route4Me.RemoveRouteDestination(routeId, destinationId, out errorString);

      Console.WriteLine("");

      if (deleted)
      {
        Console.WriteLine("RemoveRouteDestination executed successfully");

        Console.WriteLine("Destination ID: {0}", destinationId);
      }
      else
      {
        Console.WriteLine("RemoveRouteDestination error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub RemoveRouteDestination(routeId As String, destinationId As Integer)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim deleted As Boolean = route4Me.RemoveRouteDestination(routeId, destinationId, errorString)

            Console.WriteLine("")

            If deleted Then
                Console.WriteLine("RemoveRouteDestination executed successfully")

                Console.WriteLine("Destination ID: {0}", destinationId)
            Else
                Console.WriteLine("RemoveRouteDestination error: {0}", errorString)
            End If

        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    optimization = r4m.optimization
    address = r4m.address
    optimization.algorithm_type(ALGORITHM_TYPE.TSP)
    optimization.share_route(0)
    optimization.store_route(0)
    optimization.route_time(0)
    optimization.route_max_duration(86400)
    optimization.vehicle_capacity(1)
    optimization.vehicle_max_distance_mi(10000)
    optimization.route_name('Single Driver Round Trip')
    optimization.optimize(OPTIMIZE.DISTANCE)
    optimization.distance_unit(DISTANCE_UNIT.MI)
    optimization.device_type(DEVICE_TYPE.WEB)
    optimization.travel_mode(TRAVEL_MODE.DRIVING)
    address.add_address(
        address='754 5th Ave New York, NY 10019',
        lat=40.7636197,
        lng=-73.9744388,
        alias='Bergdorf Goodman',
        is_depot=1,
        time=0
    )
    address.add_address(
        address='717 5th Ave New York, NY 10022',
        lat=40.7669692,
        lng=-73.9693864,
        alias='Giorgio Armani',
        time=0
    )
    address.add_address(
        address='888 Madison Ave New York, NY 10014',
        lat=40.7715154,
        lng=-73.9669241,
        alias='Ralph Lauren Women\'s and Home',
        time=0
    )
    address.add_address(
        address='1011 Madison Ave New York, NY 10075',
        lat=40.7772129,
        lng=-73.9669,
        alias='Yigal Azrou\u00ebl',
        time=0
    )
    address.add_address(
        address='440 Columbus Ave New York, NY 10024',
        lat=40.7808364,
        lng=-73.9732729,
        alias='Frank Stella Clothier',
        time=0
    )
    address.add_address(
        address='324 Columbus Ave #1 New York, NY 10023',
        lat=40.7803123,
        lng=-73.9793079,
        alias='Liana',
        time=0
    )
    address.add_address(
        address='110 W End Ave New York, NY 10023',
        lat=40.7753077,
        lng=-73.9861529,
        alias='Toga Bike Shop',
        time=0
    )

    response = r4m.run_optimization()

    print 'Current Addresses'
    for i, address in enumerate(response.addresses):
        print 'Number {}:'.format(i)
        print '\taddress: {}'.format(address.address)
        print '\t'

    route_id = response.addresses[1].route_id
    route_destination_id = response.addresses[1].route_destination_id

    print 'Deleting address {0} from Route: {1}'.format(route_destination_id, route_id)

    response = r4m.address.delete_address_from_route(route_id, route_destination_id)
    print 'Address ID: {1} deleted: {0}'.format(response.deleted, response.route_destination_id)

if __name__ == '__main__':
    main()
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  boolean, err := service.RemoveRouteDestination("route-id", "route-destination-id")
  if err != nil {
    // handle error
    return
  }
}
unit RemoveRouteDestinationUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TRemoveRouteDestination = class(TBaseExample)
  public
    procedure Execute(RouteId: String; DestinationId: integer);
  end;

implementation

procedure TRemoveRouteDestination.Execute(RouteId: String; DestinationId: integer);
var
  ErrorString: String;
  Deleted: boolean;
begin
  Deleted := Route4MeManager.Route.Remove(RouteId, DestinationId, ErrorString);

  WriteLn('');

  if (Deleted) then
  begin
    WriteLn('RemoveRouteDestination executed successfully');
    WriteLn(Format('Destination ID: %d', [DestinationId]));
  end
  else
    WriteLn(Format('RemoveRouteDestination error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("add_address_to_route.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";
    const char *route_destination_id = "174405709A";

    Json::Value addr;
    inf >> addr;

    ret = route.remove_address_from_route(route_id, route_destination_id);
    if (ret == 0)
      cout << "Address removed" << endl;
    else
      cout << "Error removing address :"  << Json::FastWriter().write(route.get_json_resp()) << endl;

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api.v4/address.php?api_key=...&route_id=...&route_destination_id=...

You can expect this API response:

{
    "deleted": true,
    "route_destination_id": 160955262
}

Get a Route

Get a single route.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
notes integer If 1, show the route notes
device_tracking_history integer If 1, show the route tracking history
directions integer If 1, show the route directions
original integer If 1, show original route
order_inventory integer If 1, show order inventory
route_path_output integer If 1, show route path
compress_path_points boolean If true, the path points in the response will be compressed.
<job id="Get Single Route">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of getting a route.
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="3A2DD89E6E1A044B2098AD1313E3138C"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest url
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetRoute(string routeId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      RouteParametersQuery routeParameters = new RouteParametersQuery()
      {
        RouteId = routeId
      };

      // Run the query
      string errorString;
      DataObjectRoute dataObject = route4Me.GetRoute(routeParameters, out errorString);

      Console.WriteLine("");

      if (dataObject != null)
      {
        Console.WriteLine("GetRoute executed successfully");

        Console.WriteLine("Route ID: {0}", dataObject.RouteID);
        Console.WriteLine("State: {0}", dataObject.State);
      }
      else
      {
        Console.WriteLine("GetRoute error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetRoute(routeId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim routeParameters As New RouteParametersQuery() With { _
                .RouteId = routeId _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As DataObjectRoute = route4Me.GetRoute(routeParameters, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("GetRoute executed successfully")

                Console.WriteLine("Route ID: {0}", dataObject.RouteID)

                Console.WriteLine("State: {0}", dataObject.State)
            Else
                Console.WriteLine("GetRoute error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
#!/usr/bin/python

from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    route = r4m.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Optimization Problem ID: {}'.format(response.optimization_problem_id)
            print 'Route ID: {}'.format(response.route_id)
            for i, address in enumerate(response.addresses):
                print 'Address #{}'.format(i)
                print '\tAddress: {0}'.format(address.address)
                print '\tRoute Destination ID: {0}'.format(address.route_destination_id)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.routes;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Address;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

/**
 * @author juan
 */
public class GetRoute {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager routeManager = new RoutingManager(apiKey);
        try {
            List<Route> routes = routeManager.getRoutes(new RoutesRequest().setLimit(10));
            //fetches complete data
            Route r = routeManager.getRoute(new RoutesRequest().setId(routes.get(0).getId()));
            System.out.println(r);
            for (Address address : r.getAddresses()) {
                    System.out.println("Address: " + address.getAddress() + " Running Distance: " + address.getManifest().get("running_distance"));
            }
        } catch (APIException e) {
            //handle exceptions
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Can't retrieve a random route ID");

// get a route by ID
$routeResults = (array)$route->getRoutes(array('route_id' => $route_id));

Route4Me::simplePrint($routeResults, true);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  route, err = service.GetRoute(&routing.RouteQuery{ID: route-id})
  if err != nil {
    // handle errors
    return
  }
}
package GetRoute;
use strict;
use warnings FATAL => 'all';

sub GetRoute {
    my ($self, $routeId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $routeParameters = RouteParametersQuery->new( {
            route_id => $routeId
        } );

    my $errorString = "";

    my $dataObject = $route4Me->getRoute( $routeParameters, \$errorString );

    print "\n";

    if ($dataObject) {
        print "GetRoute executed successfully\n";
        printf "Route ID: %s\n", $dataObject->route_id;
        printf "State: %s\n", OptimizationState->get_optimization_state( $dataObject->state );
    } else {
        printf "GetRoute error: %s\n", $errorString;
    }
}
1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET routeid=C896D0DB99C57B483D9F51B97260DCB5

:: The example demonstrates the process of getting a route.

ECHO ON

curl -o file1.txt -g -k -X GET "%url%?route_id=%routeid%&api_key=%apikey%" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid=3A2DD89E6E1A044B2098AD1313E3138C

# The example demonstrates the process of getting a route.

curl -o file1.txt -g -X GET "$url?route_id=$routeid&api_key=$apikey" 

echo "Finished..."

sleep 15
unit GetRouteUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetRoute = class(TBaseExample)
  public
    procedure Execute(RouteId: String; GetRouteDirections, GetRoutePathPoints: boolean);
  end;

implementation
uses RouteParametersQueryUnit, DataObjectUnit, EnumsUnit;
procedure TGetRoute.Execute(RouteId: String; GetRouteDirections,
  GetRoutePathPoints: boolean);
var
  ErrorString: String;
  Route: TDataObjectRoute;
begin
  Route := Route4MeManager.Route.Get(
    RouteId, GetRouteDirections, GetRoutePathPoints, ErrorString);

  WriteLn('');
  try
    if (Route <> nil) then
    begin
      WriteLn('GetRoute executed successfully');
      WriteLn(Format('Route ID: %s', [Route.RouteId]));
      WriteLn(Format('State: %s',
        [TOptimizationDescription[TOptimizationState(Route.State)]]));
      if (Length(Route.Directions) > 0) then
        WriteLn(Format('Directions: length = %d', [Length(Route.Directions)]));
      if (Length(Route.Path) > 0) then
        WriteLn(Format('Path: length = %d', [Length(Route.Path)]));
    end
    else
      WriteLn(Format('GetRoute error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Route);
  end;
end;
end.
////////////////////////////////////////////////////////////////////////////////
// Gets a Route info by ID
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "AC16E7D338B551013FF34266FE81A5EE";
    int ret = 0;
    if(route.get_route_by_id(route_id) == 0)
    {
        // use Json::StyledWriter instead of Json::FastWriter for a human friendly output
        cout << "Route " << route_id << " info by ID:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Err: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
"use strict"

const path = require("path")
const debug = require("debug")("route4me-node:examples")

require("../init-examples-suite")
const helper  = require("./../../test/helper")

helper.describeIntegration(helper.toSuiteName(__filename), function T() {
  this.timeout(5000)
  this.slow(3000)
  it(path.basename(__filename), (done) => {
    // const Route4Me = require("route4me-node")

    const apiKey   = "11111111111111111111111111111111"
    const route4me = new Route4Me(apiKey)

    const routeId = "C896D0DB99C57B483D9F51B97260DCB5"
    route4me.Routes.get(routeId, (err, route) => {
      debug("error  ", err)
      debug("result ", route)

      // Expectations about result
      expect(err).is.null

      expect(route).has.property("route_id", "C896D0DB99C57B483D9F51B97260DCB5")

      // TODO: remove `done` call from examples
      done()
    })
  })
})
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char route_id[] = "AC16E7D338B551013FF34266FE81A5EE";
    init(key, 1);

    if (!get_route_by_id(route_id))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api.v4/route.php?api_key=...&route_id=...


See the sample JSON response of this method.


Get Multiple Routes

a) Get a limited number of routes belonging to a user.


PARAMETERS

Parameter Type Description
api_key string API key of the user
offset integer Search starting position
limit integer The number of records to return.
<job id="Get Routes">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of getting a limited number of routes from a user's account.
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      limit="20"
      offset="100"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&limit"&limit
      url=url&"&offset"&offset
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest url
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetRoutes()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      RouteParametersQuery routeParameters = new RouteParametersQuery()
      {
        Limit = 10,
        Offset = 5
      };

      // Run the query
      string errorString;
      DataObjectRoute[] dataObjects = route4Me.GetRoutes(routeParameters, out errorString);

      Console.WriteLine("");

      if (dataObjects != null)
      {
        Console.WriteLine("GetRoutes executed successfully, {0} routes returned", dataObjects.Length);
        Console.WriteLine("");

        dataObjects.ForEach(dataObject =>
        {
          Console.WriteLine("RouteID: {0}", dataObject.RouteID);
          Console.WriteLine("");
        });
      }
      else
      {
        Console.WriteLine("GetRoutes error {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetRoutes()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim routeParameters As New RouteParametersQuery() With { _
                .Limit = 10, _
                .Offset = 5 _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObjects As DataObjectRoute() = route4Me.GetRoutes(routeParameters, errorString)

            Console.WriteLine("")

            If dataObjects IsNot Nothing Then
                Console.WriteLine("GetRoutes executed successfully, {0} routes returned", dataObjects.Length)
                Console.WriteLine("")

                For Each dataobject As DataObjectRoute In dataObjects
                    Console.WriteLine("RouteID: {0}", dataobject.RouteID)
                    Console.WriteLine("")
                Next
            Else
                Console.WriteLine("GetRoutes error {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
#!/usr/bin/python

from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    route = route4me.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        for i, route in enumerate(response):
            print 'Route #{}'.format(i+1)
            print '\tOptimization Problem ID: {}'.format(route.optimization_problem_id)
            print '\tRoute ID: {}'.format(route.route_id)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.routes;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class GetRoutes {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager routeManager = new RoutingManager(apiKey);
        try {
            List<Route> routes = routeManager.getRoutes(new RoutesRequest().setLimit(10));
            for (Route r : routes) {
                System.out.println(r);
            }
        } catch (APIException e) {
            // handle exceptions
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$RouteParameters = array(
    "limit"   => 30,
    "offset"  => 0
);

$route = new Route();

$routeResults = $route->getRoutes($RouteParameters);

foreach ($routeResults as $routeResult)
{
    $results = (array)$routeResult;

    Route4Me::simplePrint($results);
    
    echo "<br>";
}
package routing

import (
  "math/rand"
  "reflect"
  "strconv"
  "testing"
  "time"

  "github.com/route4me/route4me-go-sdk"
)

var client = route4me.NewClient("11111111111111111111111111111111")
var service = &Service{Client: client}

func TestIntegrationGetTeamRoutes(t *testing.T) {
  if testing.Short() {
    t.Skip("Skipping integration tests in short mode.")
  }
  _, err := service.GetTeamRoutes(&RouteQuery{Limit: 10, Offset: 5})
  if err != nil {
    t.Error(err)
    return
  }

  // Lets try and get an array as a single route (shouldn't work)
  _, err = service.GetRoute(&RouteQuery{Limit: 10, Offset: 5})
  if err == nil {
    t.Error("Array unmarshalled into a non-array type. This shouldn't happen.")
  }
}
package GetRoutes;
use strict;
use warnings FATAL => 'all';
sub GetRoutes {

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $routeParameters = RouteParametersQuery->new( {
            limit => 10,
            offset => 5
        } );

    my $errorString = "";

    my @dataObject = $route4Me->getRoutes( $routeParameters, \$errorString );

    print "\n";

    if (@dataObject) {
        printf "GetRoutes executed successfully, %s routes returned\n\n", scalar @dataObject;

        foreach my $route (@dataObject) {
            printf "Route ID: %s\n", $route->route_id;
        }

    } else {
        printf "GetRoutes error: %s\n", $errorString;
    }
}
1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111

:: The example demonstrates the process of getting a limited number of routes from a user's account.

ECHO ON
curl -o file1.txt -g -k -X GET "%url%?api_key=%apikey%&limit=20&offset=100" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
limit=20
offset=100

# The example demonstrates the process of getting a limited number of routes from a user's account.

curl -o file1.txt -g -X GET "$url?api_key=$apikey&limit=$limit&offset=$offset" 

echo "Finished..."

sleep 15
unit GetRoutesUnit;

interface

uses SysUtils, BaseExampleUnit, DataObjectUnit;

type
  TGetRoutes = class(TBaseExample)
  public
    function Execute: TDataObjectRouteArray;
  end;

implementation

uses RouteParametersQueryUnit;

function TGetRoutes.Execute: TDataObjectRouteArray;

var
  Parameters: TRouteParametersQuery;
  ErrorString: String;
  Route: TDataObjectRoute;
  i: integer;
begin
  Parameters := TRouteParametersQuery.Create();
  try
    Parameters.Limit := 10;
    Parameters.Offset := 5;

    Result := Route4MeManager.Route.GetList(Parameters, ErrorString);
    WriteLn('');

    if (Length(Result) > 0) then
    begin
      WriteLn(Format('GetRoutes executed successfully, %d routes returned',
        [Length(Result)]));
      WriteLn('');

      for Route in Result do
        WriteLn(Format('RouteId: %s', [Route.RouteId]));
    end
    else
      WriteLn(Format('GetRoutes error "%s"', [ErrorString]));
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
////////////////////////////////////////////////////////////////////////////////
// Gets a Route info by ID
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();
    CRoute4Me route(KEY);

    int ret = 0;
    if(route.get_multiple_routes() == 0)
    {
        cout << "All routes:" << endl << Json::StyledWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Error: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }
    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);

    if (!get_multiple_routes())
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api.v4/route.php?api_key=...&offset=...&limit=...


See the sample JSON response of this method.


b) Get the routes scheduled for the specified date range.


PARAMETERS

Parameter Type Description
api_key string API key of the user
start_date string Start date (e.g. 2019-09-18)
end_date string Start date (e.g. 2019-09-18)
<job id="View Routes">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example refers to the process of getting the routes scheduled for the specified date range.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/route.php"
			apikey="11111111111111111111111111111111"
			start_date="2019-08-01"
			end_date="2019-08-05"
			
			url=url&"?api_key="&apikey
			url=url&"&strat_date="&start_date
			url=url&"&limit"&end_date
			
			Set r4m=New Route4Me
			r4m.OutputFile="get_routes_from_date_range_RESPONSE.json"
			
			r4m.HttpGetRequest url
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET "start_date=2019-08-01"
SET "end_date=2019-08-05"

:: The example refers to the process of getting the routes scheduled for the specified date range.

ECHO ON
curl -o get_routes_from_date_range_RESPONSE.json -g -k -X GET "%url%?api_key=%apikey%&start_date=%start_date%&end_date=%end_date%" 

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
start_date="2019-08-01"
end_date="2019-08-05"

 # The example refers to the process of getting the routes scheduled for the specified date range.

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&start_date=$start_date&end_date=$end_date" 

echo "Finished..."

sleep 15
public void GetRoutesFromDateRangeTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	RouteParametersQuery routeParameters = new RouteParametersQuery()
	{
		StartDate = "2019-08-01",
		EndDate = "2019-08-05"
	};

	// Run the query
	string errorString;
	DataObjectRoute[] dataObjects = route4Me.GetRoutes(routeParameters, out errorString);

	Assert.IsInstanceOfType(dataObjects, typeof(DataObjectRoute[]), "GetRoutesFromDateRangeTest failed... " + errorString);
}
Public Sub GetRoutesFromDateRangeTest()
	Dim route4Me As New Route4MeManager(c_ApiKey)

	Dim routeParameters As New RouteParametersQuery() With {
		.StartDate = "2019-08-01",
		.EndtDate = "2019-08-05"
	}

	' Run the query
	Dim errorString As String = ""
	Dim dataObjects As DataObjectRoute() = route4Me.GetRoutes(routeParameters, errorString)

	Assert.IsInstanceOfType(dataObjects, GetType(DataObjectRoute()), Convert.ToString("GetRoutesFromDateRangeTest failed... ") & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;
$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';
// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');
$RouteParameters = [
    'start_date' => '2019-08-01',
    'end_date' => '2019-08-05'
];
$route = new Route();
$routeResults = $route->getRoutes($RouteParameters);
foreach ($routeResults as $routeResult) {
    $results = (array) $routeResult;
    Route4Me::simplePrint($results);
    echo '<br>';
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/route.php?api_key=...&start_date=...&end_date=...


See the sample JSON response of this method.


Search Routes

a) Get path points of a route


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
route_path_output string Route path output type
<job id="Get Route Path Points">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      rpo="Points"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&route_path_output="&rpo
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest url
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET routeid=4728372005DE97EF9E4205852D690E34
SET rpo=Points

:: The example demonstrates the process of getting a route with path points.

ECHO ON

curl -o file1.txt -g -X GET "%url%?route_id=%routeid%&api_key=%apikey%&route_path_output=%rpo%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid=4728372005DE97EF9E4205852D690E34
rpo=Points

# The example demonstrates the process of getting a route with path points.

curl -o file1.txt -g -X POST -H "Content-Type: application/json" -d "@new_route_data.json" "$url?api_key=$apikey&route_id=$routeid&route_path_output=$rpo"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetRoute(string routeId, bool getRouteDirections, bool getRoutePathPoints)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      RouteParametersQuery routeParameters = new RouteParametersQuery()
      {
        RouteId = routeId
      };

      if (getRouteDirections)
      {
        routeParameters.Directions = true;
      }

      if (getRoutePathPoints)
      {
        routeParameters.RoutePathOutput = RoutePathOutput.Points.ToString();
      }

      // Run the query
      string errorString;
      DataObjectRoute dataObject = route4Me.GetRoute(routeParameters, out errorString);

      Console.WriteLine("");

      if (dataObject != null)
      {
        Console.WriteLine("GetRoute executed successfully");

        Console.WriteLine("Route ID: {0}", dataObject.RouteID);
        Console.WriteLine("State: {0}", dataObject.State);
        /*foreach (Address a in dataObject.Addresses)
        {
          Console.WriteLine("addr: {0}, {1}, {2}, {3}, {4}", a.RouteDestinationId, a.Latitude, a.Longitude, a.Alias, a.AddressString);
        }*/
        if (dataObject.Directions != null)
        {
          Console.WriteLine("Directions: length = {0}", dataObject.Directions.Length);
        }
        if (dataObject.Path != null)
        {
          Console.WriteLine("Path: length = {0}", dataObject.Path.Length);
        }
      }
      else
      {
        Console.WriteLine("GetRoute error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetRoutePathPoints(routeId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim routeParameters As New RouteParametersQuery() With { _
                .RouteId = routeId, _
                .RoutePathOutput = "Points"
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As DataObjectRoute = route4Me.GetRoute(routeParameters, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("GetRoutePathPoints executed successfully")

                Console.WriteLine("Route ID: {0}", dataObject.RouteID)
                'foreach (Address a in dataObject.Addresses)
                '        {
                '          Console.WriteLine("addr: {0}, {1}, {2}, {3}, {4}", a.RouteDestinationId, a.Latitude, a.Longitude, a.Alias, a.AddressString);
                '        }

                Console.WriteLine("State: {0}", dataObject.State)
            Else
                Console.WriteLine("GetRoutePathPoints error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    route = r4m.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Route ID: {}'.format(response.route_id)
            data = {"route_path_output": 'Points',
                    "route_id": response.route_id}
            response = route.get_route_path_points(**data)
            print 'Optimization Problem ID: {}'.format(response.optimization_problem_id)
            print 'Route ID: {}'.format(response.route_id)
            for i, address in enumerate(response.addresses):
                print 'Address #{}'.format(i)
                print '\tAddress: {0}'.format(address.address)
                print '\tRoute Destination ID: {0}'.format(address.route_destination_id)
                for i, path in enumerate(address.path_to_next):
                    print '\t{0} - \tlat: {1} \tlng: {2}'.format(i + 1, path.lat, path.lng)

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  routes, err := service.GetRoute(&routing.RouteQuery{ID: "routeID", PathOutput: routing.Points})
  if err != nil {
    // handle errors
    return
  }
  // do something with routes
}
<?php
namespace Route4Me;

$root=realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Can't retrieve a random route ID");

// Note: not every optimization includes information about path points, only this, which was generated with the parameter route_path_output = "Points"  

// Get a route with path points
$params = array(
    "route_path_output" => "Points",
    "route_id"   => $route_id
);

$routeResults = (array)$route->getRoutePoints($params);

if (isset($routeResults['addresses'])) {
    foreach ($routeResults['addresses'] as $key => $address) {
        $araddress = (array)$address;

        if (isset($araddress['route_destination_id'])) echo "route_destination_id=".$araddress['route_destination_id']."<br>";
        
        if (isset($araddress['path_to_next'])) {
            echo "path_to_next:<br>";
            Route4Me::simplePrint($araddress['path_to_next']);
        }
        
        echo "<br>";
    }
}
unit GetRouteUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetRoute = class(TBaseExample)
  public
    procedure Execute(RouteId: String; GetRouteDirections, GetRoutePathPoints: boolean);
  end;

implementation
uses RouteParametersQueryUnit, DataObjectUnit, EnumsUnit;
procedure TGetRoute.Execute(RouteId: String; GetRouteDirections,
  GetRoutePathPoints: boolean);
var
  ErrorString: String;
  Route: TDataObjectRoute;
begin
  Route := Route4MeManager.Route.Get(
    RouteId, GetRouteDirections, GetRoutePathPoints, ErrorString);

  WriteLn('');
  try
    if (Route <> nil) then
    begin
      WriteLn('GetRoute executed successfully');
      WriteLn(Format('Route ID: %s', [Route.RouteId]));
      WriteLn(Format('State: %s',
        [TOptimizationDescription[TOptimizationState(Route.State)]]));
      if (Length(Route.Directions) > 0) then
        WriteLn(Format('Directions: length = %d', [Length(Route.Directions)]));
      if (Length(Route.Path) > 0) then
        WriteLn(Format('Path: length = %d', [Length(Route.Path)]));
    end
    else
      WriteLn(Format('GetRoute error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Route);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";

    if (route.get_route_path_points(route_id, "Points")) {
        cout << "Route :"  << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "Route not found :"  << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char route_id[] = "AC16E7D338B551013FF34266FE81A5EE";
    init(key, 1);

    if (!get_route_path_points(route_id, "Points"))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api.v4/route.php?api_key=...&route_id=...&route_path_output=...


See the sample JSON response of this method.


b) Get the compressed path points of a route


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
route_path_output string Route path output type
compress_path_points boolean If true, the path points in the response will be compressed.
An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET routeid=4728372005DE97EF9E4205852D690E34
SET rpo=Points
SET compress_path_points=true

:: The example demonstrates the process of getting a route with encoded and compressed path points.
:: The path compression used is called the Encoded Polyline Algorithm Format (see link: https://developers.google.com/maps/documentation/utilities/polylinealgorithm).
:: There are interactive decoder polyline utilities on the Internet (see link: https://developers.google.com/maps/documentation/utilities/polylineutility).

ECHO ON

curl -o file1.txt -g -X GET "%url%?route_id=%routeid%&api_key=%apikey%&route_path_output=%rpo%&compress_path_points=%compress_path_points%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid=4728372005DE97EF9E4205852D690E34
rpo=Points
compress_path_points=true

# The example demonstrates the process of getting a route with encoded and compressed path points.
# The path compression used is called the Encoded Polyline Algorithm Format (see link: https://developers.google.com/maps/documentation/utilities/polylinealgorithm).
# There are interactive decoder polyline utilities on the Internet (see link: https://developers.google.com/maps/documentation/utilities/polylineutility).

curl -o file1.txt -g -X POST -H "Content-Type: application/json" -d "@new_route_data.json" "$url?api_key=$apikey&route_id=$routeid&route_path_output=$rpo&compress_path_points=$compress_path_points"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root=realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Can't retrieve a random route ID");

// The example demonstrates the process of getting a route with encoded and compressed path points.

// Get a route with the path points
$params = array(
    "route_path_output"     => "Points",
    "compress_path_points"  => TRUE,
    "route_id"              => $route_id
);

$routeResults = (array)$route->getRoutePoints($params);

if (isset($routeResults['addresses'])) {
    foreach ($routeResults['addresses'] as $key => $address) {
        $araddress = (array)$address;

        if (isset($araddress['route_destination_id'])) echo "route_destination_id=".$araddress['route_destination_id']."<br>";
        
        if (isset($araddress['path_to_next'])) {
            echo "path_to_next:<br>";
            Route4Me::simplePrint((array)$araddress['path_to_next']);
        }
        
        echo "<br>";
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/route.php?api_key=...&route_id=...&&compress_path_points=...


See the sample JSON response of this method.


c) Get route directions

Edge by edge turn-by-turn directions. Note: For round-trip routes (parameters.rt = true), the return to the start address is returned as well.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
directions integer If equal to 1, returns directions.
<job id="Get Route Directions">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of getting a route with directions.
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      directions="1"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&directions="&directions
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest url
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET directions=1

:: The example demonstrates the process of getting a route with directions.

ECHO ON

curl -o file1.txt -g -k -X GET "%url%?route_id=%routeid%&api_key=%apikey%&directions=%directions%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
directions=1

# The example demonstrates the process of getting a route with directions.

curl -o file1.txt -g -k -X POST -H "Content-Type: application/json" -d "@new_route_data.json" "$url?api_key=$apikey&route_id=$routeid&directions=$directions"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetRoute(string routeId, bool getRouteDirections, bool getRoutePathPoints)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      RouteParametersQuery routeParameters = new RouteParametersQuery()
      {
        RouteId = routeId
      };

      if (getRouteDirections)
      {
        routeParameters.Directions = true;
      }

      if (getRoutePathPoints)
      {
        routeParameters.RoutePathOutput = RoutePathOutput.Points.ToString();
      }

      // Run the query
      string errorString;
      DataObjectRoute dataObject = route4Me.GetRoute(routeParameters, out errorString);

      Console.WriteLine("");

      if (dataObject != null)
      {
        Console.WriteLine("GetRoute executed successfully");

        Console.WriteLine("Route ID: {0}", dataObject.RouteID);
        Console.WriteLine("State: {0}", dataObject.State);
        /*foreach (Address a in dataObject.Addresses)
        {
          Console.WriteLine("addr: {0}, {1}, {2}, {3}, {4}", a.RouteDestinationId, a.Latitude, a.Longitude, a.Alias, a.AddressString);
        }*/
        if (dataObject.Directions != null)
        {
          Console.WriteLine("Directions: length = {0}", dataObject.Directions.Length);
        }
        if (dataObject.Path != null)
        {
          Console.WriteLine("Path: length = {0}", dataObject.Path.Length);
        }
      }
      else
      {
        Console.WriteLine("GetRoute error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetRouteDirections(routeId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim routeParameters As New RouteParametersQuery() With { _
                .RouteId = routeId, _
                .Directions = True
            }

            ' Run the query
            Dim errorString As String = ""
            Dim routeResponse As RouteResponse = route4Me.GetRouteDirections(routeParameters, errorString)

            Console.WriteLine("")

            If routeResponse IsNot Nothing Then
                Console.WriteLine("GetRouteDirections executed successfully")

                Console.WriteLine("Route ID: {0}", routeResponse.RouteID)

                Console.WriteLine("Total directions: {0}", routeResponse.Directions.Count())
            Else
                Console.WriteLine("GetRouteDirections error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    route = r4m.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Route ID: {}'.format(response.route_id)
            data = {"directions": 1,
                    "route_id": response.route_id}
            response = route.get_route_directions(**data)
            print 'Optimization Problem ID: {}'.format(response.optimization_problem_id)
            print 'Route ID: {}'.format(response.route_id)
            for i, direction in enumerate(response.directions):
                print 'Direction #{}'.format(i)
                print '\tLocation'
                print '\t\tTime: {}'.format(direction.location.time)
                print '\t\tName: {}'.format(direction.location.name)
                print '\t\tStart Location: {}'.format(direction.location.start_location)
                print '\t\tEnd Location: {}'.format(direction.location.end_location)
                print '\tSteps'
                for step in direction.steps:
                    print '\t\tDirections: {}'.format(step.directions)
                    print '\t\tDirection: {}'.format(step.direction)
                    print '\t\tDistance: {}'.format(step.distance)
                    print '\t\tDistance unit: {}'.format(step.distance_unit)
                    print '\t\tManeuver Type: {}'.format(step.maneuverType)
                    print '\t\tCompass Direction: {}'.format(step.compass_direction)
                    print '\t\tDuration sec: {}'.format(step.duration_sec)
                    print '\t\tManeuver Point'
                    print '\t\t\tLat: {}'.format(step.maneuverPoint.lat)
                    print '\t\t\tLng: {}'.format(step.maneuverPoint.lng)

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
}

routes, err := service.GetRoute(&routing.RouteQuery{ID: "routeID", Directions: true})
if err != nil {
    // handle errors
    return
}
// do something with routes
<?php
namespace Route4Me;

$root=realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Can't retrieve a random route ID");

// Note: not every optimization includes information about directions, only this, which was generated with the parameter directions = 1
  
// Get a route with the directions
$params = array(
    "directions" => 1,
    "route_id"   => $route_id
);

$routeResults = (array)$route->getRoutePoints($params);

Route4Me::simplePrint($routeResults, true);
unit GetRouteUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetRoute = class(TBaseExample)
  public
    procedure Execute(RouteId: String; GetRouteDirections, GetRoutePathPoints: boolean);
  end;

implementation
uses RouteParametersQueryUnit, DataObjectUnit, EnumsUnit;
procedure TGetRoute.Execute(RouteId: String; GetRouteDirections,
  GetRoutePathPoints: boolean);
var
  ErrorString: String;
  Route: TDataObjectRoute;
begin
  Route := Route4MeManager.Route.Get(
    RouteId, GetRouteDirections, GetRoutePathPoints, ErrorString);

  WriteLn('');
  try
    if (Route <> nil) then
    begin
      WriteLn('GetRoute executed successfully');
      WriteLn(Format('Route ID: %s', [Route.RouteId]));
      WriteLn(Format('State: %s',
        [TOptimizationDescription[TOptimizationState(Route.State)]]));
      if (Length(Route.Directions) > 0) then
        WriteLn(Format('Directions: length = %d', [Length(Route.Directions)]));
      if (Length(Route.Path) > 0) then
        WriteLn(Format('Path: length = %d', [Length(Route.Path)]));
    end
    else
      WriteLn(Format('GetRoute error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Route);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";

    if (route.get_route_directions(route_id, 1)) {
        cout << "Route :"  << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "Route not found :"  << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char route_id[] = "CA902292134DBC134EAF8363426BD247";
    init(key, 1);

    if (!get_route_directions(route_id, 1))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api.v4/route.php?api_key=...&route_id=...&directions=...


See the sample JSON response of this method.


d) Search the routes for a specified text

Search for the specified text throughout all routes belonging to the user’s account.


PARAMETERS

Parameter Type Description
api_key string API key of the user
query string The text to search for.
<job id="Search Routes">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of searching for the specified text throughout all routes belonging to the user's account.
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      query="Tbilisi"
      
      url=url&"?api_key="&apikey
      url=url&"&query="&query
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest url
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET query=Tbilisi

:: The example demonstrates the process of searching for the specified text throughout all routes belonging to the user's account.

ECHO ON

curl -o file1.txt -g -k -X GET "%URL%?query=%query%&api_key=%apikey%" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
query=Tbilisi

# The example demonstrates the process of searching for the specified text throughout all routes belonging to the user's account.

curl -o file1.txt -g -k -X GET "$url?query=$query&api_key=$apikey" 

echo "Finished.."

using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        public void SearchRoutesForText(string query)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            // The example demonstrates the process of searching for the specified text throughout all routes belonging to the user's account.

            RouteParametersQuery routeParameters = new RouteParametersQuery()
            {
                Query = query
            };

            // Run the query
            string errorString;
            DataObjectRoute[] dataObjects = route4Me.GetRoutes(routeParameters, out errorString);

            Console.WriteLine("");

            if (dataObjects != null)
            {
                Console.WriteLine("SearchRoutesForText executed successfully, {0} routes returned", dataObjects.Length);
                Console.WriteLine("");

                dataObjects.ForEach(dataObject =>
                {
                    Console.WriteLine("RouteID: {0}", dataObject.RouteID);
                    Console.WriteLine("");
                });
            }
            else
            {
                Console.WriteLine("SearchRoutesForText error {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchRoutesForText(query As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim routeParameters As New RouteParametersQuery() With { _
                .Query = query _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObjects As DataObjectRoute() = route4Me.GetRoutes(routeParameters, errorString)

            Console.WriteLine("")

            If dataObjects IsNot Nothing Then
                Console.WriteLine("SearchRoutesForText executed successfully, {0} routes returned", dataObjects.Length)
                Console.WriteLine("")

                For Each dataobject As DataObjectRoute In dataObjects
                    Console.WriteLine("RouteID: {0}", dataobject.RouteID)
                    Console.WriteLine("")
                Next
            Else
                Console.WriteLine("SearchRoutesForText error {0}", errorString)
            End If

        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    routes, err := service.GetTeamRoutes(&RouteQuery{Query: "Tbilisi"})
    if err != nil {
        // handle errors
        return
    }
    // do something with routes
}
<?php
namespace Route4Me;

$root=realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example demonstrates the process of searching for the specified text throughout all routes belonging to the user's account.

$RouteParameters = array(
    "query"   => 'Automated'
);

$route = new Route();

$routeResults = $route->getRoutes($RouteParameters);

foreach ($routeResults as $routeResult)
{
    $results = (array)$routeResult;
    
    if (isset($results['route_id'])) echo "Route ID - > " . $results['route_id'] . "<br>";
    
    if (isset($results['parameters']->route_name)) echo "Route name - > ".$results['parameters']->route_name."<br>";

    echo "<br>";
}
unit SearchRoutesForSpecifiedTextUnit;

interface

uses SysUtils, BaseExampleUnit, DataObjectUnit;

type
  TSearchRoutesForSpecifiedText = class(TBaseExample)
  public
    function Execute(Text: String): TDataObjectRouteList;
  end;

implementation
function TSearchRoutesForSpecifiedText.Execute(Text: String): TDataObjectRouteList;
var
  ErrorString: String;
  Route: TDataObjectRoute;
begin
  Result := Route4MeManager.Route.GetList(Text, ErrorString);
  WriteLn('');

  if (Result <> nil) and (Result.Count > 0) then
  begin
    WriteLn(Format('SearchRoutesForSpecifiedText executed successfully, %d routes returned',
      [Result.Count]));
    WriteLn('');

    for Route in Result do
      WriteLn(Format('RouteId: %s', [Route.RouteId]));
  end
  else
    WriteLn(Format('SearchRoutesForSpecifiedText error "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";

    if (route.get_route_query(route_id, "prog")) {
        cout << "Route :"  << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "Route not found :"  << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char route_id[] = "CA902292134DBC134EAF8363426BD247";
    init(key, 1);

    if (!get_route_query(route_id, "prog"))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api.v4/route.php?api_key=...&query=...


See the sample JSON response of this method.


Get an Address from a Route

Get an address with specified route_destination_id from a route with specified route_id.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
route_destination_id integer Route destination ID
<job id="MarkAddressAsVisited">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address.php"
      apikey="11111111111111111111111111111111"
      route_id="5C15E83A4BE005BCD1537955D28D51D7"
      rdi="160940135"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&route_id
      url=url&"&route_destination_id="&rdi
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetAddress(string routeId, int routeDestinationId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      AddressParameters addressParameters = new AddressParameters()
      {
        RouteId = routeId,
        RouteDestinationId = routeDestinationId,
        Notes = true
      };

      // Run the query
      string errorString;
      Address dataObject = route4Me.GetAddress(addressParameters, out errorString);

      Console.WriteLine("");

      if (dataObject != null)
      {
        Console.WriteLine("GetAddress executed successfully");
        Console.WriteLine("RouteId: {0}; RouteDestinationId: {1}", dataObject.RouteId, dataObject.RouteDestinationId);
        Console.WriteLine("");
      }
      else
      {
        Console.WriteLine("GetAddress error: {0}", errorString);
        Console.WriteLine("");
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetAddress(routeId As String, routeDestinationId As Integer)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim addressParameters As New AddressParameters() With { _
                .RouteId = routeId, _
                .RouteDestinationId = routeDestinationId, _
                .Notes = True _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As Address = route4Me.GetAddress(addressParameters, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("GetAddress executed successfully")
                Console.WriteLine("RouteId: {0}; RouteDestinationId: {1}", dataObject.RouteId, dataObject.RouteDestinationId)
                Console.WriteLine("")
            Else
                Console.WriteLine("GetAddress error: {0}", errorString)
                Console.WriteLine("")
            End If
        End Sub
    End Class
End Namespace
#!/usr/bin/python

from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    route = route4me.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            route_id = response.route_id
            route_destination_id = response.addresses[0].route_destination_id
            response = route4me.address.get_address(route_id=route_id, route_destination_id=route_destination_id)
            if hasattr(response, 'errors'):
                print '. '.join(response.errors)
            else:

                print 'Address: {}'.format(response.address)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.addresses;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Address;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class GetAddress {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager manager = new RoutingManager(apiKey);
        try {
            List<Route> routes = manager.getRoutes(new RoutesRequest().setLimit(10));
            Route route = manager.getRoute(new RoutesRequest().setId(routes.get(0).getId()));
            Address addr = manager.getAddress(route.getId(), route.getAddresses().get(0).getRouteDestinationId());
            System.out.println(addr);
        } catch (APIException e) {
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route_id");

// Get random address ID from selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($routeId);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

// Get the address by route_destination_id
$address = new Address();

$addressRetrieved = $address->getAddress($routeId, $route_destination_id);

Route4Me::simplePrint((array)$addressRetrieved);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  address, err = service.GetAddress(&routing.AddressQuery{RouteID: "route-id",
  RouteDestinationID: "route-destination-id",
  Notes: true, // If this is set to true, all notes associated with this address will be returned.
  })
  if err != nil {
    // handle errors
    return
  }
}
package GetAddress;
use strict;
use warnings FATAL => 'all';

use Route4MeSDK::QueryTypes::AddressParameters;

sub GetAddress {
    my ($self, $routeId, $routeDestinationId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $addressParameters = AddressParameters->new(
        route_id => $routeId,
        route_destination_id => $routeDestinationId,
        notes => 1
    );

    my $errorString;

    my $dataObject = $route4Me->getAddress($addressParameters, $errorString);

    print "\n";

    if ($dataObject) {
        print "GetAddress executed successfully\n";

        printf "RouteId: %s; RouteDestinationId: %s\n\n", $dataObject->route_id, $dataObject->route_destination_id;

    } else {
        printf "GetAddress error: %s\n", $errorString;
    }
}
1;
@ECHO OFF
SET url=https://api.route4me.com/api.v4/address.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET routedestinationid=160940135

ECHO ON
curl -o file1.txt -k -g -X GET "%URL%?api_key=%apikey%&route_id=%routeid%&route_destination_id=%routedestinationid%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
routedestinationid=160940135

curl -o file1.txt -k -g -X GET "$url?api_key=$apikey&route_id=$routeid&route_destination_id=$routedestinationid"

echo "Finished..."

sleep 15
unit GetAddressUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAddress = class(TBaseExample)
  public
    procedure Execute(RouteId: String; RouteDestinationId: integer);
  end;

implementation

uses AddressParametersUnit, AddressUnit;

procedure TGetAddress.Execute(RouteId: String; RouteDestinationId: integer);

var
  ErrorString: String;
  Parameters: TAddressParameters;
  Address: TAddress;
begin
  Parameters := TAddressParameters.Create();
  try
    Parameters.RouteId := RouteId;
    Parameters.RouteDestinationId := RouteDestinationId;
    Parameters.Notes := True;

    Address := Route4MeManager.Address.Get(Parameters, ErrorString);
    try
      WriteLn('');

      if (Address <> nil) then
      begin
        WriteLn('GetAddress executed successfully');
        WriteLn(Format('RouteId: %s; RouteDestinationId: %d',
          [Address.RouteId.Value, Address.RouteDestinationId.Value]));
      end
      else
        WriteLn(Format('GetAddress error: "%s"', [ErrorString]));
    finally
      FreeAndNil(Address);
    end;
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";
    const char *route_destination_id = "174405709A";

    int ret = route.get_address(route_id, route_destination_id);
    if (ret == 0) {
      cout << "Route address by ID:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
      cout << "Error reading address: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
      ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char route_id[] = "CA902292134DBC134EAF8363426BD247";
    char route_destination_id[] = "174405709A";
    init(key, 1);

    if (!get_address(route_id, route_destination_id))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api.v4/address.php?api_key=...&route_id=...&route_destination_id=...


See the sample JSON response of this method.


Manually Resequence a Route

Route resequence

Resequence a single destination of a route.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_id string Route ID GET
route_destination_id integer Route destination ID GET
addresses array A valid JSON array of Address objects. See the Address JSON Schema as a guide. POST
<job id="Resequence Route">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      rdi="160955261"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&route_destination_id="&rdi
      
      jFile="resequence_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET routeid=F0C842829D8799067F9BF7A495076335
SET routedestid=174389214

:: The example demonstrates the process of resequencing a specified address inside a route.

ECHO ON

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@resequence_data.json" "%url%?route_id=%routeid%&route_destination_id=%routedestid%&api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
routedestid=160955261

# The example demonstrates the process of resequencing a specified address inside a route.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@resequence_data.json" "$url?route_id=$routeid&route_destination_id=$routedestid&api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void ResequenceRouteDestinations(DataObjectRoute route)
    {
      if (route.Addresses == null && route.Addresses.Length < 3)
      {
        Console.WriteLine("ResequenceRouteDestinations error {0}", "route.Addresses == null && route.Addresses.Length < 3. Number of addresses should be >= 3");
        return;
      }

      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Switch 2 addresses after departure address:

      AddressesOrderInfo addressesOrderInfo = new AddressesOrderInfo();
      addressesOrderInfo.RouteId = route.RouteID;
      addressesOrderInfo.Addresses = new AddressInfo[0];
      for (int i = 0; i < route.Addresses.Length; i++)
      {
        Address address = route.Addresses[i];
        AddressInfo addressInfo = new AddressInfo();
        addressInfo.DestinationId = address.RouteDestinationId.Value;
        addressInfo.SequenceNo = i;
        if (i == 1)
          addressInfo.SequenceNo = 2;
        else if (i == 2)
          addressInfo.SequenceNo = 1;
        addressInfo.IsDepot = (addressInfo.SequenceNo == 0);
        List<AddressInfo> addressesList = new List<AddressInfo>(addressesOrderInfo.Addresses);
        addressesList.Add(addressInfo);
        addressesOrderInfo.Addresses = addressesList.ToArray();
      }

      // Run the query
      string errorString1 = "";
      DataObjectRoute route1 = route4Me.GetJsonObjectFromAPI<DataObjectRoute>(addressesOrderInfo,
                              R4MEInfrastructureSettings.RouteHost,
                              HttpMethodType.Put,
                              out errorString1);

      // Output the result
      PrintExampleOptimizationResult("ResequenceRouteDestinations, switch 2 addresses.", route1, errorString1);
      Console.WriteLine("");
    }

    [DataContract]
    private class AddressInfo : GenericParameters
    {
      [DataMember(Name = "route_destination_id")]
      public int DestinationId { get; set; }

      [DataMember(Name = "sequence_no")]
      public int SequenceNo { get; set; }

      [DataMember(Name = "is_depot")]
      public bool IsDepot { get; set; }
    }

    [DataContract]
    private class AddressesOrderInfo : GenericParameters
    {
      [HttpQueryMemberAttribute(Name = "route_id", EmitDefaultValue = false)]
      public string RouteId { get; set; }

      [DataMember(Name = "addresses")]
      public AddressInfo[] Addresses { get; set; }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Resequence Route Destination
        ''' </summary>
        Public Sub ResequenceRouteDestination(routeId As String, routeDestinationId As Integer)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim rParameters As New RouteParametersQuery() With { _
                .RouteId = routeId, _
                .RouteDestinationId = routeDestinationId
            }

            Dim addresses As Address() = New Address() {New Address() With { _
                .RouteId = routeId, _
                .Latitude = 40.285026, _
                .Longitude = -74.333839, _
                .SequenceNo = 2
            }}

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As RouteResponse = route4Me.ResequenceRouteDestination(rParameters, addresses, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("Route was resequenced successfully")

                Console.WriteLine("Route ID: {0}", dataObject.RouteID)
                ' Console.WriteLine("State: {0}", dataObject.State)
            Else
                Console.WriteLine("Route resequence error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    route = r4m.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Route ID: {}'.format(response.route_id)
            route_destination_id = response.addresses[1].route_destination_id
            route_destination_id2 = response.addresses[2].route_destination_id
            data = {"route_destination_id": route_destination_id,
                    "route_id": response.route_id,
                    "addresses": [{"route_destination_id": route_destination_id2,
                                   "sequence_no": 2,
                                   }]
                    }
            response = route.resequence_route(**data)
            print 'Optimization Problem ID: {}'.format(response.optimization_problem_id)
            print 'Route ID: {}'.format(response.route_id)
            for i, address in enumerate(response.addresses):
                print 'Address #{}'.format(i)
                print '\tAddress: {0}'.format(address.address)
                print '\tRoute Destination ID: {0}'.format(address.route_destination_id)

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    updated, err := service.UpdateRoute(&routing.Route{
        ID:        "route-id",
        Addresses: []Address{
            RouteDestinationID: json.Number{`route-destination-id`),
            SequenceNo: 2,
        },
    })
    if err != nil {
        // handle errors
        return
    }
    // do something with the updated route
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Address;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$route = new Route();

// Select a route with more than 4 addresses.
$routesParams = array(
    "offset"  =>  0,
    "limit"   =>  20
);

$routes = $route->getRoutes($routesParams);

$selectedRoute = null;

foreach ($routes as $route1) {
    if (isset($route1->destination_count)) {
        if ($route1->destination_count>4) {
            $selectedRoute = $route->getRoutes(array('route_id' => $route1->route_id));
            break;
        }
    }
}

assert(!is_null($selectedRoute), "Can't select a route with more than 4 addresses");

// Resequence a route destination 
$routeID = $selectedRoute->route_id;
$routeDestinationID = $selectedRoute->addresses[2]->route_destination_id;

echo "Route ID-> $routeID, Route destination ID -> $routeDestinationID <br>"; 

$params = array(
    "route_id"              => $routeID,
    "route_destination_id"  => $routeDestinationID,
    "addresses"  => array(
        "0" => array(
            "route_destination_id"  => $routeDestinationID,
            "sequence_no"           => 3
        )
    )
);

$response = $route->resequenceRoute($params);

foreach ($response['addresses'] as $address) {
    Route4Me::simplePrint($address);
    echo "<br>";
}
unit ResequenceRouteDestinationsUnit;

interface

uses SysUtils, BaseOptimizationExampleUnit, DataObjectUnit;

type
  TResequenceRouteDestinations = class(TBaseOptimizationExample)
  public
    procedure Execute(Route: TDataObjectRoute);
  end;

implementation

uses
  AddressUnit, AddressesOrderInfoUnit;

procedure TResequenceRouteDestinations.Execute(Route: TDataObjectRoute);
var
  AddressesOrderInfo: TAddressesOrderInfo;
  Address: TAddress;
  AddressInfo: TAddressInfo;
  i: integer;
  SequenceNo: integer;
  ErrorString: String;
  NewRoute: TDataObjectRoute;
begin
  if (Length(Route.Addresses) < 3) then
  begin
    WriteLn(Format('ResequenceRouteDestinations error: "%s"',
      ['Route.Addresses.Length < 3. Number of addresses should be >= 3']));
    Exit;
   end;

  // Switch 2 addresses after departure address:
  AddressesOrderInfo := TAddressesOrderInfo.Create(Route.RouteID);
  try
    for i := 0 to Length(Route.Addresses) - 1 do
    begin
      Address := Route.Addresses[i];

      SequenceNo := i;
      if (i = 1) then
        SequenceNo := 2
      else
        if (i = 2) then
          SequenceNo := 1;

      AddressInfo := TAddressInfo.Create;
      AddressInfo.DestinationId := Address.RouteDestinationId.Value;
      AddressInfo.SequenceNo := SequenceNo;
      AddressInfo.IsDepot := (AddressInfo.SequenceNo = 0);

      AddressesOrderInfo.AddAddress(AddressInfo);
    end;

    NewRoute := Route4MeManager.Route.Resequence(AddressesOrderInfo, ErrorString);
    try
      PrintExampleOptimizationResult(
        'ResequenceRouteDestinations, switch 2 addresses.', NewRoute, ErrorString);
      WriteLn('');
    finally
      FreeAndNil(NewRoute);
    end;
  finally
    FreeAndNil(AddressesOrderInfo);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/route.php?api_key=...&route_id=...&route_destination_id=...


See the sample JSON response of this method.


Move a Destination into a Route

Move a destination to another route. This API endpoint will respond with a Boolean status code. This API method allows you to remove one specific address ID from one specific route ID.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
to_route_id string Destination route ID POST
route_destination_id integer A destination ID to be moved. POST
after_destination_id integer A destination ID in a destination route after which the moved destination will be inserted. POST
<job id="Move Destination to Other Route">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example demonstrates the process of moving an address into a route after a specified address.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/actions/route/move_route_destination.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="move_destination_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void MoveDestinationToRoute(string toRouteId, int routeDestinationId, int afterDestinationId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Run the query
      string errorString;
      bool success = route4Me.MoveDestinationToRoute(toRouteId, routeDestinationId, afterDestinationId, out errorString);

      Console.WriteLine("");

      if (success)
      {
        Console.WriteLine("MoveDestinationToRoute executed successfully");

        Console.WriteLine("Destination {0} moved to Route {1} after Destination {2}", routeDestinationId, toRouteId, afterDestinationId);
      }
      else
      {
        Console.WriteLine("MoveDestinationToRoute error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub MoveDestinationToRoute(toRouteId As String, routeDestinationId As Integer, afterDestinationId As Integer)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim success As Boolean = route4Me.MoveDestinationToRoute(toRouteId, routeDestinationId, afterDestinationId, errorString)

            Console.WriteLine("")

            If success Then
                Console.WriteLine("MoveDestinationToRoute executed successfully")

                Console.WriteLine("Destination {0} moved to Route {1} after Destination {2}", routeDestinationId, toRouteId, afterDestinationId)
            Else
                Console.WriteLine("MoveDestinationToRoute error: {0}", errorString)
            End If

        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    optimization = r4m.optimization
    address = r4m.address
    optimization.algorithm_type(ALGORITHM_TYPE.TSP)
    optimization.share_route(0)
    optimization.store_route(0)
    optimization.route_time(0)
    optimization.route_max_duration(86400)
    optimization.vehicle_capacity(1)
    optimization.vehicle_max_distance_mi(10000)
    optimization.route_name('Single Driver Round Trip')
    optimization.optimize(OPTIMIZE.DISTANCE)
    optimization.distance_unit(DISTANCE_UNIT.MI)
    optimization.device_type(DEVICE_TYPE.WEB)
    optimization.travel_mode(TRAVEL_MODE.DRIVING)
    address.add_address(
        address='754 5th Ave New York, NY 10019',
        lat=40.7636197,
        lng=-73.9744388,
        alias='Bergdorf Goodman',
        is_depot=1,
        time=0
    )
    address.add_address(
        address='717 5th Ave New York, NY 10022',
        lat=40.7669692,
        lng=-73.9693864,
        alias='Giorgio Armani',
        time=0
    )
    address.add_address(
        address='888 Madison Ave New York, NY 10014',
        lat=40.7715154,
        lng=-73.9669241,
        alias='Ralph Lauren Women\'s and Home',
        time=0
    )
    address.add_address(
        address='1011 Madison Ave New York, NY 10075',
        lat=40.7772129,
        lng=-73.9669,
        alias='Yigal Azrou\u00ebl',
        time=0
    )
    address.add_address(
        address='440 Columbus Ave New York, NY 10024',
        lat=40.7808364,
        lng=-73.9732729,
        alias='Frank Stella Clothier',
        time=0
    )
    address.add_address(
        address='324 Columbus Ave #1 New York, NY 10023',
        lat=40.7803123,
        lng=-73.9793079,
        alias='Liana',
        time=0
    )
    address.add_address(
        address='110 W End Ave New York, NY 10023',
        lat=40.7753077,
        lng=-73.9861529,
        alias='Toga Bike Shop',
        time=0
    )
    address.add_address(
        address='555 W 57th St New York, NY 10019',
        lat=40.7718005,
        lng=-73.9897716,
        alias='BMW of Manhattan',
        time=0
    )
    address.add_address(
        address='57 W 57th St New York, NY 10019',
        lat=40.7558695,
        lng=-73.9862019,
        alias='Verizon Wireless',
        time=0
    )

    new_sequence = [8, 5, 1, 7, 2, 6, 0, 3, 4]

    addresses = {'addresses': []}
    response = r4m.run_optimization()

    print 'Current Addresses'
    for i, address in enumerate(response.addresses):
        print 'Number {}:'.format(i)
        if address.is_depot:
            print '\t This is a Depot'
        print '\taddress: {}'.format(address.address)
        print '\t'
        if new_sequence[i] == 0:
            addresses['addresses'].append(
                {
                    "route_destination_id": address.route_destination_id,
                    "is_depot": True
                })
        else:
            addresses['addresses'].append({
                    "route_destination_id": address.route_destination_id,
                    "sequence_no": new_sequence[i],
                    "is_depot": False
                })

    print 'Moving addresses'

    route_id = response.addresses[1].route_id

    response = r4m.route.move_addresses_from_route(addresses, route_id)
    print 'Addresses after move'

    for i, address in enumerate(response.addresses):
        print 'Number {}:'.format(i)
        if address.is_depot:
            print '\t This is a Depot'
        print '\taddress: {}'.format(address.address)
        print '\t'

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.addresses;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.DataObject;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class MoveAddresses {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager manager = new RoutingManager(apiKey);
        try {
            List<DataObject> data = manager.getOptimizations(10, 5);
            DataObject obj = data.get(0);
            List<Route> routes = manager.getRoutes(new RoutesRequest().setLimit(10));
            DataObject newObj = manager.moveAddresses(obj, routes.get(2).getId());
            System.out.println(newObj);
        } catch (APIException e) {
            // handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$route = new Route();

$grParams = array(
    'offset' => 0,
    'limit'  => 10
);

$routes = $route->getRoutes($grParams);
assert(!is_null($routes), "There are no routes in the account for this example. Please create at least 2 routes first.");
assert(sizeof($routes)>1, "This example requires at least 2 routes. Please, create them first.");

// Get random source route from test routes
$route = new Route();

$route_id0 = $routes[rand(0, sizeof($routes)-1)]->route_id;

echo "<br> From the route -> ".$route_id0 ."<br>";

if (is_null($route_id0)) {
    echo "Can't retrieve random route_id! Try again.";
    return;
}

// Get random source destination from selected source route above
$addressRand = (array)$route->GetRandomAddressFromRoute($route_id0);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address.");

echo "Moved destination ID = $route_destination_id <br>";

// Get random destination route from test routes
$to_route_id = $route_id0;

while ($to_route_id==$route_id0) {
    $to_route_id = $routes[rand(0, sizeof($routes) - 1)]->route_id;
}

echo "<br> to the route -> ".$to_route_id ."<br>";

if (is_null($to_route_id)) {
    echo "Can't retrieve random route_id! Try again.";
    return;
}

// Get random destination destination from selected source route above
$addressRand2 = (array)$route->GetRandomAddressFromRoute($to_route_id);

$after_destination_id = $addressRand2['route_destination_id'];

if (is_null($after_destination_id)) {
    echo "Can't retrieve random address! Try again.";
    return;
}

echo "after_destination_id = $after_destination_id <br>";

// Move the destination to the route     
$routeparams = array(
    'to_route_id'           =>  $to_route_id,
    'route_destination_id'  =>  strval($route_destination_id),
    'after_destination_id'  =>  strval($after_destination_id)
);

$address = new Address();
$result = $address->moveDestinationToRoute($routeparams);

var_dump($result);
package MoveDestinationToRoute;
use strict;
use warnings FATAL => 'all';
sub MoveDestinationToRoute {
    my ( $self, $toRouteId, $routeDestinationId, $afterDestinationId ) = @_;

    my $route4Me = Route4MeManager->new(ExamplesInfrastructure->ApiKey);

    my $errorString = "";

    my $success = $route4Me->moveDestinationToRoute($toRouteId, $routeDestinationId, $afterDestinationId, $errorString);

    if ($success) {
        print "MoveDestinationToRoute executed successfully";
        print "\n";
        printf "Destination %s moved to Route %s after Destination %s", , $routeDestinationId, $toRouteId, $afterDestinationId;
        print "\n";
    } else {
        printf "MoveDestinationToRoute error: %s", $errorString;
        print "\n";
    }
    print "\n";
}
1;
@ECHO OFF

SET url=https://api.route4me.com/actions/route/move_route_destination.php
SET apikey=11111111111111111111111111111111

:: Recipient route ID
SET trid=BAD35EEE32BFF8E20C2077AC53761BC7

:: The destination to be moved 
SET rdi=184611093

:: The destination ID in a recipient route, after which will be inserted moving destination.
SET adi=184611074

ECHO ON

:: The example demonstrates the process of moving an address into a route after a specified address.

curl -o file1.txt -g -X POST -k -H "Content-Type: multipart/form-data;" -F "to_route_id=%trid%" -F "route_destination_id=%rdi%" -F "after_destination_id=%adi%" "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/route/move_route_destination.php
apikey=11111111111111111111111111111111

# Recipient route ID
trid=BAD35EEE32BFF8E20C2077AC53761BC7

# The destination to be moved
rdi=184611093

# The destination ID in a recipient route, after which will be inserted moving destination.
adi=184611074

# The example demonstrates the process of moving an address into a route after a specified address.

curl -o file1.txt -g -X POST -k -H "Content-Type: multipart/form-data;" -F "to_route_id=$trid" -F "route_destination_id=$rdi" -F "after_destination_id=$adi" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  query := routing.DestinationMoveRequest {
    ToRouteID: "route-id",
    RouteDestinationID: "route-destination-id",
    AfterDestinationID: "after-destination-id",
  }
  success, err := service.MoveDestinationToRoute(query)
  if err != nil {
    // handle error
    return
  }
  if !success {
    // handle failed attempt
    return
  }
}
unit MoveDestinationToRouteUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TMoveDestinationToRoute = class(TBaseExample)
  public
    procedure Execute(ToRouteId: String;
      RouteDestinationId, AfterDestinationId: integer);
  end;

implementation

procedure TMoveDestinationToRoute.Execute(ToRouteId: String;
  RouteDestinationId, AfterDestinationId: integer);
var
  ErrorString: String;
  Success: boolean;
begin
  Success := Route4MeManager.Route.MoveDestinationToRoute(ToRouteId,
    RouteDestinationId, AfterDestinationId, ErrorString);

  WriteLn('');

  if (Success) then
  begin
    WriteLn('MoveDestinationToRoute executed successfully');
    WriteLn(Format(
      'Destination %d moved to Route %s after Destination %d',
      [RouteDestinationId, ToRouteId, AfterDestinationId]));
  end
  else
    WriteLn(Format('MoveDestinationToRoute error: "%s"', [ErrorString]));
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/actions/route/move_route_destination.php?api_key=...

You can expect this API response:

{
  "success":true
}

Remove Routes

Given multiple route IDs, remove all routes at the same time. Limited to a maximum of N routes, where N is 40 characters multiplied by the maximum length of the hosting server’s maximum GET request query string length. The user must be authenticated because deleted routes are bound to the authenticated member ID.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string A comma-separated list of route IDs.
<job id="Delete Routes">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of removing the specified routes.
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="270CB108F227AD6E11827FC08EE4E2D7,C340E3F6AF28E20EFAE0FBE51759C338"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid

      jFile=""
      
      Set r4m=New Route4Me
      
      r4m.HttpDeleteRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void DeleteRoutes(string[] routeIds)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      //routeIds = new string[] { "1" };

      // Run the query
      string errorString;
      string[] deletedRouteIds = route4Me.DeleteRoutes(routeIds, out errorString);

      Console.WriteLine("");

      if (deletedRouteIds != null)
      {
        Console.WriteLine("DeleteRoutes executed successfully, {0} routes deleted", deletedRouteIds.Length);
        Console.WriteLine("");
      }
      else
      {
        Console.WriteLine("DeleteRoutes error {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub DeleteRoutes(routeIds As String())
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            'routeIds = new string[] { "1" }

            ' Run the query
            Dim errorString As String = ""
            Dim deletedRouteIds As String() = route4Me.DeleteRoutes(routeIds, errorString)

            Console.WriteLine("")

            If deletedRouteIds IsNot Nothing Then
                Console.WriteLine("DeleteRoutes executed successfully, {0} routes deleted", deletedRouteIds.Length)
                Console.WriteLine("")
            Else
                Console.WriteLine("DeleteRoutes error {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
#!/usr/bin/python

from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    route = route4me.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.delete_routes(route_id=[response[0].route_id, ])
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Routes Deleted:'
            for i, route in enumerate(response.route_ids):
                print '\t{0} - {1}'.format(i+1, route)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.routes;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RouteDeletedResponse;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

/**
 * @author juan
 */
public class DeleteRoutes {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager routeManager = new RoutingManager(apiKey);
        try {
            List<Route> routes = routeManager.getRoutes(new RoutesRequest().setLimit(3).setOffset(0));
            if (routes.size() < 2) {
                throw new RuntimeException("Not enough routes");
            }
            RouteDeletedResponse deleted = routeManager.deleteRoutes(routes.get(0).getId(), routes.get(1).getId());
            System.out.println(deleted);
        } catch (APIException e) {
            //handle exceptions
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root=realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$route = new Route();

// Get 2 random route IDs
$randomRouteID1 = $route->getRandomRouteId(0, 25);
assert(!is_null($randomRouteID1), "Can't retrieve the first random route ID");

$randomRouteID2 = $route->getRandomRouteId(0, 25);
assert(!is_null($randomRouteID2), "Can't retrieve the second random route ID");

echo "Random route ID 1 -> $randomRouteID1 <br>  Random route ID 2 -> $randomRouteID2 <br>";

// Remove selected routes
$route_ids = join(',', array($randomRouteID1, $randomRouteID2));

$result = $route->deleteRoutes($route_ids);

Route4Me::simplePrint($result);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  routes, err = service.DeleteRoutes([]string{"route-id"})
  if err != nil {
    // handle errors
    return
  }
}
package DeleteRoutes;
use strict;
use warnings FATAL => 'all';

sub DeleteRoutes {
    my ($self, @routeIds) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $errorString = "";

    my @deletedRouteIds = $route4Me->deleteRoutes( @routeIds, \$errorString );

    print "\n";

    if (@deletedRouteIds) {
        printf "DeleteRoutes executed successfully, routes deleted: %s\n", scalar @deletedRouteIds;
    } else {
        printf "DeleteRoutes error: %s\n", $errorString;
    }
}

1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET "routeid=270CB108F227AD6E11827FC08EE4E2D7,C340E3F6AF28E20EFAE0FBE51759C338"

ECHO ON

:: The example demonstrates the process of removing the specified routes.

curl -o file1.txt -g -k -X DELETE "%url%?api_key=%apikey%&route_id=%routeid%" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid="270CB108F227AD6E11827FC08EE4E2D7,C340E3F6AF28E20EFAE0FBE51759C338"

# The example demonstrates the process of removing the specified routes.

curl -o file1.txt -g -k -X DELETE "$url?api_key=$apikey&route_id=$routeid" 

echo "Finished..."

sleep 15
unit DeleteRoutesUnit;

interface

uses SysUtils, BaseExampleUnit, CommonTypesUnit;

type
  TDeleteRoutes = class(TBaseExample)
  public
    procedure Execute(RouteIds: TStringArray);
  end;

implementation

procedure TDeleteRoutes.Execute(RouteIds: TStringArray);

var
  ErrorString: String;
  DeletedRouteIds: TStringArray;
begin
  DeletedRouteIds := Route4MeManager.Route.Delete(RouteIds, ErrorString);

  WriteLn('');

  if (Length(DeletedRouteIds) > 0) then
  begin
    WriteLn(Format('DeleteRoutes executed successfully, %d routes deleted',
      [Length(DeletedRouteIds)]));
    WriteLn('');
  end
  else
    WriteLn(Format('DeleteRoutes error "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "AC16E7D338B551013FF34266FE81A5EEXXX";
    int ret = 0;
    if(route.delete_route(route_id) == 0)
    {
        // use Json::StyledWriter instead of Json::FastWriter for a human friendly output
        cout << "Response of deleted route " << route_id << " is:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Error when deleting route: code = " << route.get_err_code() << ", msg:" << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);
    const char route_id[] = "AC16E7D338B551013FF34266FE81A5EEXXX";

    if (!delete_route(route_id))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

DELETE
/api.v4/route.php?api_key=...&route_id=...

You can expect this API response:

{
  "deleted": true,
  "route_id": "270CB108F227AD6E11827FC08EE4E2D7,C340E3F6AF28E20EFAE0FBE51759C338",
  "route_ids": [
    "270CB108F227AD6E11827FC08EE4E2D7",
    "C340E3F6AF28E20EFAE0FBE51759C338"
    ]
}

Merge Routes

The endpoint /actions/merge_routes.php accepts an array of valid route IDs which exist in the Route4Me database and merges all the route destinations into a single new route. A new route ID is generated, and it is a union of all the routes in the provided list of route IDs. The new route’s destinations are all in the sequence of the route IDs that are being merged. The merged route has all the same metadata and account ownership information as the original routes, however, route notes and visited status flags are not copied into the new route.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_ids array An array of Route IDs to be merged. POST
<job id="Merge Routes">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim FormData
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of merging two routes into one.
      
      url="https://api.route4me.com/actions/merge_routes.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      route_ids="807D38F914B27A7E9B05EDF0E1BE4014,F9165689AEB9818ED61AF3CC1C759AE4"
      depot_address="10180 Dyer St, El Paso, TX 79924, USA"
      remove_origin="false"
      depot_lat="31.9061405"
      depot_lng="-106.4033899"
      
      FormData="route_ids=" & route_ids
      FormData=FormData & "|depot_address=" & depot_address
      FormData=FormData & "|remove_origin=" & remove_origin
      FormData=FormData & "|depot_lat=" & depot_lat
      FormData=FormData & "|depot_lng=" & depot_lng
      
      Set r4m=New Route4Me
      
      r4m.HttpPostFormRequest url,FormData
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF
setlocal enableDelayedExpansion

SET url=https://api.route4me.com/actions/merge_routes.php
SET apikey=11111111111111111111111111111111
SET route_ids=807D38F914B27A7E9B05EDF0E1BE4014,F9165689AEB9818ED61AF3CC1C759AE4
SET "depot_address=10180 Dyer St, El Paso, TX 79924, USA"
SET "remove_origin=false"
SET depot_lat=31.9061405
SET depot_lng=-106.4033899

ECHO ON

:: The example demonstrates the process of merging two routes into one.

curl -o merge_routes_RESPONSE.json -g -k -H "multipart/form-data" -X POST ^
-F "route_ids=%route_ids%" ^
-F "depot_address=%depot_address%" ^
-F "remove_origin=%remove_origin%" ^
-F "depot_lat=%depot_lat%" ^
-F "depot_lng=%depot_lng%" ^
"%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/merge_routes.php
apikey=11111111111111111111111111111111
route_ids="807D38F914B27A7E9B05EDF0E1BE4014,F9165689AEB9818ED61AF3CC1C759AE4"
depot_address="10180 Dyer St, El Paso, TX 79924, USA"
remove_origin=false
depot_lat=31.9061405
depot_lng=-106.4033899

# The example demonstrates the process of merging two routes into one.

curl -o merge_routes_RESPONSE.json -g -k -H "multipart/form-data" -X POST \
-F "route_ids=$route_ids" \
-F "depot_address=$depot_address" \
-F "remove_origin=$remove_origin" \
-F "depot_lat=$depot_lat" \
-F "depot_lng=$depot_lng" \
"$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void MergeRoutes(MergeRoutesQuery mergeRoutesParameters)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Run the query
      string errorString;
      bool result = route4Me.MergeRoutes(mergeRoutesParameters, out errorString);

      Console.WriteLine("");

      if (result)
      {
          Console.WriteLine("MergeRoutes executed successfully, {0} routes merged", mergeRoutesParameters.RouteIds);
        Console.WriteLine("");
      }
      else
      {
        Console.WriteLine("MergeRoutes error {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples

    Partial Public NotInheritable Class Route4MeExamples
        Public Sub MergeRoutes(params As MergeRoutesQuery)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim result As Boolean = route4Me.MergeRoutes(params, errorString)

            Console.WriteLine("")

            If result Then
                Console.WriteLine("MergeRoutes executed successfully")
            Else
                Console.WriteLine("MergeRoutes error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    route = r4m.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        route_id1 = response[0].route_id
        route_id2 = response[1].route_id
        data = {'route_ids': [route_id1, route_id2]}
        response = route.merge_routes(**data)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Optimization Problem ID: {}'.format(response.optimization_problem_id)
            print 'Route ID: {}'.format(response.route_id)
            for i, address in enumerate(response.addresses):
                print 'Address #{}'.format(i)
                print '\tAddress: {0}'.format(address.address)
                print '\tRoute Destination ID: {0}'.format(address.route_destination_id)

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  err := service.MergeRoutes("route-id","route2-id")
  if err != nil {
    // handle errors
    return
  }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$route = new Route();

// Get 2 different random route IDs
$route_id1 = $route->getRandomRouteId(0, 20);
assert(!is_null($route_id1), "Can't retrieve a random route ID");

$route_id2 = $route_id1;

$count = 0; 

while ($route_id1==$route_id2) {
    $route_id2 = $route->getRandomRouteId(0, 20);
    
    $count++;
    
    if ($count>5) break; // Avoid running into an infinite loop, if there are less than 2 routes.
}

echo "Route ID 1 -> $route_id1 <br> Route ID 2 -> $route_id2 <br>";

// Get the depot address from first route
$addresses = $route->GetAddressesFromRoute($route_id1);
assert(!is_null($addresses), "Can't retrieve the addresses from the route");

$depot = null;

foreach ($addresses as $address) {
    if (isset($address->is_depot)) {
        if ($address->is_depot==true) {
            $depot = $address;
            break;
        }
    }
}

// Merge the selected routes
$params = array(
    "route_ids"      => $route_id1.",".$route_id2,
    "depot_address"  =>  $depot->address,
    "remove_origin"  =>  false,
    "depot_lat"      =>  $depot->lat,
    "depot_lat"      =>  $depot->lng
);

$result = $route->mergeRoutes($params);

var_dump($result);
unit MergeRoutesUnit;

interface

uses SysUtils, BaseExampleUnit, CommonTypesUnit;

type
  TMergeRoutes = class(TBaseExample)
  public
    procedure Execute(RouteIds: TListString);
  end;

implementation


procedure TMergeRoutes.Execute(RouteIds: TListString);

var
  ErrorString: String;
begin
  Route4MeManager.Route.Merge(RouteIds.ToArray, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    WriteLn('MergeRoutes executed successfully');
    WriteLn('');
  end
  else
    WriteLn(Format('MergeRoutes error "%s"', [ErrorString]));
end;

end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY, true);

    const char* route_ids="075594D31563C05ACCEBCAA77D026B2D,6AF79B603C1B6C5AAC714CDD76687CC6";
    const char* depot_address="11921 N Dickinson Dr, Fredericksburg, VA 22407, USA";

    MapPoint point;
    point.lat = 38.285804;
    point.lng=-77.555054;

    if(route.merge_routes(route_ids, depot_address, point) == 0)
    {
        cout << "Routes merged:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Failed to merge routes: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/actions/merge_routes.php?api_key=...

You can expect this API response:

{"status":true}

Duplicate a Route

The duplicated route has all the same metadata and account ownership information as the original route. However, route notes and visited status flags are not copied into the new route. The name of the new route is automatically appended with the string “(Duplicate)” to indicate that the route is a duplicate route. There is currently no special designation inside the database to indicate that a route originated from another route.


PARAMETERS

Parameter Type Description
api_key string API key of the user
duplicate_routes_id array An array of the Route IDs
<job id="Duplicate Route">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/route.php"
			apikey="11111111111111111111111111111111"
			routeid="253FB124F4A53031EBC344B2F1BA466D"
			
			url=url&"?api_key="&apikey
			
			jFile="duplicate_route_data.json"
			
			Set r4m=New Route4Me
			r4m.OutputFile="duplicate_route_RESPONSE.json"
			
			r4m.HttpPostRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Duplicate a route
        /// </summary>
        /// <param name="routeId">Route ID</param>
        public void DuplicateRoute(string routeId = null)
        {
            // Create the manager with the api key
            var route4Me = new Route4MeManager(ActualApiKey);

            bool isInnerEample = routeId == null ? true : false;

            if (isInnerEample)
            {
                RunOptimizationSingleDriverRoute10Stops();
                OptimizationsToRemove = new List<string>()
                {
                    SD10Stops_optimization_problem_id
                };

                routeId = SD10Stops_route_id;
            }

            var routeParameters = new RouteParametersQuery()
            {
                DuplicateRoutesId = new string[] { routeId }
            };

            // Run the query
            var result = route4Me.DuplicateRoute(routeParameters, out string errorString);

            if (((result?.Status ?? false) && (result?.RouteIDs?.Length ?? 0)>0))
            {
                RoutesToRemove = new List<string>() { result.RouteIDs[0] };
            }

            Console.WriteLine(
                (result?.Status ?? false) && (result?.RouteIDs?.Length ?? 0) > 0 
                ? String.Format(
                    "DuplicateRoute executed successfully, duplicated route ID: {0}",
                    result.RouteIDs[0]
                  )
                : String.Format(
                    "DuplicateRoute error {0}",
                    errorString
                  )
             );

            if (isInnerEample)
            {
                RemoveTestRoutes();
                RemoveTestOptimizations();
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Duplicate a route
        ''' </summary>
        ''' <param name="routeId">Route ID</param>
        Public Sub DuplicateRoute(ByVal Optional routeId As String = Nothing)
            ' Create the manager with the api key
            Dim route4Me = New Route4MeManager(ActualApiKey)
            Dim isInnerEample As Boolean = If(routeId Is Nothing, True, False)

            If isInnerEample Then
                RunOptimizationSingleDriverRoute10Stops()

                OptimizationsToRemove = New List(Of String)() From {
                    SD10Stops_optimization_problem_id
                }

                routeId = SD10Stops_route_id
            End If

            Dim routeParameters = New RouteParametersQuery() With {
                .DuplicateRoutesId = New String() {routeId}
            }

            ' Run the query
            Dim errorString As String = Nothing
            Dim result = route4Me.DuplicateRoute(routeParameters, errorString)

            If ((If(result?.Status, False)) AndAlso (If(result?.RouteIDs?.Length, 0)) > 0) Then
                RoutesToRemove = New List(Of String)() From {
                    result.RouteIDs(0)
                }
            End If

            Console.WriteLine(
                If(
                    (If(result?.Status, False)) AndAlso (If(result?.RouteIDs?.Length, 0)) > 0,
                    String.Format("DuplicateRoute executed successfully, duplicated route ID: {0}", result.RouteIDs(0)),
                    String.Format("DuplicateRoute error {0}", errorString))
                  )

            If isInnerEample Then
                RemoveTestRoutes()
                RemoveTestOptimizations()
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

API_KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(API_KEY)
    route = route4me.route
    response = route.get_routes(limit=1, offset=0)
    if isinstance(response, dict) and 'errors' in response.keys():
        print('. '.join(response['errors']))
    else:
        route_id = response[0]['route_id']
        print('Route ID: {}'.format(route_id))
        response = route.duplicate_route(route_id=route_id)
        if isinstance(response, dict) and 'errors' in response.keys():
            print('. '.join(response['errors']))
        else:
            print('Optimization Problem ID: {}'.format(
                response['optimization_problem_id']
            ))
            print('Route ID: {}'.format(response['route_id']))
            for address in response['addresses']:
                print('\t\t\tAddress: {0}'.format(address['address']))


if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.routes;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

/**
 * @author juan
 */
public class DuplicateRoute {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager routeManager = new RoutingManager(apiKey);
        try {
            List<Route> routes = routeManager.getRoutes(new RoutesRequest().setLimit(10));
            RoutingManager.DuplicateRouteResponse resp = routeManager.duplicateRoute(routes.get(0).getId());
            System.out.println(resp);
        } catch (APIException e) {
            //handle exceptions
            e.printStackTrace();
        }
    }
}
<?php

namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the api key in the Route4Me class
Route4Me::setApiKey(Constants::API_KEY);

$route = new Route();

// Get random route ID
$randomRouteID = $route->getRandomRouteId(0, 25);
assert(!is_null($randomRouteID), "Cannot retrieve a random route ID");

$routeIDs = [$randomRouteID];

// Duplicate the selected route
$routeDuplicate = $route->duplicateRoute($routeIDs);

Route4Me::simplePrint($routeDuplicate);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  duplicated, err := service.DuplicateRoute(`route-id`)
  if err != nil {
    // handle errors
    return
  }
}
package DuplicateRoute;
use strict;
use warnings FATAL => 'all';

sub DuplicateRoute {
    my ($self, $routeId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $routeParameters = RouteParametersQuery->new({
            route_id => $routeId
        });

    my $errorString = "";

    my $duplicatedRouteId = $route4Me->duplicateRoute( $routeParameters, \$errorString );

    print "\n";

    if ($duplicatedRouteId) {
        printf "DuplicateRoute executed successfully, duplicated route ID: %s\n", $duplicatedRouteId;
    } else {
        printf "DuplicateRoute error: %s\n", $errorString;
    }

    return $duplicatedRouteId;
}
1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of making duplicate of a route.

ECHO ON
curl -o duplicate_route_RESPONSE.json -g -k -XPOST -d "{\"duplicate_routes_id\": [\"253FB124F4A53031EBC344B2F1BA466D\"]}" "%url%?api_key=%apikey%" 

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111

 # The example refers to the process of making duplicate of a route.

curl -o duplicate_route_RESPONSE.json -g -k XPOST -d "{\"duplicate_routes_id\": [\"253FB124F4A53031EBC344B2F1BA466D\"]}" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
unit DuplicateRouteUnit;

interface

uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit;

type
  TDuplicateRoute = class(TBaseExample)
  public
    function Execute(RouteId: String): NullableString;
  end;

implementation

uses RouteParametersQueryUnit;

function TDuplicateRoute.Execute(RouteId: String): NullableString;

var
  ErrorString: String;
  Parameters: TRouteParametersQuery;
begin
  Parameters := TRouteParametersQuery.Create;
  try
    Parameters.RouteId := RouteId;

    Result := Route4MeManager.Route.Duplicate(Parameters, ErrorString);

    WriteLn('');

    if (Result.IsNotNull) then
    begin
      WriteLn(Format('DuplicateRoute executed successfully, duplicated route ID: %s',
        [Result.Value]));
      WriteLn('');
    end
    else
      WriteLn(Format('DuplicateRoute error "%s"', [ErrorString]));
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";
    const char *route_destination_id = "174405709A";

    int ret = route.get_address(route_id, route_destination_id);
    if (ret == 0) {
      cout << "Route address by ID:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
      if (route.duplicate_route(route_id, "none") == 0) {
        cout << "Duplicated route " << endl;
      }
      else {
        cout << "Duplicating problem for route " << route_id << endl;
      }
    }
    else {
      cout << "Error reading address: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
      ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);

    if (!duplicate_route("CA902292134DBC134EAF8363426BD247", "none"))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

POST
/api.v4/route.php?api_key=...

You can expect this API response:

{
  "status":true,
  "route_ids":[ "E5229D257DC3BC84CB6696E98AAEAAE8" ]
}

Share Routes

Share a route via email.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_id string Route ID GET
response_format string Response format GET
recipient_email string Recipient email POST
<job id="Share Route">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' needs an email provider
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/actions/route/share_route.php"
      apikey="11111111111111111111111111111111"
      routeid="3A2DD89E6E1A044B2098AD1313E3138C"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&response_format=json"
      
      jFile="email_for_route_sharing.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/actions/route/share_route.php
SET apikey=11111111111111111111111111111111
SET routeid=3A2DD89E6E1A044B2098AD1313E3138C

ECHO ON

:: The example demonstrates the process of sharing a route via email.

curl -o file1.txt -g -X POST -k -H "Content-Type: multipart/form-data;" -F "[email protected]" "%url%?api_key=%apikey%&route_id=%routeid%&response_format=json" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/route/share_route.php
apikey=11111111111111111111111111111111
routeid=3A2DD89E6E1A044B2098AD1313E3138C
frmt=json

# The example demonstrates the process of sharing a route via email.

curl -o file1.txt -g -X POST -k -H "Content-Type: multipart/form-data;" -F "[email protected]" "$url?api_key=$apikey&route_id=$routeid&response_format=$frmt" 

echo "Finished.."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        public void RouteSharing(string routeId, string Email)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            // The example demonstrates the process of sharing a route via email.

            // Run the query
            RouteParametersQuery parameters = new RouteParametersQuery()
            {
                RouteId = routeId,
                ResponseFormat = "json"
            };

            string errorString;
            bool result = route4Me.RouteSharing(parameters, Email, out errorString);

            Console.WriteLine("");

            if (result)
            {
                Console.WriteLine("RouteSharing executed successfully");
            }
            else
            {
                Console.WriteLine("RouteSharing error {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Sharing a Route with someone by email
        ''' </summary>
        Public Sub RouteSharing(routeId As String, Email As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim rParameters As New RouteParametersQuery() With { _
                .RouteId = routeId, _
                .ResponseFormat = "jon"
            }

            ' Run the query
            Dim errorString As String = ""
            Dim result As Boolean = route4Me.RouteSharing(rParameters, Email, errorString)

            Console.WriteLine("")

            If result Then
                Console.WriteLine("Route Sharing executed successfully")
            Else
                Console.WriteLine("RouteSharing error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    route = r4m.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Route ID: {}'.format(response.route_id)
            data = {"recipient_email": "[email protected]",
                    "route_id": response.route_id,
                    "response_format": "json"}
            response = route.share_route(**data)
            print response

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    err := service.ShareRoute("route-id","[email protected]")
    if err != nil {
        // handle errors
        return
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Can't retrieve a random route ID");

// Share a route with an email
$params = array(
    "route_id"         => $route_id,
    "response_format"  => "json",
    "recipient_email"  => "[email protected]"
);

$result = $route->shareRoute($params);

var_dump($result);
unit ShareRouteUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TShareRoute = class(TBaseExample)
  public
    procedure Execute(RouteId: String; RecipientEmail: String);
  end;

implementation

procedure TShareRoute.Execute(RouteId: String; RecipientEmail: String);

var
  ErrorString: String;
begin
  Route4MeManager.Route.Share(RouteId, RecipientEmail, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
    WriteLn('ShareRoute executed successfully')
  else
    WriteLn(Format('ShareRoute error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY, true);

    const char* route_id = "CA902292134DBC134EAF8363426BD247";
    const char* email = "[email protected]";

    if(route.share_routes(route_id, email) == 0)
    {
        cout << "Delivered:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Failed: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
"use strict"

const path = require("path")
const debug = require("debug")("route4me-node:examples")

require("../init-examples-suite")
const helper  = require("./../../test/helper")

helper.describeIntegration(helper.toSuiteName(__filename), function T() {
  this.timeout(5000)
  this.slow(3000)
  it(path.basename(__filename), (done) => {
    // const Route4Me = require("route4me-node")

    const apiKey   = "11111111111111111111111111111111"
    const route4me = new Route4Me(apiKey)

    const routeId = "3A2DD89E6E1A044B2098AD1313E3138C"
    const email = "[email protected]"

    route4me.Routes.share(routeId, email, (err, nothing) => {
      debug("error  ", err)
      debug("result ", nothing)

      // Expectations about result
      expect(err).is.null

      expect(nothing).true

      // TODO: remove `done` call from examples
      done()
    })
  })
})
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 1);

    char route_id[] = "CA902292134DBC134EAF8363426BD247";
    char email[] = "[email protected]";

    if (!share_routes(route_id, email, "json"))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

POST
/actions/route/share_route.php?api_key=...&route_id=...&response_format=...

You can expect this API response:

{"status":true}

Update a Route

a) Update a route destination.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_id string Route ID GET
route_destination_id string Route destination ID GET
alias string Address alias POST
first_name string The first name of the receiving address. POST
last_name string The last name of the receiving address. POST
address string Destination address POST
address_stop_type string The type of stop: “PICKUP”, “DELIVERY”, “BREAK”, “MEETUP” POST
is_depot boolean If true, the address is a depot. POST
lat number Latitude POST
lng number Longitude POST
sequence_no integer The sequence number for the address. POST
is_visited boolean If true, the driver pressed the ‘Visited’ button. POST
is_departed boolean If true, the driver pressed the ‘Departed’ button. POST
timestamp_last_visited integer The timestamp when the address was last visited. POST
timestamp_last_departed integer The timestamp when the address was last departed POST
customer_po string The customer purchase order for the address. POST
invoice_no string The invoice number for the address. POST
reference_no string The reference number for the address. POST
order_no string The order number for the address. POST
order_id integer Parent order ID. POST
weight number Weight POST
cost number The cost of the order for the address. POST
revenue number The total revenue for the address. POST
cube number The cubic volume of cargo. POST
pieces integer Pieces POST
email string A valid e-mail address assigned to this stop. POST
phone string Customer Phone POST
time_window_start integer The time window start value, in seconds. POST
time_window_end integer The time window end value, in seconds. POST
time integer The service time, in seconds. POST
priority integer 0 is the highest priority; n has higher priority than n + 1 POST
curbside_lat number Curbside latitude POST
curbside_lng number Curbside Longitude POST
time_window_start_2 integer See time_window_start property POST
time_window_end_2 integer See time_window_end property POST
custom_fields array Any string array POST
<job id="Update Route Destination">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of updating a route destination.
      
      url="https://api.route4me.com/api.v4/address.php"
      apikey="11111111111111111111111111111111"
      routeid="CA902292134DBC134EAF8363426BD247"
      routedestinationid="174405640"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&route_destination_id="&routedestinationid
      
      jFile="update_route_destination_data.json"
      
      Set r4m=New Route4Me
      r4m.OutputFile="update_route_destination_RESPONSE.json"
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF
SET url=https://api.route4me.com/api.v4/address.php

SET apikey=11111111111111111111111111111111
SET routeid=CA902292134DBC134EAF8363426BD247
SET routedestinationid=174405640

:: The example demonstrates the process of updating a route destination.

ECHO ON

curl -o update_route_destination_RESPONSE.json -g -k -X PUT -H "Content-Type: application/json" -d "@update_route_destination_data.json" "%url%?api_key=%apikey%&route_id=%routeid%&route_destination_id=%routedestinationid%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address.php

apikey=11111111111111111111111111111111
routeid=CA902292134DBC134EAF8363426BD247
routedestinationid=174405640

# The example demonstrates the process of updating a route destination.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@update_route_destination_data.json" "$url?api_key=$apikey&route_id=$routeid&route_destination_id=$routedestinationid"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        public void UpdateRouteDestination()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager("11111111111111111111111111111111");

            // The example demonstrates the process of updating a route destination.

            string routeId = "824CA521E3A8DE9F1C684C8BAE90CF07";
            int routeDestionationId = 217393034;

            Dictionary<string, string> CustomData = new Dictionary<string, string>();
            CustomData.Add("BatchId", "e7c672b1-a356-4a97-803e-97db88fdcf99");
            CustomData.Add("CustomerNumber", "2788500");
            CustomData.Add("DeliveryId", "2c71f6d9-c1aa-4672-a682-3e9f12badac9");
            CustomData.Add("DeliveryInvoices", "<?xml version=\"1.0\" encoding=\"utf-16\"?>\u000d\u000a<!DOCTYPE EXAMPLEDelivery SYSTEM \"EXAMPLEDelivery.dtd\">\u000d\u000a<ArrayOfRouteDeliveryInvoice>\u000d\u000a  <RouteDeliveryInvoice>\u000d\u000a    <InvoiceNumber>999999</InvoiceNumber>\u000d\u000a    <InventoryIds>\u000d\u000a      <string>1790908</string>\u000d\u000a    </InventoryIds>\u000d\u000a    <IsRA>false</IsRA>\u000d\u000a    <IsDT>false</IsDT>\u000d\u000a    <IsINC>true</IsINC>\u000d\u000a    <IsPO>false</IsPO>\u000d\u000a    <IsPOPickup>false</IsPOPickup>\u000d\u000a  </RouteDeliveryInvoice>\u000d\u000a</ArrayOfRouteDeliveryInvoice>");
            CustomData.Add("DeliveryNotes", "");
            CustomData.Add("RouteId", "20191");

            // Run the query
            RouteParametersQuery routeParameters = new RouteParametersQuery()
            {
                RouteId = routeId
            };

            string errorString;
            DataObjectRoute dataObject = route4Me.GetRoute(routeParameters, out errorString);

            foreach (Address oAddress in dataObject.Addresses)
            {
                if (oAddress.RouteDestinationId == routeDestionationId)
                {
                    RouteParametersQuery routeParams = new RouteParametersQuery()
                    {
                        RouteId = routeId,
                        RouteDestinationId = oAddress.ContactId
                    };
                    oAddress.Alias = "Steele's - MONTICELLO";
                    oAddress.Cost = 5;
                    oAddress.InvoiceNo = 945825;
                    // etc fill the necessary address parameters
                    oAddress.CustomFields = CustomData;

                    errorString = "";
                    Address address = route4Me.UpdateRouteDestination(oAddress, out errorString);

                    Console.WriteLine("");

                    if (address != null)
                    {
                        Console.WriteLine("UpdateRouteDestination executed successfully");
                        Console.WriteLine("Alias {0}", address.Alias);
                        Console.WriteLine("Cost {0}", address.Cost);
                        Console.WriteLine("InvoiceNo {0}", address.InvoiceNo);
                        foreach (KeyValuePair<string, string> kvpair in address.CustomFields)
                        {
                            Console.WriteLine(kvpair.Key + ": " + kvpair.Value);
                        }
                    }
                    else
                    {
                        Console.WriteLine("UpdateRouteDestination error {0}", errorString);
                    }
                }
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Imports System.Collections.Generic

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub UpdateRouteDestination()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager("11111111111111111111111111111111")

            ' The example demonstrates the process of updating a route destination.

            Dim routeId As String = "824CA521E3A8DE9F1C684C8BAE90CF07"
            Dim routeDestionationId As Integer = 217393034

            Dim CustomData As New Dictionary(Of String, String)()
            CustomData.Add("BatchId", "e7c672b1-a356-4a97-803e-97db88fdcf99")
            CustomData.Add("CustomerNumber", "2718500")
            CustomData.Add("DeliveryId", "2c71f6d9-c1aa-4672-a682-3e9f12badac9")
            CustomData.Add("DeliveryInvoices", "<?xml version=""1.0"" encoding=""utf-16""?>" & vbCr & vbLf & "<!DOCTYPE EXAMPLEDelivery SYSTEM ""EXAMPLEDelivery.dtd"">" & vbCr & vbLf & "<ArrayOfRouteDeliveryInvoice>" & vbCr & vbLf & "  <RouteDeliveryInvoice>" & vbCr & vbLf & "    <InvoiceNumber>999999</InvoiceNumber>" & vbCr & vbLf & "    <InventoryIds>" & vbCr & vbLf & "      <string>1790908</string>" & vbCr & vbLf & "    </InventoryIds>" & vbCr & vbLf & "    <IsRA>false</IsRA>" & vbCr & vbLf & "    <IsDT>false</IsDT>" & vbCr & vbLf & "    <IsINC>true</IsINC>" & vbCr & vbLf & "    <IsPO>false</IsPO>" & vbCr & vbLf & "    <IsPOPickup>false</IsPOPickup>" & vbCr & vbLf & "  </RouteDeliveryInvoice>" & vbCr & vbLf & "</ArrayOfRouteDeliveryInvoice>")
            CustomData.Add("DeliveryNotes", "")
            CustomData.Add("RouteId", "20191")

            ' Run the query
            Dim routeParameters As New RouteParametersQuery() With { _
                .RouteId = routeId _
            }

            Dim errorString As String = ""
            Dim dataObject As DataObjectRoute = route4Me.GetRoute(routeParameters, errorString)

            For Each oAddress As Address In dataObject.Addresses
                If oAddress.RouteDestinationId = routeDestionationId Then
                    Dim routeParams As New RouteParametersQuery() With { _
                        .RouteId = routeId, _
                        .RouteDestinationId = oAddress.ContactId _
                    }
                    oAddress.[Alias] = "Steele's - MONTICELLO"
                    oAddress.Cost = 5
                    oAddress.InvoiceNo = 945825
                    ' etc fill the necessary address parameters
                    oAddress.CustomFields = CustomData

                    errorString = ""
                    Dim address As Address = route4Me.UpdateRouteDestination(oAddress, errorString)

                    Console.WriteLine("")

                    If address IsNot Nothing Then
                        Console.WriteLine("UpdateRouteDestination executed successfully")
                        Console.WriteLine("Alias {0}", address.[Alias])
                        Console.WriteLine("Cost {0}", address.Cost)
                        Console.WriteLine("InvoiceNo {0}", address.InvoiceNo)
                        For Each kvpair As KeyValuePair(Of String, String) In address.CustomFields
                            Console.WriteLine(kvpair.Key & ": " & kvpair.Value)
                        Next
                    Else
                        Console.WriteLine("UpdateRouteDestination error {0}", errorString)
                    End If
                End If
            Next
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
package com.route4me.sdk.examples.addresses;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Address;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class UpdateAddressAttribute {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager manager = new RoutingManager(apiKey);
        try {
            List<Route> routes = manager.getRoutes(new RoutesRequest().setLimit(10));
            Route route = manager.getRoute(new RoutesRequest().setId(routes.get(0).getId()));
            Address addr = manager.getAddress(route.getId(), route.getAddresses().get(1).getRouteDestinationId());
            addr.setAlias("New Alias");
            addr.addCustomField("NOTE 1", "Adding Custom Fields");
            Address address = manager.updateAddressAttribute(route.getId(), route.getAddresses().get(0).getRouteDestinationId(), addr);
            System.out.println(address);
        } catch (APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example demonstrates the process of updating a route destination.

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Can't retrieve a random route ID");

// Get a random address ID from selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($route_id);

$route->route_id = $route_id;
$route->route_destination_id = $addressRand['route_destination_id'];

// Update the route destination
$route->parameters = new \stdClass();

$route->addresses = array(Address::fromArray(array(
    "alias"                   =>  "new address alias",
    "first_name"              =>  "Edi",
    "last_name"               =>  "Jacobson",
    "address"                 =>  "230 Arbor Way Milledgeville GA 31061",
    "is_depot"                =>  false,
    "lat"                     =>  33.129695892334,
    "lng"                     =>  -83.24577331543,
    "sequence_no"             =>  9,
    "is_visited"              =>  true,
    "is_departed"             =>  false,
    "timestamp_last_visited"  =>  36000,
    "timestamp_last_departed" =>  null,
    "customer_po"             =>  "po_131324566",
    "invoice_no"              =>  "in549874",
    "reference_no"            =>  "7988544",
    "order_no"                =>  "on654754",
    "order_id"                =>  4564,
    "weight"                  =>  45,
    "cost"                    =>  55.60,
    "revenue"                 =>  75.80,
    "cube"                    =>  3,
    "pieces"                  =>  30,
    "email"                   =>  "[email protected]",
    "phone"                   =>  "111-222-333",
    "time_window_start"       =>  36600,
    "time_window_end"         =>  37200,
    "time"                    =>  600,
    "priority"                =>  1,
    "curbside_lat"            =>  33.129695892334,
    "curbside_lng"            =>  -83.24577331543,
    "time_window_start_2"     =>  39400,
    "time_window_end_2"       =>  40000
)));

$route->httpheaders = 'Content-type: application/json';

$result = $route->updateAddress();

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/address.php?api_key=...&route_id=...&route_destination_id=...

You can expect this API response:

{
    "route_destination_id": 174405640,
    "alias": "new address alias",
    "member_id": 1,
    "address": "230 Arbor Way Milledgeville GA 31061",
    "is_depot": false,
    "timeframe_violation_state": null,
    "timeframe_violation_time": 0,
    "timeframe_violation_rate": 0,
    "lat": 33.129695892334,
    "lng": -83.24577331543,
    "curbside_lat": 33.129695892334,
    "curbside_lng": -83.24577331543,
    "priority": 1,
    "route_id": "CA902292134DBC134EAF8363426BD247",
    "original_route_id": null,
    "optimization_problem_id": "622D999019C839BD9102D6459D125E23",
    "sequence_no": 9,
    "geocoded": false,
    "preferred_geocoding": null,
    "failed_geocoding": false,
    "geocodings": [],
    "contact_id": 0,
    "order_id": 4564,
    "address_stop_type": "DELIVERY",
    "is_visited": true,
    "timestamp_last_visited": 36000,
    "visited_lat": null,
    "visited_lng": null,
    "is_departed": false,
    "departed_lat": null,
    "departed_lng": null,
    "timestamp_last_departed": null,
    "group": null,
    "customer_po": "po_131324566",
    "invoice_no": "in549874",
    "reference_no": "7988544",
    "order_no": "on654754",
    "weight": 45,
    "cost": 55.6,
    "revenue": 75.8,
    "cube": 3,
    "pieces": 30,
    "first_name": "Edi",
    "last_name": "Jacobson",
    "email": "[email protected]",
    "phone": "111-222-333",
    "destination_note_count": 0,
    "drive_time_to_next_destination": 0,
    "abnormal_traffic_time_to_next_destination": null,
    "uncongested_time_to_next_destination": null,
    "traffic_time_to_next_destination": null,
    "distance_to_next_destination": 0,
    "channel_name": "f8dc104f30ec453b946f08b32a38c931",
    "generated_time_window_start": null,
    "generated_time_window_end": null,
    "time_window_start": 36600,
    "time_window_end": 37200,
    "time_window_start_2": 39400,
    "time_window_end_2": 40000,
    "geofence_detected_visited_timestamp": null,
    "geofence_detected_departed_timestamp": null,
    "geofence_detected_service_time": null,
    "geofence_detected_visited_lat": null,
    "geofence_detected_visited_lng": null,
    "geofence_detected_departed_lat": null,
    "geofence_detected_departed_lng": null,
    "time": 600,
    "tracking_number": "Y31Q1E6X",
    "custom_fields": {
        "animal": "lion",
        "bird": "canary"
    },
    "custom_fields_str_json": "{\"animal\":\"lion\",\"bird\":\"canary\"}",
    "custom_fields_config": null,
    "custom_fields_config_str_json": "null",
    "notes": []
}

b) Update the custom data of the route destinations.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_id string Route ID GET
route_destination_id string Route destination ID GET
custom_fields array Any string array POST
<job id="Update Route Destination Custom Data">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."

      ' The example demonstrates the process of updating the custom data of a route destination.

      url="https://api.route4me.com/api.v4/address.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      routedestinationid="160940135"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&route_destination_id="&routedestinationid
      
      jFile="update_route_destination_custom_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/address.php

SET apikey=11111111111111111111111111111111
SET routeid=CA902292134DBC134EAF8363426BD247
SET routedestinationid=174405640

:: The example demonstrates the process of updating the custom data of a route destination.

ECHO ON

curl -o file1.txt -g -k -X PUT -H "Content-Type: application/json" -d "@update_route_destination_custom_data.json" "%url%?api_key=%apikey%&route_id=%routeid%&route_destination_id=%routedestinationid%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address.php

apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
routedestinationid=160940135

# The example demonstrates the process of updating the custom data of a route destination.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@update_route_destination_custom_data.json" "$url?api_key=$apikey&route_id=$routeid&route_destination_id=$routedestinationid"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        public void UpdateRouteCustomData(string routeId, int routeDestionationId, Dictionary<string, string> CustomData)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            // The example demonstrates the process of updating the custom data of a route destination.

            // Run the query
            RouteParametersQuery parameters = new RouteParametersQuery()
            {
                RouteId = routeId,
                RouteDestinationId = routeDestionationId
            };

            string errorString;
            Address result = route4Me.UpdateRouteCustomData(parameters, CustomData, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("UpdateRouteCustomData executed successfully");
                Console.WriteLine("Route ID: {0}", result.RouteId);
                Console.WriteLine("Route Destination ID: {0}", result.RouteDestinationId);
            }
            else
            {
                Console.WriteLine("UpdateRouteCustomData error {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    ''' <summary>
    ''' Update Route Custom Data
    ''' </summary>
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub UpdateRouteCustomData(routeId As String, routeDestionationId As Integer, CustomData As Dictionary(Of String, String))
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim routeParameters As New RouteParametersQuery() With { _
                .RouteId = routeId, _
                .RouteDestinationId = routeDestionationId
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As Address = route4Me.UpdateRouteCustomData(routeParameters, CustomData, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("UpdateRouteCustomData executed successfully")

                Console.WriteLine("Route ID: {0}", dataObject.RouteId)
                Console.WriteLine("Route Destination ID: {0}", dataObject.RouteDestinationId)
            Else
                Console.WriteLine("UpdateRouteCustomData error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    route = r4m.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Route ID: {}'.format(response.route_id)
            route_destination_id = response.addresses[1].route_destination_id
            print 'Route Destination ID: {}'.format(route_destination_id)
            data = {"route_destination_id": route_destination_id,
                    "route_id": response.route_id,
                    "custom_fields": {"SDK": "Python"}
                    }
            response = route.update_route_destination_custom_data(**data)
            print 'Optimization Problem ID: {}'.format(response.optimization_problem_id)
            print 'Route ID: {}'.format(response.route_id)
            print '\tAddress: {0}'.format(response.address)
            print '\tRoute Destination ID: {0}'.format(response.route_destination_id)
            print '\tCustom Fields: {0}'.format(response.custom_fields)

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  updated, err := service.UpdateAddress(address)
  if err != nil {
    // handle errors
    return
  }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example demonstrates the process of updating the custom data of a route destination.

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Can't retrieve a random route ID");

// Get a random address ID from selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($route_id);

$route->route_id = $route_id;
$route->route_destination_id = $addressRand['route_destination_id'];

// Update destination custom data
$route->parameters = new \stdClass();

$route->parameters->custom_fields = array(
        "animal"  => "tiger",
        "bird"    => "canary"
);

$route->httpheaders = 'Content-type: application/json';

$result = $route->updateAddress();

Route4Me::simplePrint($result);
unit UpdateRoutesCustomFieldsUnit;

interface

uses SysUtils, BaseExampleUnit, CommonTypesUnit;

type
  TUpdateRoutesCustomFields = class(TBaseExample)
  public
    procedure Execute(RouteId: String; RouteDestinationId: integer);
  end;

implementation

procedure TUpdateRoutesCustomFields.Execute(RouteId: String;

  RouteDestinationId: integer);

var
  ErrorString: String;
  CustomFields: TListStringPair;
begin
  CustomFields := TListStringPair.Create;
  try
    CustomFields.Add(TStringPair.Create('animal', 'lion'));
    CustomFields.Add(TStringPair.Create('form', 'rectangle'));

    Route4MeManager.Route.UpdateCustomFields(RouteId, RouteDestinationId,
      CustomFields, ErrorString);

    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn('UpdateCustomFields executed successfully');
      WriteLn(Format('Route ID: %s', [RouteId]));
    end
    else
      WriteLn(Format('UpdateCustomFields error: %s', [ErrorString]));
  finally
    FreeAndNil(CustomFields);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";
    const char *route_destination_id = "174405709A";

    ifstream inf("update_route_destination_custom_data.json");
    if(!inf.is_open()) {
      cout << "Can't find a file with route data" << endl;
      return -1;
    }
    Json::Value input_data;
    inf >> input_data;

    if (route.update_route(route_id, route_destination_id, input_data) == 0) {
       cout << "Route updated:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
       cout << "Error updating route: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
       ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);
    char* data = NULL;

    char route_id[] = "CA902292134DBC134EAF8363426BD247";
    char dest_id[] = "174405709A";
    char file_name[] = "update_route_destination_custom_data.json";

    deserialize(file_name, &data);
    printf("Data: %s\n", data);

    if (!update_route(route_id, dest_id, data))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    if (data)
    {
       free(data);
    }
    cleanUp();
  return 0;
}


HTTP Request

PUT
/api.v4/address.php?api_key=...&route_id=...&route_destination_id=...

You can expect this API response:

{
    "route_destination_id": 160940135,
    "alias": "",
    "member_id": 177496,
    "address": "Dronning Olgas Vej 26, 2000 Frederiksberg, Denmark",
    "is_depot": true,
    "timeframe_violation_state": null,
    "timeframe_violation_time": 0,
    "timeframe_violation_rate": 0,
    "lat": 55.6884868,
    "lng": 12.5366426,
    "curbside_lat": 55.6884868,
    "curbside_lng": 12.5366426,
    "priority": null,
    "route_id": "5C15E83ABBBBBBCD1537955D28D51D7",
    "original_route_id": "",
    "route_name": null,
    "optimization_problem_id": null,
    "sequence_no": 0,
    "geocoded": false,
    "preferred_geocoding": null,
    "failed_geocoding": false,
    "geocodings": [],
    "contact_id": 0,
    "address_stop_type": "DELIVERY",
    "is_visited": false,
    "timestamp_last_visited": null,
    "visited_lat": null,
    "visited_lng": null,
    "is_departed": false,
    "departed_lat": null,
    "departed_lng": null,
    "timestamp_last_departed": null,
    "group": null,
    "customer_po": null,
    "invoice_no": null,
    "reference_no": null,
    "order_no": null,
    "weight": 0,
    "cost": 0,
    "revenue": 0,
    "cube": 0,
    "pieces": 0,
    "first_name": null,
    "last_name": null,
    "email": null,
    "phone": null,
    "destination_note_count": 0,
    "drive_time_to_next_destination": 0,
    "abnormal_traffic_time_to_next_destination": null,
    "uncongested_time_to_next_destination": null,
    "traffic_time_to_next_destination": null,
    "distance_to_next_destination": 0,
    "channel_name": "3f9506ab1bf7607d4f8edbdb53676a1b",
    "generated_time_window_start": null,
    "generated_time_window_end": null,
    "time_window_start": null,
    "time_window_end": null,
    "time_window_start_2": null,
    "time_window_end_2": null,
    "geofence_detected_visited_timestamp": null,
    "geofence_detected_departed_timestamp": null,
    "geofence_detected_service_time": null,
    "geofence_detected_visited_lat": null,
    "geofence_detected_visited_lng": null,
    "geofence_detected_departed_lat": null,
    "geofence_detected_departed_lng": null,
    "time": 0,
    "custom_fields": {
        "animal": "lion"
    },
    "custom_fields_str_json": "{\"animal\":\"lion\"}",
    "custom_fields_config": null,
    "custom_fields_config_str_json": "null",
    "notes": []
}

c) Update a route’s specified parameters.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_id string Route ID GET
input data Route parameters A valid JSON object string. See the Route Parameters JSON Schema as a guide. POST
<job id="Update Route">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."

      ' The example demonstrates the process of updating the parameters of a route.

      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      
      jFile="update_route_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  /// <summary>
  /// Update Route Parameters
  /// </summary>
  public sealed partial class Route4MeExamples
  {
    public void UpdateRoute(string routeId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      RouteParameters parametersNew = new RouteParameters()
      {
        RouteName = "New name of the route"
      };

      RouteParametersQuery routeParameters = new RouteParametersQuery()
      {
        RouteId = routeId,
        Parameters = parametersNew
      };

      // Run the query
      string errorString;
      DataObjectRoute dataObject = route4Me.UpdateRoute(routeParameters, out errorString);

      Console.WriteLine("");

      if (dataObject != null)
      {
        Console.WriteLine("UpdateRoute executed successfully");

        Console.WriteLine("Route ID: {0}", dataObject.RouteID);
        Console.WriteLine("State: {0}", dataObject.State);
      }
      else
      {
        Console.WriteLine("UpdateRoute error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    ''' <summary>
    ''' Update Route Parameters
    ''' </summary>
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub UpdateRoute(routeId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim parametersNew As New RouteParameters() With { _
                .RouteName = "New name of the route" _
            }

            Dim routeParameters As New RouteParametersQuery() With { _
                .RouteId = routeId, _
                .Parameters = parametersNew _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As DataObjectRoute = route4Me.UpdateRoute(routeParameters, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("UpdateRoute executed successfully")

                Console.WriteLine("Route ID: {0}", dataObject.RouteID)
                Console.WriteLine("State: {0}", dataObject.State)
            Else
                Console.WriteLine("UpdateRoute error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    optimization = r4m.optimization
    address = r4m.address
    optimization.algorithm_type(ALGORITHM_TYPE.TSP)
    optimization.share_route(0)
    optimization.store_route(0)
    optimization.route_time(0)
    optimization.route_max_duration(86400)
    optimization.vehicle_capacity(1)
    optimization.vehicle_max_distance_mi(10000)
    optimization.route_name('Single Driver Round Trip')
    optimization.optimize(OPTIMIZE.DISTANCE)
    optimization.distance_unit(DISTANCE_UNIT.MI)
    optimization.device_type(DEVICE_TYPE.WEB)
    optimization.travel_mode(TRAVEL_MODE.DRIVING)
    address.add_address(
        address='754 5th Ave New York, NY 10019',
        lat=40.7636197,
        lng=-73.9744388,
        alias='Bergdorf Goodman',
        is_depot=1,
        time=0
    )
    address.add_address(
        address='717 5th Ave New York, NY 10022',
        lat=40.7669692,
        lng=-73.9693864,
        alias='Giorgio Armani',
        time=0
    )
    address.add_address(
        address='888 Madison Ave New York, NY 10014',
        lat=40.7715154,
        lng=-73.9669241,
        alias='Ralph Lauren Women\'s and Home',
        time=0
    )
    address.add_address(
        address='1011 Madison Ave New York, NY 10075',
        lat=40.7772129,
        lng=-73.9669,
        alias='Yigal Azrou\u00ebl',
        time=0
    )
    address.add_address(
        address='440 Columbus Ave New York, NY 10024',
        lat=40.7808364,
        lng=-73.9732729,
        alias='Frank Stella Clothier',
        time=0
    )
    address.add_address(
        address='324 Columbus Ave #1 New York, NY 10023',
        lat=40.7803123,
        lng=-73.9793079,
        alias='Liana',
        time=0
    )
    address.add_address(
        address='110 W End Ave New York, NY 10023',
        lat=40.7753077,
        lng=-73.9861529,
        alias='Toga Bike Shop',
        time=0
    )

    response = r4m.run_optimization()

    parameters = {"parameters": {"member_id":  1,
                                 "route_name": "Route name updated"
                                 }
                  }

    route_id = response.addresses[1].route_id

    response = r4m.update_route_parameters(parameters, route_id)

    print 'Route Name: {}'.format(response.parameters.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.routes;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Parameters;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class UpdateRouteParameters {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager routeManager = new RoutingManager(apiKey);
        try {
            List<Route> routes = routeManager.getRoutes(new RoutesRequest().setLimit(10));
            // fetches complete data
            Route r = routeManager.getRoute(new RoutesRequest().setId(routes.get(0).getId()));
            Parameters params = r.getParameters();
            params.setIp("192168100100");
            Route newRoute = routeManager.updateRoute(r);
            System.out.println(newRoute);
        } catch (APIException e) {
            // handle exceptions
            e.printStackTrace();
        }
    }
}
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
  
  route.Field = "updated value"
  updated, err := service.UpdateRoute(route)
  if err != nil {
    // handle errors
    return
  }
  // do something with the updated route
}
package UpdateRoute;
use strict;
use warnings FATAL => 'all';

sub UpdateRoute {
    my ($self, $routeId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $parametersNew = RouteParameters->new ({
        route_name => "New name of the route"
        });

    my $routeParameters = RouteParametersQuery->new({
            route_id => $routeId,
            parameters => $parametersNew
        });

    my $errorString = "";

    my $dataObject = $route4Me->updateRoute( $routeParameters, \$errorString );

    print "\n";

    if ($dataObject) {
        print "UpdateRoute executed successfully\n";
        printf "Route ID: %s\n", $dataObject->route_id;
        printf "State: %s\n", OptimizationState->get_optimization_state($dataObject->state);
    } else {
        printf "UpdateRoute error: %s\n", $errorString;
    }
}
1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7

ECHO ON

:: The example demonstrates the process of updating the parameters of a route.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@update_route_data.json" "%url%?route_id=%routeid%&api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7

# The example demonstrates the process of updating the parameters of a route.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@update_route_data.json" "$url?route_id=$routeid&api_key=$apikey"

echo "Finished..."

sleep 15
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example demonstrates the process of updating the parameters of a route.

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Can't retrieve a random route ID");

$randomRoute = $route->getRoutes(array('route_id' => $route_id));
assert(!is_null($randomRoute), "Can't retrieve a random route ID");

// Update the route parameters
$route->route_id = $route_id;

$route->parameters = new \stdClass();

$route->parameters = array(
    "member_id"           => $randomRoute->member_id,
    "optimize"            => "Distance",
    "route_max_duration"  => "82400",
    "route_name"          => "updated " . date('m-d-Y')
);

$route->httpheaders = 'Content-type: application/json';

$result = $route->update();

Route4Me::simplePrint((array)$result->parameters);
unit UpdateRouteUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TUpdateRoute = class(TBaseExample)
  public
    procedure Execute(RouteId: String);
  end;

implementation

uses RouteParametersUnit, RouteParametersQueryUnit, DataObjectUnit, EnumsUnit;

procedure TUpdateRoute.Execute(RouteId: String);

var
  RouteParameters: TRouteParametersQuery;
  ErrorString: String;
  Route: TDataObjectRoute;
begin
  RouteParameters := TRouteParametersQuery.Create;
  try
    RouteParameters.RouteId := RouteId;
    RouteParameters.Parameters := TRouteParameters.Create;
    TRouteParameters(RouteParameters.Parameters.Value).RouteName := 'New name of the route';

    Route := Route4MeManager.Route.Update(RouteParameters, ErrorString);

    WriteLn('');
    try
      if (Route <> nil) then
      begin
        WriteLn('UpdateRoute executed successfully');
        WriteLn(Format('Route ID: %s', [Route.RouteId]));
      end
      else
        WriteLn(Format('UpdateRoute error: %s', [ErrorString]));
    finally
      FreeAndNil(Route);
    end;
  finally
    FreeAndNil(RouteParameters);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/route.php?api_key=...&route_id=...


See the sample JSON response of this method.


d) Recompute the route directions

By sending recompute_directions=1, we request that the route directions be recomputed (note that this does happen automatically if specific properties of the route are updated, such as stop sequence_no changes).

<job id="Recompute Route Directions">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example demonstrates the process of recomputing route directions.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="79F570D5523C8156955786789DACDEC8"
      
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&recompute_directions=1"
      
      jFile="update_route_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET routeid=79F570D5523C8156955786789DACDEC8

ECHO ON

:: The example demonstrates the process of recomputing route directions.

curl -o file1.txt -g -k -X PUT -H "Content-Type: application/json" -d "@recompute_directions_data.json" "%url%?route_id=%routeid%&api_key=%apikey%&recompute_directions=1"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid=79F570D5523C8156955786789DACDEC8

# The example demonstrates the process of recomputing route directions.

curl -o file1.txt -g -k -X PUT -H "Content-Type: application/json" -d "@recompute_directions_data.json" "$url?route_id=$routeid&api_key=$apikey&recompute_directions=1"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example demonstrates the process of recomputing route directions.

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Can't retrieve a random route ID");

$randomRoute = $route->getRoutes(array('route_id' => $route_id));
assert(!is_null($randomRoute), "Can't retrieve a random route ID");

// Recompute the route directions
$route->route_id = $route_id;

$route->parameters = new \stdClass();

$route->parameters = array( 
    "recompute_directions" => 1
);

$route->httpheaders = 'Content-type: application/json';

$result = $route->update();

Route4Me::simplePrint((array)$result->parameters);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/route.php?api_key=...&route_id=...recompute_directions=...


See the sample JSON response of this method.


e) Unlink a route from master optimization

PARAMETERS

Parameter Type Description  
api_key string API key of the user  
route_id string Route ID GET
unlink_from_master_optimization boolean If true, a route is unlinked from master optimization.  
<job id="Unlink Route From Optimization">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example refers to the process of unlinking a route from master optimization.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/route.php"
			apikey="11111111111111111111111111111111"
			routeid="34171F062292E3CBEB163FFE281464A9"
			
			url=url&"?api_key="&apikey
			url=url&"&route_id="&routeid
			
			jFile="unlink_route_data.json"
			
			Set r4m=New Route4Me
			r4m.OutputFile="unlink_route_RESPONSE.json"
			
			r4m.HttpPutRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET routeid=34171F062292E3CBEB163FFE281464A9

ECHO ON

:: The example refers to the process of unlinking a route from master optimization.

curl -o unlink_route_RESPONSE.json -g -k -X PUT -H "Content-Type: application/json" -d "@unlink_route_data.json" "%url%?route_id=%routeid%&api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid=34171F062292E3CBEB163FFE281464A9

 # The example refers to the process of unlinking a route from master optimization.

curl -o unlink_route_RESPONSE.json -g -k -X PUT -H "Content-Type: application/json" -d "@unlink_route_data.json" "$url?route_id=$routeid&api_key=$apikey"

echo "Finished..."

sleep 15
public void UnlinkRouteFromOptimizationTest()
{
	var route4Me = new Route4MeManager(c_ApiKey);

	string routeId = tdr.SD10Stops_route_id;
	Assert.IsNotNull(routeId, "routeId_SingleDriverRoute10Stops is null.");

	var routeDuplicateParameters = new RouteParametersQuery()
	{
		RouteId = routeId
	};

	// Run the query
	var duplicatedRouteId = route4Me.DuplicateRoute(routeDuplicateParameters, out string errorString);

	Assert.IsNotNull(duplicatedRouteId, "Cannot duplicate a route. "+ errorString);
	Assert.IsTrue(duplicatedRouteId.Length==32, "Cannot duplicate a route.");

	var duplicatedRoute = route4Me.GetRoute(
		new RouteParametersQuery() { RouteId = duplicatedRouteId }, 
		out errorString);

	Assert.IsNotNull(duplicatedRoute, "Cannot retrieve the duplicated route.");
	Assert.IsInstanceOfType(
		duplicatedRoute, 
		typeof(DataObjectRoute), 
		"Cannot retrieve the duplicated route.");
	Assert.IsNotNull(duplicatedRoute.OptimizationProblemId, "Optimization problem ID of the duplicated route is null.");

	var routeParameters = new RouteParametersQuery()
	{
		RouteId = duplicatedRouteId,
		UnlinkFromMasterOptimization = true
	};

	lsOptimizationIDs.Add(duplicatedRoute.OptimizationProblemId);

	// Run the query
	var unlinkedRoute = route4Me.UpdateRoute(routeParameters, out errorString);

	Assert.IsNotNull(unlinkedRoute, "UnlinkRouteFromOptimizationTest failed. " + errorString);
	Assert.IsNull(unlinkedRoute.OptimizationProblemId, "Optimization problem ID of the unlinked route is not null.");
}
Public Sub UnlinkRouteFromOptimizationTest()
	Dim route4Me = New Route4MeManager(c_ApiKey)

	Dim routeId As String = tdr.SD10Stops_route_id

	Assert.IsNotNull(routeId, "routeId_SingleDriverRoute10Stops is null.")

	Dim routeDuplicateParameters = New RouteParametersQuery() With {
		.RouteId = routeId
	}

	Dim errorString As String = Nothing
	Dim duplicatedRouteId = route4Me.DuplicateRoute(routeDuplicateParameters, errorString)

	Thread.Sleep(3000)

	Assert.IsNotNull(duplicatedRouteId, "Cannot duplicate a route. " & errorString)
	Assert.IsTrue(duplicatedRouteId.Length = 32, "Cannot duplicate a route.")

	Dim duplicatedRoute = route4Me.GetRoute(New RouteParametersQuery() With {
		.RouteId = duplicatedRouteId
	}, errorString)

	Assert.IsNotNull(duplicatedRoute, "Cannot retrieve the duplicated route.")
	Assert.IsInstanceOfType(duplicatedRoute, GetType(DataObjectRoute), "Cannot retrieve the duplicated route.")
	Assert.IsNotNull(duplicatedRoute.OptimizationProblemId, "Optimization problem ID of the duplicated route is null.")

	Dim routeParameters = New RouteParametersQuery() With {
		.RouteId = duplicatedRouteId,
		.UnlinkFromMasterOptimization = True
	}

	lsOptimizationIDs.Add(duplicatedRoute.OptimizationProblemId)

	Dim unlinkedRoute = route4Me.UpdateRoute(routeParameters, errorString)

	Assert.IsNotNull(unlinkedRoute, "UnlinkRouteFromOptimizationTest failed. " & errorString)
	Assert.IsNull(unlinkedRoute.OptimizationProblemId, "Optimization problem ID of the unlinked route is not null.")
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php

namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example refers to the process of unlinking a route from master optimization.

$route = new Route();

// Get a random route ID
$route_id = $route->getRandomRouteId(0, 10);
assert(!is_null($route_id), "Cannot retrieve a random route ID");

// Unlink a route from master destination.
$route->route_id = $route_id;
$route->parameters = new \stdClass();

$route->parameters = [
    'unlink_from_master_optimization' => true,
];

$route->httpheaders = 'Content-type: application/json';

$result = $route->update();

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/route.php?api_key=...&route_id=...


See the sample JSON response of this method.


Get Schedule Calendar

Get the scheduled events from a user’s account.

PARAMETERS

Parameter Type Description
api_key string API key of the user
date_from_string string Start date
date_to_string string End date
timezone_offset_minutes integer Time zone offset in minutes
orders boolean If true, show orders count in the response
ab boolean If true, show address book contacts count in the response
routes_count boolean If true, show routes count in the response
<job id="Get Schedule Calendar">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			WScript.Echo "Please, press OK and wait..."
			
			' The example refers to the process of getting the schedule calendar.
			' The example requires an API key with the enterprise subscription.
			
			url="https://api.route4me.com/api/schedule_calendar_data.php"
			apikey="11111111111111111111111111111111"
			date_from_string="2020-10-20"
			date_to_string="2020-11-20"
			timezone_offset_minutes=-240
			orders=1
			ab=1
			routes_count=1
			
			url=url&"?api_key="&apikey
			url=url&"&date_from_string="&date_from_string
			url=url&"&date_to_string="&date_to_string
			url=url&"&timezone_offset_minutes="&timezone_offset_minutes
			url=url&"&orders="&orders
			url=url&"&ab="&ab
			url=url&"&routes_count="&routes_count
			
			Set r4m=New Route4Me
			r4m.OutputFile="get_schedule_calendar_RESPONSE.json"
			
			r4m.HttpGetRequest url
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api/schedule_calendar_data.php

SET apikey=11111111111111111111111111111111

SET date_from_string="2020-10-20"
SET date_to_string="2020-11-20"
SET timezone_offset_minutes=-240
SET orders=true
SET ab=true
SET routes_count=true

:: The example refers to the process of getting the schedule calendar.
:: The example requires an API key with the enterprise subscription.

ECHO ON

curl -o get_schedule_calendar_RESPONSE.json -g -k -X GET "%url%?route_id=%routeid%&api_key=%apikey%&date_from_string=%date_from_string%&date_to_string=%date_to_string%&timezone_offset_minutes=%timezone_offset_minutes%&orders=%orders%&ab=%ab%&routes_count=%routes_count%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api/schedule_calendar_data.php
apikey=11111111111111111111111111111111

date_from_string="2020-10-20"
date_to_string="2020-11-20"
timezone_offset_minutes=-240
orders=true
ab=true
routes_count=true

 # The example refers to the process of getting the schedule calendar.
 # The example requires an API key with the enterprise subscription.

curl -o get_schedule_calendar_RESPONSE.json -g -k -X GET "$url?api_key=$apikey&date_from_string=$date_from_string&date_to_string=$date_to_string&timezone_offset_minutes=$timezone_offset_minutes&orders=$orders&ab=$ab&routes_count=$routes_count"

echo "Finished..."

sleep 15
public void GetScheduleCalendarTest()
{
	var route4Me = new Route4MeManager(c_ApiKey);

	if (!route4Me.MemberHasCommercialCapability(c_ApiKey, ApiKeys.demoApiKey, out string errorString0)) return;

	TimeSpan days5 = new TimeSpan(5, 0, 0, 0);

	var calendarQuery = new ScheduleCalendarQuery()
	{
		DateFromString = (DateTime.Now - days5).ToString("yyyy-MM-dd"),
		DateToString = (DateTime.Now + days5).ToString("yyyy-MM-dd"),
		TimezoneOffsetMinutes = 4*60,
		ShowOrders = true,
		ShowContacts = true,
		RoutesCount = true
	};

	var scheduleCalendar = route4Me.GetScheduleCalendar(calendarQuery, out string errorString);

	Assert.IsNotNull(scheduleCalendar, "The test GetScheduleCalendarTest failed");

	Assert.IsNotNull(scheduleCalendar.AddressBook, "The test GetScheduleCalendarTest failed");
	Assert.IsNotNull(scheduleCalendar.Orders, "The test GetScheduleCalendarTest failed");
	Assert.IsNotNull(scheduleCalendar.RoutesCount, "The test GetScheduleCalendarTest failed");
}
Public Sub GetScheduleCalendarTest()
	Dim route4Me = New Route4MeManager(c_ApiKey)

	Dim errorString0 As String = Nothing
	If Not route4Me.MemberHasCommercialCapability(c_ApiKey, ApiKeys.demoApiKey, errorString0) Then Return

	Dim days5 As TimeSpan = New TimeSpan(5, 0, 0, 0)

	Dim calendarQuery = New ScheduleCalendarQuery() With {
		.DateFromString = (DateTime.Now - days5).ToString("yyyy-MM-dd"),
		.DateToString = (DateTime.Now + days5).ToString("yyyy-MM-dd"),
		.TimezoneOffsetMinutes = 4 * 60,
		.ShowOrders = True,
		.ShowContacts = True,
		.RoutesCount = True
	}

	Dim errorString As String = Nothing
	Dim scheduleCalendar = route4Me.GetScheduleCalendar(calendarQuery, errorString)

	Assert.IsNotNull(scheduleCalendar, "The test GetScheduleCalendarTest failed")
	Assert.IsNotNull(scheduleCalendar.AddressBook, "The test GetScheduleCalendarTest failed")
	Assert.IsNotNull(scheduleCalendar.Orders, "The test GetScheduleCalendarTest failed")
	Assert.IsNotNull(scheduleCalendar.RoutesCount, "The test GetScheduleCalendarTest failed")
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php

namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// The example requires an API key with the enterprise subscription.

// Set the api key in the Route4Me class
Route4Me::setApiKey('E60AA4276C4A321FE4AF62D0705D346E');

$now            = new \DateTime();

$schedCalendarParams = new ScheduleCalendarParameters();

$schedCalendarParams->date_from_string   = $now->add(\DateInterval::createFromDateString('-5 days'))->format('Y-m-d');
$schedCalendarParams->date_to_string     = $now->add(\DateInterval::createFromDateString('5 days'))->format('Y-m-d');
$schedCalendarParams->orders             = true;
$schedCalendarParams->ab                 = true;
$schedCalendarParams->routes_count       = true;

$scheduleCalendar = $schedCalendarParams->getScheduleCalendar($schedCalendarParams);

Route4Me::simplePrint($scheduleCalendar);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/optimization_problem.php?api_key=...


See the sample JSON response of this method.


Orders

An order is a document to deliver freight to another party, either coming from a consignee, shipper, freight owner, terminal operator, carrier, or warehouseman.

See the Order JSON Schema in our GitHub repository.

Order Properties

Attribute Type Description
api_key string API key of the user
address_1 string Address #1 field
address_2 string Address #2 field
cached_lat double Cached latitude
cached_lng double Cached longitude
curbside_lat double Curbside latitude
curbside_lng double Curbside longitude
color string The order icon’s color on the map.
address_alias string Address alias
address_city string The city the address is located in.
day_scheduled_for_YYMMDD string The date the order was scheduled for.
local_time_window_start integer The start of a time window to service the order.
The value must be in Epoch time.
local_time_window_end integer The end of a time window to service the order.
The value must be in Epoch time.
local_time_window_start_2 integer The start of another time window to service the order.
The value must be in Epoch time.
local_time_window_end_2 integer The end of another time window to service the order.
The value must be in Epoch time.
service_time integer The amount of time, in Epoch format, required to service the order.
The value can’t be longer or higher than the duration of a given time window’s start and end time.
See the local_time_window_start and local_time_window_end attributes for reference.
EXT_FIELD_first_name string The first name of the receiving address.
EXT_FIELD_last_name string The last name of the receiving address.
EXT_FIELD_email string Address email
EXT_FIELD_phone string The phone number for the address.
EXT_FIELD_custom_data array The custom data of the order.
order_icon string The URL to an order icon file.

Create an Order

Add an order to the user’s account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data POST data A valid JSON object string. See the Order JSON Schema as a guide.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of adding an order to the user's account using HTTP POST data.

curl -o file1.txt -k -g -X POST -H "Content-Type: application/json" -d "@add_order_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111

# The example demonstrates the process of adding an order to the user's account using HTTP POST data.

curl -o file1.txt -k -g -X POST -H "Content-Type: application/json" -d "@add_order_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Add Order
    /// </summary>
    /// <returns> Added Order </returns>
    public Order AddOrder()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      Order order = new Order()
      {
        Address1 = "Test Address1 " + (new Random()).Next().ToString(),
        AddressAlias = "Test AddressAlias " + (new Random()).Next().ToString(),
        CachedLatitude = 37.773972,
        CachedLongitude = -122.431297
      };

      // Run the query
      string errorString;
      Order resultOrder = route4Me.AddOrder(order, out errorString);

      Console.WriteLine("");

      if (resultOrder != null)
      {
        Console.WriteLine("AddOrder executed successfully");

        Console.WriteLine("Order ID: {0}", resultOrder.OrderId);

        return resultOrder;
      }
      else
      {
        Console.WriteLine("AddOrder error: {0}", errorString);

        return null;
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Add Order
        ''' </summary>
        ''' <returns> Added Order </returns>
        Public Function AddOrder() As Order
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim order As New Order() With { _
                .Address1 = "Test Address1 " + (New Random()).[Next]().ToString(), _
                .AddressAlias = "Test AddressAlias " + (New Random()).[Next]().ToString(), _
                .CachedLatitude = 37.773972, _
                .CachedLongitude = -122.431297 _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim resultOrder As Order = route4Me.AddOrder(order, errorString)

            Console.WriteLine("")

            If resultOrder IsNot Nothing Then
                Console.WriteLine("AddOrder executed successfully")

                Console.WriteLine("Order ID: {0}", resultOrder.OrderId)

                Return resultOrder
            Else
                Console.WriteLine("AddOrder error: {0}", errorString)

                Return Nothing
            End If
        End Function
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    order = route4me.order
    url = "http://www.bk.com/restaurants/ny/new-york/106-fulton-st-17871.html"
    data = {'address_1': '106 Fulton St, Farmingdale, NY 11735, USA',
            'cached_lat': 40.730730,
            'cached_lng': -73.459283,
            'address_alias': 'BK Restaurant #: 17871',
            'EXT_FIELD_phone': '(212) 566-5132',
            'day_scheduled_for_YYMMDD': '2016-07-01',
            'EXT_FIELD_custom_data': {'url': url
                                      }
            }
    response = order.create_order(**data)
    print 'Member ID:\t{0}'.format(response.get('member_id'))
    print 'Order ID:\t{0}'.format(response.get('order_id'))
    print 'Order Status ID:\t{0}'.format(response.get('order_status_id'))
    print 'In Route Count:\t{0}'.format(response.get('in_route_count'))
    print 'Day Added:\t{0}'.format(response.get('day_added_YYMMDD'))
    print 'Is Pending:\t{0}'.format(response.get('is_pending'))
    print 'Is Accepted:\t{0}'.format(response.get('is_accepted'))
    print 'Is Started:\t{0}'.format(response.get('is_started'))
    print 'Is Validated:\t{0}'.format(response.get('is_validated'))
    print 'Is Completed:\t{0}'.format(response.get('is_completed'))

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.orders;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.orders.Order;
import com.route4me.sdk.services.orders.OrdersManager;

public class AddOrder {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        OrdersManager manager = new OrdersManager(apiKey);
        try {
            Order order = new Order();
            order.setAddress1("Some address");
            order.setCachedLatitude(48.335991);
            order.setCachedLongitude(31.18287);
            manager.addOrder(order);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  order := &orders.Order{
    Address1: "Some address",
    CachedLatitude: 48.335991,
    CachedLongitude: 31.18287,
  }
  newOrder, err := service.Add(order)
  if err != nil {
    //handle errors
    return
  }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

// The example demonstrates the creation of a new Order.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$orderParameters = Order::fromArray(array(
    "address_1"                => "1358 E Luzerne St, Philadelphia, PA 19124, US",
    "cached_lat"               => 48.335991,
    "cached_lng"               => 31.18287,
    "address_alias"            => "Auto test address",
    "address_city"             => "Philadelphia",
    "day_scheduled_for_YYMMDD" => date("Y-m-d"),
    "EXT_FIELD_first_name"     => "Igor",
    "EXT_FIELD_last_name"      => "Progman",
    "EXT_FIELD_email"          => "[email protected]",
    "EXT_FIELD_phone"          => "380380380380",
    "EXT_FIELD_custom_data"    => array(
          0 => array(
             'order_id' => '10',
             'name'     => 'Bill Soul'
          )
    )
));

$order = new Order();

$response = $order->addOrder($orderParameters);

Route4Me::simplePrint($response);
<job id="Create New Order">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example refers to the process of creating an order by sending HTTP POST data.
      ' Note: This method is only allowed for Route4Me Business and higher account types, so you should use a valid API key.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/order.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="add_order_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit AddOrderUnit;

interface

uses SysUtils, BaseExampleUnit, OrderUnit;

type
  TAddOrder = class(TBaseExample)
  public
    function Execute: TOrder;
  end;

implementation

function TAddOrder.Execute: TOrder;

var
  ErrorString: String;
  Order: TOrder;
begin
  Order := TOrder.Create();
  try
    Order.Address1 := 'Test Address1';
    Order.AddressAlias := 'Test AddressAlias';
    Order.CachedLatitude := 37.773972;
    Order.CachedLongitude := -122.431297;

    Result := Route4MeManager.Order.Add(Order, ErrorString);

    WriteLn('');

    if (Result <> nil) then
    begin
      WriteLn('AddOrder executed successfully');
      WriteLn(Format('Order ID: %s', [Result.OrderId.Value]));
    end
    else
      WriteLn(Format('AddOrder error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Order);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";

    ifstream inf("add_order_data.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }

    Json::Value body;
    inf >> body;
    int ret = route.add_order(body);
    if (ret == 0)
        cout << "Order added: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "Error adding order: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    Json::Value orders;
    orders.append("1247");
    orders.append("1248");
    ret = route.remove_order(1, orders);
    if (ret == 0)
       cout << "Order removed: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
       cout << "Error removing order: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/order.php?api_key=...

You can expect this API response:

{
  "created_timestamp": 1521184759,
  "order_id": 27992,
  "order_status_id": 0,
  "day_added_YYMMDD": "2018-03-16",
  "day_scheduled_for_YYMMDD": "2018-05-16",
  "address_alias": "Auto test address",
  "address_1": "1358 E Luzerne St, Philadelphia, PA 19124, US",
  "address_2": "",
  "member_id": 1,
  "EXT_FIELD_first_name": "Igor",
  "EXT_FIELD_last_name": "Progman",
  "EXT_FIELD_email": "[email protected]",
  "EXT_FIELD_phone": "380380380380",
  "address_city": "Philadelphia",
  "address_state_id": null,
  "address_country_id": "0",
  "address_zip": "",
  "cached_lat": 48.335991,
  "cached_lng": 31.18287,
  "curbside_lat": 48.335991,
  "curbside_lng": 31.18287,
  "EXT_FIELD_custom_data": [{
    "order_id": "10",
    "name": "Bill Soul"
  }],
  "in_route_count": 0,
  "last_visited_timestamp": 0,
  "last_routed_timestamp": 0,
  "local_time_window_start": null,
  "local_time_window_end": null,
  "local_time_window_start_2": null,
  "local_time_window_end_2": null,
  "service_time": null,
  "local_timezone_string": null,
  "color": null,
  "order_icon": null,
  "is_validated": false,
  "is_pending": true,
  "is_accepted": false,
  "is_started": false,
  "is_completed": false,
  "custom_user_fields": []
}

Create an Order With Custom Field

Add an order with a custom user field to the user’s account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data POST data A valid JSON object string. See the Order JSON Schema as a guide.
<job id="Create Order With Custom User Field">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example demonstrates process of creating an order with a custom user field by sending HTPP POST data.
			' Note: this method allowed only for business and higher account types, you should use valid API key.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/order.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="create_order_with_custom_field_data.json"
			
			Set r4m=New Route4Me
			
			r4m.outputFile="create_order_with_custom_field_RESPONSE.json"
			
			r4m.HttpPostRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates process of creating an order with a custom user field by sending HTPP POST data.

curl -o create_order_with_custom_field_RESPONSE.json -g -k -X POST -H "Content-Type: application/json" -d "@create_order_with_custom_field_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111

 # The example demonstrates process of creating an order with a custom user field by sending HTPP POST data.

curl -o create_order_with_custom_field_RESPONSE.json -k -g -X POST -H "Content-Type: application/json" -d "@create_order_with_custom_field_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
public void CreateOrderWithCustomFieldTest()
{
	if (skip == "yes") return;

	var route4Me = new Route4MeManager(c_ApiKey);

	var orderParams = new Order()
	{
		address_1 = "1358 E Luzerne St, Philadelphia, PA 19124, US",
		cached_lat = 48.335991,
		cached_lng = 31.18287,
		day_scheduled_for_YYMMDD = "2019-10-11",
		address_alias = "Auto test address",
		CustomUserFields = new OrderCustomField[]
		{
			new OrderCustomField()
			{
				OrderCustomFieldId = 93,
				OrderCustomFieldValue = "false"
			}
		}
	};

	var result = route4Me.AddOrder(orderParams, out string errorString);

	Assert.IsNotNull(result, "AddOrdersToRouteTest failed... " + errorString);

	lsOrderIds.Add(result.order_id.ToString());

	lsOrders.Add(result);
}
Public Sub CreateOrderWithCustomFieldTest()
	If skip = "yes" Then Return

	Dim route4Me = New Route4MeManager(c_ApiKey)

	Dim orderParams = New Order() With {
		.address_1 = "1358 E Luzerne St, Philadelphia, PA 19124, US",
		.cached_lat = 48.335991,
		.cached_lng = 31.18287,
		.day_scheduled_for_YYMMDD = "2019-10-11",
		.address_alias = "Auto test address",
		.custom_user_fields = New OrderCustomField() {New OrderCustomField() With {
			.OrderCustomFieldId = 93,
			.OrderCustomFieldValue = "false"
		}}
	}

	Dim errorString As String = Nothing
	Dim result = route4Me.AddOrder(orderParams, errorString)

	Assert.IsNotNull(result, "AddOrdersToRouteTest failed... " & errorString)

	lsOrderiDs.Add(result.order_id.ToString())
	lsOrders.Add(result)
End Sub
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
<?php
namespace Route4Me;
$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);
// The example demonstrates process of creating an order with a custom user field by sending HTPP POST data.
// Set the api key in the Route4me class
Route4Me::setApiKey('11111111111111111111111111111111');
$orderParameters = Order::fromArray([
    'address_1'                => '1358 E Luzerne St, Philadelphia, PA 19124, US',
    'cached_lat'               => 48.335991,
    'cached_lng'               => 31.18287,
    'day_scheduled_for_YYMMDD' => '2019-10-11',
    'address_alias'            => 'Auto test address',
    'custom_user_fields' => [
        OrderCustomField::fromArray([
                'order_custom_field_id'    => 93,
                'order_custom_field_value' => 'false'
            ])
    ]
]);
$order = new Order();
$response = $order->addOrder($orderParameters);
Route4Me::simplePrint($response, true);
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.


HTTP Request

PUT
/api.v4/address.php?api_key=...&route_id=...&route_destination_id=...

You can expect this API response:

{
	"created_timestamp": 1570026062,
	"order_id": 65898,
	"order_status_id": 0,
	"day_added_YYMMDD": "2019-10-02",
	"day_scheduled_for_YYMMDD": "2019-10-11",
	"address_alias": "Auto test address",
	"address_1": "1358 E Luzerne St, Philadelphia, PA 19124, US",
	"address_2": "",
	"member_id": 1,
	"EXT_FIELD_first_name": "",
	"EXT_FIELD_last_name": "",
	"EXT_FIELD_email": "",
	"EXT_FIELD_phone": "",
	"address_city": "",
	"address_state_id": null,
	"address_country_id": "0",
	"address_zip": "",
	"cached_lat": 48.335991,
	"cached_lng": 31.18287,
	"curbside_lat": 48.335991,
	"curbside_lng": 31.18287,
	"EXT_FIELD_custom_data": [],
	"in_route_count": 0,
	"last_visited_timestamp": 0,
	"last_routed_timestamp": 0,
	"local_time_window_start": null,
	"local_time_window_end": null,
	"local_time_window_start_2": null,
	"local_time_window_end_2": null,
	"service_time": null,
	"local_timezone_string": null,
	"color": null,
	"order_icon": null,
	"is_validated": false,
	"is_pending": true,
	"is_accepted": false,
	"is_started": false,
	"is_completed": false,
	"custom_user_fields": [
		{
			"order_custom_field_id": 93,
			"order_custom_field_type": "checkbox",
			"order_custom_field_name": "customField_1",
			"order_custom_field_label": "customField_1",
			"order_custom_field_type_info": {
				"short_label": "Val"
			},
			"order_custom_field_value": "false"
		}
	]
}

Create a Scheduled Order

Creates an order that is scheduled for a specific date. Assign a correct date value to the day_scheduled_for_YYMMDD attribute of your Order object.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data POST data A valid JSON object string. See the Order JSON Schema as a guide.
An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of creating scheduled orders with time windows

curl -o add_scheduled_order_RESPONSE_1.json -k -g -X POST -H "Content-Type: application/json" -d "@add_scheduled_order_data_1.json" "%url%?api_key=%apikey%"

START /WAIT curl -o add_scheduled_order_RESPONSE_2.json -k -g -X POST -H "Content-Type: application/json" -d "@add_scheduled_order_data_2.json" "%url%?api_key=%apikey%"

START /WAIT curl -o add_scheduled_order_RESPONSE_3.json -k -g -X POST -H "Content-Type: application/json" -d "@add_scheduled_order_data_3.json" "%url%?api_key=%apikey%"

timeout /t 30
An example for this language will be added in the future. For now, please see the other languages available for reference.
public void AddScheduledOrderTest()
{
  Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

  Order orderParams = new Order()
  {
    address_1 = "318 S 39th St, Louisville, KY 40212, USA",
    cached_lat = 38.259326,
    cached_lng = -85.814979,
    curbside_lat = 38.259326,
    curbside_lng = -85.814979,
    address_alias = "318 S 39th St 40212",
    address_city = "Louisville",
    EXT_FIELD_first_name = "Lui",
    EXT_FIELD_last_name = "Carol",
    EXT_FIELD_email = "[email protected]",
    EXT_FIELD_phone = "897946541",
    EXT_FIELD_custom_data = new Dictionary<string, string>() {{"order_type","scheduled order"}},
    day_scheduled_for_YYMMDD = "2017-12-20",
    local_time_window_end = 39000,
    local_time_window_end_2 = 46200,
    local_time_window_start = 37800,
    local_time_window_start_2 = 45000,
    local_timezone_string = "America/New_York",
    order_icon = "emoji/emoji-bank"
  };

  string errorString = "";
  var newOrder = route4Me.AddOrder(orderParams, out errorString);

  Assert.IsNotNull(newOrder, "AddScheduledOrdersTest failed... " + errorString);
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$orderParameters = Order::fromArray(array(
    "address_1"                 => "318 S 39th St, Louisville, KY 40212, USA",
    "cached_lat"                => 38.259326,
    "cached_lng"                => -85.814979,
    "curbside_lat"              => 38.259326,
    "curbside_lng"              => -85.814979,
    "address_alias"             => "318 S 39th St 40212",
    "address_city"              => "Louisville",
    "EXT_FIELD_first_name"      => "Lui",
    "EXT_FIELD_last_name"       => "Carol",
    "EXT_FIELD_email"           => "[email protected]",
    "EXT_FIELD_phone"           => "897946541",
    "EXT_FIELD_custom_data"     => array("order_type" => "scheduled order"),
    "day_scheduled_for_YYMMDD"  => date("Y-m-d"),
    "local_time_window_end"     => 39000,
    "local_time_window_end_2"   => 46200,
    "local_time_window_start"   => 37800,
    "local_time_window_start_2" => 45000,
    "local_timezone_string"     => "America/New_York",
    "order_icon"                => "emoji/emoji-bank"
));

$order = new Order();

$response = $order->addOrder($orderParameters);

Route4Me::simplePrint($response);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/order.php?api_key=...

You can expect this API response:

{
  "created_timestamp": 1509890857,
  "order_id": 24669,
  "order_status_id": 0,
  "day_added_YYMMDD": "2017-11-05",
  "day_scheduled_for_YYMMDD": "2017-12-20",
  "address_alias": "318 S 39th St 40212",
  "address_1": "318 S 39th St, Louisville, KY 40212, USA",
  "address_2": "",
  "member_id": 1,
  "EXT_FIELD_first_name": "Lui",
  "EXT_FIELD_last_name": "Carol",
  "EXT_FIELD_email": "[email protected]",
  "EXT_FIELD_phone": "897946541",
  "address_city": "Louisville",
  "address_state_id": null,
  "address_country_id": "0",
  "address_zip": "",
  "cached_lat": 38.259326,
  "cached_lng": -85.814979,
  "curbside_lat": 38.259326,
  "curbside_lng": -85.814979,
  "EXT_FIELD_custom_data": [{
    "order_type": "scheduled order"
  }],
  "in_route_count": 0,
  "last_visited_timestamp": 0,
  "last_routed_timestamp": 0,
  "local_time_window_start": 37800,
  "local_time_window_end": 39000,
  "local_time_window_start_2": 45000,
  "local_time_window_end_2": 46200,
  "service_time": null,
  "local_timezone_string": "America\/New_York",
  "color": null,
  "order_icon": "emoji\/emoji-bank",
  "is_validated": false,
  "is_pending": true,
  "is_accepted": false,
  "is_started": false,
  "is_completed": false
}

Add an Order to a Route

Insert an existing order into an existing route.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
redirect integer If equal to 1, it will be redirected. Use 0 for no redirection.
route_id string Route ID
input data POST data A valid JSON object string. See the Order JSON Schema as a guide.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET rdirect=0
SET routeid=CEAA81617489EC7F8972372F6248946D

ECHO ON

:: The example demonstrates the process of adding an order to a route by sending HTTP PUT data.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@add_order_to_route_data.json" "%url%?api_key=%apikey%&redirect=%rdirect%&route_id=%routeid"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111
rdirect=0
optid=E0883C1A2C7B3AAA9397BDDF90C9CFF8

# The example demonstrates the process of adding an order to a route by sending HTTP PUT data.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@add_order_to_route_data.json" "$url?api_key=$apikey&redirect=$rdirect&route_id=$routeid"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Add Orders to a Route
        /// </summary>
        /// <returns> Route object </returns>
        public void AddOrdersToRoute()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            RouteParametersQuery rQueryParams = new RouteParametersQuery()
            {
                RouteId = "F0C842829D8799067F9BF7A495076335",
                Redirect = false
            };

            Address[] addresses = new Address[] {
            new Address {
              AddressString = "273 Canal St, New York, NY 10013, USA",
              Latitude = 40.7191558,
              Longitude = -74.0011966,
              Alias = "",
              CurbsideLatitude = 40.7191558,
              CurbsideLongitude = -74.0011966
            },
            new Address {
              AddressString = "106 Liberty St, New York, NY 10006, USA",
              Alias = "BK Restaurant #: 2446",
              Latitude = 40.709637,
              Longitude = -74.011912,
              CurbsideLatitude = 40.709637,
              CurbsideLongitude = -74.011912,
              Email = "",
              Phone = "(917) 338-1887",
              FirstName = "",
              LastName = "",
              CustomFields = new Dictionary<string, string> { {
                "icon",
                null
              } },
              Time = 0,
              OrderId = 7205705
            },
            new Address {
              AddressString = "106 Fulton St, Farmingdale, NY 11735, USA",
              Alias = "BK Restaurant #: 17871",
              Latitude = 40.73073,
              Longitude = -73.459283,
              CurbsideLatitude = 40.73073,
              CurbsideLongitude = -73.459283,
              Email = "",
              Phone = "(212) 566-5132",
              FirstName = "",
              LastName = "",
              CustomFields = new Dictionary<string, string> { {
                "icon",
                null
              } },
              Time = 0,
              OrderId = 7205703
            }
          };

            RouteParameters rParams = new RouteParameters()
            {
                RouteName = "Wednesday 15th of June 2016 07:01 PM (+03:00)",
                RouteDate = 1465948800,
                RouteTime = 14400,
                Optimize = "Time",
                RouteType = "single",
                AlgorithmType = AlgorithmType.TSP,
                RT = false,
                LockLast = false,
                MemberId = "1",
                VehicleId = "",
                DisableOptimization = false
            };

            string errorString;
            RouteResponse result = route4Me.AddOrdersToRoute(rQueryParams, addresses, rParams, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("AddOrdersToRoute executed successfully");

                Console.WriteLine("Route ID: {0}", result.RouteID);
            }
            else
            {
                Console.WriteLine("AddOrdersToRoute error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    ''' <summary>
    ''' Add Orders to a Route
    ''' </summary>
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub AddOrdersToRoute(rQueryParams As RouteParametersQuery, addresses As Address(), rParams As RouteParameters)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As RouteResponse = route4Me.AddOrdersToRoute(rQueryParams, addresses, rParams, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("UpdateRouteCustomData executed successfully")

                Console.WriteLine("Route ID: {0}", dataObject.RouteID)
            Else
                Console.WriteLine("UpdateRouteCustomData error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
package test

import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
    order := &orders.Order{
        Address1:        "Some address",
        CachedLatitude:  48.335991,
        CachedLongitude: 31.18287,
        RouteID:         "CEAA81617489EC7F8972372F6248946D",
    }
    newOrder, err := service.Add(order)
    if err != nil {
        //handle errors
        return
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Order;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the adding of an order to a route.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new  Route();

$routeID = $route->getRandomRouteId(0, 10);

assert(!is_null($routeID), "Can't retrieve a random route ID");

// Add an order to a route

$jfile = file_get_contents("add_order_to_route_data.json");

$body = json_decode($jfile);

$orderParameters = Order::fromArray(array(
    "route_id"    => $routeID,
    "redirect"    => 0,
    "addresses"   => $body->addresses
));

$order = new Order();

$response = $order->addOrder2Route($orderParameters);

Route4Me::simplePrint($response, true);
<job id="Add Order To Route">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example refers to the process of adding an order to a route by sending HTTP PUT data.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      redirect="0"
      routeid="CEAA81617489EC7F8972372F6248946D"
      
      url=url&"?api_key="&apikey
      url=url&"&redirect="&redirect
      url=url&"&route_id="&routeid
      
      jFile="add_order_to_route_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit AddOrderToRouteUnit;

interface

uses SysUtils, BaseExampleUnit, RouteParametersUnit, AddressUnit;

type
  TAddOrderToRoute = class(TBaseExample)
  public
    procedure Execute(RouteId: String; RouteParameters: TRouteParameters;
      OrderedAddresses: TOrderedAddressArray);
  end;

implementation
uses
  AddOrderToRouteRequestUnit;

procedure TAddOrderToRoute.Execute(RouteId: String;
  RouteParameters: TRouteParameters; OrderedAddresses: TOrderedAddressArray);
var
  ErrorString: String;
begin
  Route4MeManager.Route.AddOrder(RouteId, RouteParameters, OrderedAddresses, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
    WriteLn('AddOrderToRoute executed successfully')
  else
    WriteLn(Format('AddOrderToRoute error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("add_order_to_route_data.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";

    if(route.get_route_by_id(route_id) == 0)
    {
        cout << "Route " << route_id << " info by ID:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
        Json::Value order;
        inf >> order;

        int ret = route.add_order_to_route(route_id, order);
        if (ret == 0)
            cout << "Order added to route" << route_id << endl;
        else
            cout << "Error adding order" << endl;
    }
    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.

HTTP Request

PUT
/api.v4/route.php?api_key=...&route_id=...



See the sample JSON response of this method.


Add an Order to an Optimization

Insert an existing order into an existing optimization.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
optimization_problem_id string Optimization Problem ID
redirect integer If equal to 1, it will be redirected. Use 0 for no redirection.
input data POST data A valid JSON object string. See the Order JSON Schema as a guide.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/optimization_problem.php
SET apikey=11111111111111111111111111111111
SET rdirect=0
SET optid=E0883C1A2C7B3AAA9397BDDF90C9CFF8

ECHO ON

:: The example demonstrates the process of adding an order to an optimization by sending HTTP PUT data.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@add_order_to_route_data.json" "%url%?api_key=%apikey%&redirect=%rdirect%&optimization_problem_id=%optid%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/optimization_problem.php
apikey=11111111111111111111111111111111
rdirect=0
optid=E0883C1A2C7B3AAA9397BDDF90C9CFF8

 # The example demonstrates the process of adding an order to an optimization by sending HTTP PUT data.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@add_order_to_route_data.json" "$url?api_key=$apikey&redirect=$rdirect&optimization_problem_id=$optid"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Add Orders to an Optimization Problem object
        /// </summary>
        /// <returns> Optimization Problem object </returns>
        public void AddOrdersToOptimization()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            OptimizationParameters rQueryParams = new OptimizationParameters()
            {
                OptimizationProblemID = "7988378F70C533283BAD5024E6E37201",
                Redirect = false
            };

            Address[] addresses = new Address[] {
        new Address {
          AddressString = "273 Canal St, New York, NY 10013, USA",
          Latitude = 40.7191558,
          Longitude = -74.0011966,
          Alias = "",
          CurbsideLatitude = 40.7191558,
          CurbsideLongitude = -74.0011966,
          IsDepot = true
        },
        new Address {
          AddressString = "106 Liberty St, New York, NY 10006, USA",
          Alias = "BK Restaurant #: 2446",
          Latitude = 40.709637,
          Longitude = -74.011912,
          CurbsideLatitude = 40.709637,
          CurbsideLongitude = -74.011912,
          Email = "",
          Phone = "(917) 338-1887",
          FirstName = "",
          LastName = "",
          CustomFields = new Dictionary<string, string> { {"icon", null} },
          Time = 0,
          TimeWindowStart = 1472544000,
          TimeWindowEnd = 1472544300,
          OrderId = 7205705
        },
        new Address {
          AddressString = "325 Broadway, New York, NY 10007, USA",
          Alias = "BK Restaurant #: 20333",
          Latitude = 40.71615,
          Longitude = -74.00505,
          CurbsideLatitude = 40.71615,
          CurbsideLongitude = -74.00505,
          Email = "",
          Phone = "(212) 227-7535",
          FirstName = "",
          LastName = "",
          CustomFields = new Dictionary<string, string> { {"icon", null} },
          Time = 0,
          TimeWindowStart = 1472545000,
          TimeWindowEnd = 1472545300,
          OrderId = 7205704
        },
        new Address {
          AddressString = "106 Fulton St, Farmingdale, NY 11735, USA",
          Alias = "BK Restaurant #: 17871",
          Latitude = 40.73073,
          Longitude = -73.459283,
          CurbsideLatitude = 40.73073,
          CurbsideLongitude = -73.459283,
          Email = "",
          Phone = "(212) 566-5132",
          FirstName = "",
          LastName = "",
          CustomFields = new Dictionary<string, string> { {"icon", null} },
          Time = 0,
          TimeWindowStart = 1472546000,
          TimeWindowEnd = 1472546300,
          OrderId = 7205703
        }
      };

        RouteParameters rParams = new RouteParameters()
        {
            RouteName = "Wednesday 15th of June 2016 07:01 PM (+03:00)",
            RouteDate = 1465948800,
            RouteTime = 14400,
            Optimize = "Time",
            RouteType = "single",
            AlgorithmType = AlgorithmType.TSP,
            RT = false,
            LockLast = false,
            MemberId = "1",
            VehicleId = "",
            DisableOptimization = false
        };

        // Run the query

        string errorString = "";
        DataObject dataObject = route4Me.AddOrdersToOptimization(rQueryParams, addresses, rParams, out errorString);

        Console.WriteLine("");

        if (dataObject != null)
        {
            Console.WriteLine("AddOrdersToOptimization executed successfully");

            Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId);
        }
        else
        {
            Console.WriteLine("AddOrdersToOptimization error: {0}", errorString);
        }

        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    ''' <summary>
    ''' Add Orders to an Optimization
    ''' </summary>
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub AddOrdersToOptimization(rQueryParams As OptimizationParameters, addresses As Address(), rParams As RouteParameters)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim dataObject As DataObject = route4Me.AddOrdersToOptimization(rQueryParams, addresses, rParams, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("UpdateRouteCustomData executed successfully")

                Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId)
            Else
                Console.WriteLine("UpdateRouteCustomData error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  addresses := []routing.Address{
    //address to be added
    routing.Address{
      AddressString: "717 5th Ave New York, NY 10021",
      Alias:         "Giorgio Armani",
      Latitude:      40.7669692,
      Longitude:     -73.9693864,
      Time:          0,
    },
  }

  updated, err := service.UpdateOptimization(&OptimizationParameters{ProblemID: "problem_id", Addresses: addresses, Reoptimize: true})
  if err != nil {
    //handle errors
    return
  }
  // do something with updated optimization
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\OptimizationProblem;
use Route4Me\Order;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the adding of an order to an optimization.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random optimization problem ID
$optimization = new OptimizationProblem();

$optimizationProblemId = $optimization->getRandomOptimizationId(0, 10);

assert(!is_null($optimizationProblemId), "Can't retrieve a random optimization problem ID");

// Add an order to an optimization

$jfile = file_get_contents("add_order_to_optimization_data.json");

$body = json_decode($jfile);

$orderParameters = array(
    "optimization_problem_id" => $optimizationProblemId,
    "redirect"                => 0,
    "device_type"             => "web",
    "addresses"               => $body->addresses
);

$order = new Order();

$response = $order->addOrder2Optimization($orderParameters);

Route4Me::simplePrint($response, true);
<job id="Add Order To Optimization">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example refers to the process of adding an order to an optimization by sending HTTP PUT data.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/optimization_problem.php"
      apikey="11111111111111111111111111111111"
      rdirect=0
      optid=E0883C1A2C7B3AAA9397BDDF90C9CFF8
      
      url=url&"?api_key="&apikey
      url=url&"&redirect="&redirect
      url=url&"&optimization_problem_id="&optid
      
      jFile="add_order_to_optimization_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit AddOrderToOptimizationUnit;

interface

uses SysUtils, BaseExampleUnit, RouteParametersUnit,
  AddressUnit;

type
  TAddOrderToOptimization = class(TBaseExample)
  public
    procedure Execute(OptimizationId: String; RouteParameters: TRouteParameters;
      OrderedAddresses: TOrderedAddressArray);
  end;

implementation

uses AddOrderToOptimizationRequestUnit;

procedure TAddOrderToOptimization.Execute(OptimizationId: String;

  RouteParameters: TRouteParameters; OrderedAddresses: TOrderedAddressArray);

var
  ErrorString: String;
  Parameters: TAddOrderToOptimizationRequest;
  Address: TOrderedAddress;
begin
  Parameters := TAddOrderToOptimizationRequest.Create;
  try
    Parameters.OptimizationProblemId := OptimizationId;
    Parameters.Redirect := False;
    Parameters.Parameters := RouteParameters;
    for Address in OrderedAddresses do
      Parameters.AddAddress(Address);

    Route4MeManager.Optimization.AddOrder(Parameters, ErrorString);

    WriteLn('');

    if (ErrorString = EmptyStr) then
      WriteLn('AddOrderToOptimization executed successfully')
    else
      WriteLn(Format('AddOrderToOptimization error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.

HTTP Request

PUT
/api.v4/optimization_problem.php?api_key=...&optimization_problem_id=...



See the sample JSON response of this method.


Get Single or Multiple Orders

Get a single order or multiple ones using the order_id parameter.


PARAMETERS

Parameter Type Description
api_key string API key of the user
order_id string The Order ID or a comma-separated list of Order IDs.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111
SET orderid=7205711

ECHO ON

:: The example demonstrates the process of getting a single order using the order_id query parameter and the HTTP GET method to make the request.

curl -o file1.txt -g -X GET "%URL%?api_key=%apikey%&order_id=%orderid%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111
orderid=7205711

# The example demonstrates the process of getting a single order using the order_id query parameter and the HTTP GET method to make the request.

curl -o file1.txt -g -X GET "$url?api_key=$apikey&order_id=$orderid"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Order details by order_id
        /// </summary>
        public void GetOrderByID(string orderIds)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            OrderParameters orderParameters = new OrderParameters()
            {
                OrderId = orderIds
            };

            string errorString;
            Order[] orders = route4Me.GetOrderByID(orderParameters, out errorString);

            Console.WriteLine("");

            if (orders != null)
            {
                Console.WriteLine("GetOrderByID executed successfully, orders total = {0}", orders.Length);
            }
            else
            {
                Console.WriteLine("GetOrderByID error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get single Order by order_id
        ''' </summary>
        Public Sub GetOrderByID(OrderId As Integer)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim orderParameters As New OrderParameters() With { _
                .OrderId = OrderId _
            }

            Dim errorString As String = ""
            Dim order As Order = route4Me.GetOrderByID(orderParameters, errorString)

            Console.WriteLine("")

            If order IsNot Nothing Then
                Console.WriteLine("GetOrderByID executed successfully, order_id = {0}", order.OrderId)
            Else
                Console.WriteLine("GetOrderByID error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    order = route4me.order
    url = "http://www.bk.com/restaurants/ny/new-york/106-fulton-st-17871.html"
    data = {'address_1': '106 Fulton St, Farmingdale, NY 11735, USA',
            'cached_lat': 40.730730,
            'cached_lng': -73.459283,
            'address_alias': 'BK Restaurant #: 17871',
            'EXT_FIELD_phone': '(212) 566-5132',
            'day_scheduled_for_YYMMDD': '2016-07-01',
            'EXT_FIELD_custom_data': {'url': url,
                                      }
            }
    response = order.create_order(**data)
    order_id = response.get('order_id')
    if order_id:
        response = order.get_order(order_id=order_id)
        print 'Member ID:\t{0}'.format(response.get('member_id'))
        print 'Order ID:\t{0}'.format(response.get('order_id'))
        print 'Order Status ID:\t{0}'.format(response.get('order_status_id'))
        print 'In Route Count:\t{0}'.format(response.get('in_route_count'))
        print 'Day Added:\t{0}'.format(response.get('day_added_YYMMDD'))
        print 'Is Pending:\t{0}'.format(response.get('is_pending'))
        print 'Is Accepted:\t{0}'.format(response.get('is_accepted'))
        print 'Is Started:\t{0}'.format(response.get('is_started'))
        print 'Is Validated:\t{0}'.format(response.get('is_validated'))
        print 'Is Completed:\t{0}'.format(response.get('is_completed'))
    else:
        print 'Error Getting Order'

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.orders;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.orders.Order;
import com.route4me.sdk.services.orders.OrdersManager;

public class GetOrderById {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        OrdersManager manager = new OrdersManager(apiKey);
        try {
            Order order = manager.getOrder(1317);
            System.out.println(order);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  order, err := service.Get(&Query{ID: orderid})
  if err != nil {
    //handle error
    return
  }
  //do something with the order
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the process of getting an order's details.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

// Get a random order ID
$order = new Order();

$orderID = $order->getRandomOrderId(0, 10);

assert(!is_null($orderID), "Can't retrieve a random order ID");

// Get an order
$orderParameters = Order::fromArray(array(
    "order_id"  => $orderID
));

$response = $order->getOrder($orderParameters);

Route4Me::simplePrint($response);
<job id="Get Orders By ID">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      ' The example demonstrates the process of getting a single order using the order_id query parameter and the HTTP GET method to make the request.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/order.php"
      apikey="11111111111111111111111111111111"
      
      orderid="96"
      
      url=url&"?api_key="&apikey
      url=url&"&order_id="&orderid
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit GetOrderUnit;

interface

uses SysUtils, BaseExampleUnit, OrderUnit;

type
  TGetOrder = class(TBaseExample)
  public
    procedure Execute(OrderId: String);
  end;

implementation

procedure TGetOrder.Execute(OrderId: String);

var
  ErrorString: String;
  Order: TOrder;
begin
  Order := Route4MeManager.Order.Get(OrderId, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
      WriteLn('GetOrder executed successfully')
    else
      WriteLn(Format('GetOrder error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Order);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/order.php?api_key=...&order_id=...

You can expect this API response:

{
  "created_timestamp": 0,
  "order_id": 7205711,
  "order_status_id": 0,
  "day_added_YYMMDD": "2016-06-08",
  "day_scheduled_for_YYMMDD": null,
  "address_alias": "Auto test order",
  "address_1": "1358 E Luzerne St, Philadelphia, PA 19124, US",
  "address_2": "",
  "member_id": 1,
  "EXT_FIELD_first_name": "Igor",
  "EXT_FIELD_last_name": "Progman",
  "EXT_FIELD_email": "[email protected]",
  "EXT_FIELD_phone": "",
  "address_city": "Philadelphia",
  "address_state_id": "",
  "address_country_id": "",
  "address_zip": "",
  "cached_lat": 41.592753,
  "cached_lng": -73.830487,
  "curbside_lat": 41.592753,
  "curbside_lng": -73.830487,
  "EXT_FIELD_custom_data": null,
  "in_route_count": 0,
  "last_visited_timestamp": 0,
  "last_routed_timestamp": 0,
  "local_time_window_start": 0,
  "local_time_window_end": 0,
  "local_time_window_start_2": 0,
  "local_time_window_end_2": 0,
  "service_time": 0,
  "local_timezone_string": null,
  "color": null,
  "order_icon": "NULL",
  "is_validated": false,
  "is_pending": false,
  "is_accepted": false,
  "is_started": false,
  "is_completed": false
}

Get Orders

a) Get all the orders created under the specific Route4Me account


PARAMETERS

Parameter Type Description
api_key string API key of the user
ECHO OFF
SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of getting all orders.

curl -o file1.txt -X GET "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111

 # The example demonstrates the process of getting all orders.

curl -o file1.txt -X GET "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Get Orders
    /// </summary>
    public void GetOrders()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      OrderParameters orderParameters = new OrderParameters()
      {
        Limit = 10
      };

      uint total;
      string errorString;
      Order[] orders = route4Me.GetOrders(orderParameters, out total, out errorString);

      Console.WriteLine("");

      if (orders != null)
      {
        Console.WriteLine("GetOrders executed successfully, {0} orders returned, total = {1}", orders.Length, total);
      }
      else
      {
        Console.WriteLine("GetOrders error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get Orders
        ''' </summary>
        Public Sub GetOrders()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim orderParameters As New OrderParameters() With { _
                .Limit = 10 _
            }

            Dim total As UInteger
            Dim errorString As String = ""
            Dim orders As Order() = route4Me.GetOrders(orderParameters, total, errorString)

            Console.WriteLine("")

            If orders IsNot Nothing Then
                Console.WriteLine("GetOrders executed successfully, {0} orders returned, total = {1}", orders.Length, total)
            Else
                Console.WriteLine("GetOrders error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
package com.route4me.sdk.examples.orders;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.orders.Order;
import com.route4me.sdk.services.orders.OrderRequest;
import com.route4me.sdk.services.orders.OrdersManager;

import java.util.List;

public class GetOrders {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        OrdersManager manager = new OrdersManager(apiKey);
        try {
            List<Order> orders = manager.getOrders(new OrderRequest());
            System.out.println(orders);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  orders, err := service.GetAll(&Query{})
  if err != nil {
    //Handle error
    return
  }
  //do something with orders, it's a []Order
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

// The example demonstrates the process of getting all orders.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$order = new Order();

$orderParameters = Order::fromArray(array(
    "offset" => 0,
    'limit'  => 5,
));

$response = $order->getOrders($orderParameters);

foreach ($response['results'] as $key => $order) {
    Route4Me::simplePrint($order);
    echo "<br>";
}
<job id="Get All Orders">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      ' The example refers to the process of getting all orders.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/order.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit GetOrdersUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetOrders = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses OrderParametersUnit, OrderUnit;

procedure TGetOrders.Execute;
var
  ErrorString: String;
  Parameters: TOrderParameters;
  Total: integer;
  Orders: TOrderArray;
  i: integer;
begin
  Parameters := TOrderParameters.Create();
  try
    Parameters.Limit := 10;

    Orders := Route4MeManager.Order.Get(Parameters, Total, ErrorString);
    try
      WriteLn('');

      if (Length(Orders) > 0) then
        WriteLn(Format(
          'GetOrders executed successfully, %d orders returned, total = %d',
          [Length(Orders), Total]))
      else
        WriteLn(Format('GetOrders error: "%s"', [ErrorString]));
    finally
      for i := Length(Orders) - 1 downto 0 do
        FreeAndNil(Orders[i]);
    end;
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/order.php?api_key=...



See the sample JSON response of this method.


b) Get the orders inserted on a specific date


PARAMETERS

Parameter Type Description
api_key string API key of the user
redirect integer If equal to 1, it will be redirected. Use 0 for no redirection.
day_added_YYMMDD string The date the order was inserted. Use the format “YYYY-MM-DD”.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111
SET "sdate=2016-06-15"

ECHO ON

:: The example demonstrates the process of retrieving orders inserted on a specific date.

curl -o file1.txt -g -X GET "%URL%?api_key=%apikey%&day_added_YYMMDD=%sdate%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey="11111111111111111111111111111111"
sdate="2016-06-15"

# The example demonstrates the process of retrieving orders inserted on a specific date.

curl -o file1.txt -g -X GET "$url?api_key=$apikey&day_added_YYMMDD=$sdate"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Orders by Inserted Date
        /// </summary>
        public void GetOrderByInsertedDate(string InsertedDate)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            OrderParameters oParams = new OrderParameters { DayAddedYYMMDD = InsertedDate };

            string errorString = "";
            Order[] orders = route4Me.SearchOrders(oParams, out errorString);

            Console.WriteLine("");

            if (orders != null)
            {
                Console.WriteLine("GetOrderByInsertedDate executed successfully, orders searched total = {0}", orders.Length);
            }
            else
            {
                Console.WriteLine("GetOrderByInsertedDate error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get single Order by order_id
        ''' </summary>
        Public Sub GetOrderByInsertedDate(InsertedDate As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim oParams As New OrderParameters() With { _
                .DayAddedYYMMDD = InsertedDate _
            }

            Dim errorString As String = ""
            Dim orders As Order() = route4Me.SearchOrders(oParams, errorString)

            Console.WriteLine("")

            If orders IsNot Nothing Then
                Console.WriteLine("GetOrderByInsertedDate executed successfully, orders searched total = {0}", orders.Count)
            Else
                Console.WriteLine("GetOrderByInsertedDate error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
package com.route4me.sdk.examples.orders;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.orders.Order;
import com.route4me.sdk.services.orders.OrderRequest;
import com.route4me.sdk.services.orders.OrdersManager;

import java.util.List;

public class GetOrdersByDateCreated {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        OrdersManager manager = new OrdersManager(apiKey);
        try {
            List<Order> orders = manager.getOrders(new OrderRequest().setDateInserted("sdate=2016-06-10"));
            System.out.println(orders);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  orders, err := service.GetAll(&Query{DateInserted:"sdate=2016-06-10"}) //DD-MM-YYYY
  if err != nil {
    //handle error
    return
  }
  //do something with the orders it's []Order
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

// The example demonstrates the process of retrieving orders inserted on a specific date.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$orderParameters = Order::fromArray(array(
    "day_added_YYMMDD"  => date("Y-m-d", strtotime( '-1 days' )),
    "offset"            => 0,
    "limit"             => 5
));

$order = new Order();

$response = $order->getOrder($orderParameters);

foreach ($response['results'] as $key => $order) {
    Route4Me::simplePrint($order);
    echo "<br>";
}
<job id="Get Orders By Inserted Date">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      ' The example demonstrates the process of retrieving orders inserted on a specific date.

      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/order.php"
      apikey="11111111111111111111111111111111"
      
      sdate="2016-06-15"
      
      url=url&"?api_key="&apikey
      url=url&"&day_added_YYMMDD="&sdate
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit GetOrdersByDateUnit;

interface

uses SysUtils, BaseExampleUnit, OrderUnit;

type
  TGetOrdersByDate = class(TBaseExample)
  public
    procedure Execute(Date: TDate);
  end;

implementation

procedure TGetOrdersByDate.Execute(Date: TDate);

var
  ErrorString: String;
  Orders: TOrderArray;
  i: integer;
begin
  Orders := Route4MeManager.Order.Get(Date, ErrorString);
  try
    WriteLn('');

    if (Length(Orders) > 0) then
      WriteLn(Format(
        'GetOrderByDate executed successfully, %d orders returned', [Length(Orders)]))
    else
      WriteLn(Format('GetOrderByDate error: "%s"', [ErrorString]));
  finally
    for i := Length(Orders) - 1 downto 0 do
      FreeAndNil(Orders[i]);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main(int argc, char* argv[])
{
    if (argc < 2) {
        cerr << "Pass date in format YYMMDD" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    int ret = route.get_orders(0, argv[1]);
    if (ret == 0)
        cout << "Orders on 27 Dec 2016: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "No order inserted on this date: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/order.php?api_key=...&day_added_YYMMDD=...



See the sample JSON response of this method.


c) Get the orders scheduled for a specific date


PARAMETERS

Parameter Type Description
api_key string API key of the user
redirect integer If equal to 1, it will be redirected. Use 0 for no redirection.
scheduled_for_YYMMDD string The date the order is scheduled for. Use the format “YYYY-MM-DD”.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111
SET "sdate=2016-06-16"

ECHO ON

:: The example demonstrates the process of retrieving orders scheduled for a specific date.

curl -o file1.txt -g -X GET "%URL%?api_key=%apikey%&scheduled_for_YYMMDD=%sdate%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey="11111111111111111111111111111111"
sdate="2016-06-16"

# The example demonstrates the process of retrieving orders scheduled for a specific date.

curl -o file1.txt -g -X GET "$url?api_key=$apikey&scheduled_for_YYMMDD=$sdate"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Orders by Scheduled Date
        /// </summary>
        public void GetOrderByScheduledDate(string ScheduleddDate)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            OrderParameters oParams = new OrderParameters { ScheduledForYYMMDD = ScheduleddDate };

            string errorString = "";
            Order[] orders = route4Me.SearchOrders(oParams, out errorString);

            Console.WriteLine("");

            if (orders != null)
            {
                Console.WriteLine("GetOrderByScheduledDate executed successfully, orders searched total = {0}", orders.Length);
            }
            else
            {
                Console.WriteLine("GetOrderByScheduledDate error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get single Order by order_id
        ''' </summary>
        Public Sub GetOrderByScheduledDate(ScheduleddDate As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim oParams As New OrderParameters() With { _
                .ScheduledForYYMMDD = ScheduleddDate _
            }

            Dim errorString As String = ""
            Dim orders As Order() = route4Me.SearchOrders(oParams, errorString)

            Console.WriteLine("")

            If orders IsNot Nothing Then
                Console.WriteLine("GetOrderByInsertedDate executed successfully, orders searched total = {0}", orders.Count)
            Else
                Console.WriteLine("GetOrderByInsertedDate error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
package com.route4me.sdk.examples.orders;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.orders.Order;
import com.route4me.sdk.services.orders.OrderRequest;
import com.route4me.sdk.services.orders.OrdersManager;

import java.util.List;

public class GetOrdersByDateScheduled {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        OrdersManager manager = new OrdersManager(apiKey);
        try {
            List<Order> orders = manager.getOrders(new OrderRequest().setDateScheduled("sdate=2016-06-10"));
            System.out.println(orders);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  orders, err := service.GetAll(&Query{DateScheduled:"sdate=2016-06-10"}) //DD-MM-YYYY
  if err != nil {
    //handle error
    return
  }
  //do something with the orders it's []Order
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

// The example demonstrates the process of retrieving orders scheduled for a specific date.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$orderParameters = Order::fromArray(array(
    "scheduled_for_YYMMDD" => date("Y-m-d", strtotime('-1 days')),
    "offset"               => 0,
    "limit"                => 5
));

$order = new Order();

$response = $order->getOrder($orderParameters);

foreach ($response['results'] as $key => $order) {
    Route4Me::simplePrint($order);
    echo "<br>";
}
<job id="Get Orders By Scheduled Date">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      ' The example demonstrates the process of retrieving orders scheduled for a specific date.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/order.php"
      apikey="11111111111111111111111111111111"
      
      sdate="2016-06-16"
      
      url=url&"?api_key="&apikey
      url=url&"&scheduled_for_YYMMDD="&sdate
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit GetOrdersScheduledForUnit;

interface

uses SysUtils, BaseExampleUnit, OrderUnit;

type
  TGetOrdersScheduledFor = class(TBaseExample)
  public
    procedure Execute(Date: TDate);
  end;

implementation

procedure TGetOrdersScheduledFor.Execute(Date: TDate);

var
  ErrorString: String;
  Orders: TOrderArray;
  i: integer;
begin
  Orders := Route4MeManager.Order.GetOrdersScheduledFor(Date, ErrorString);
  try
    WriteLn('');

    if (Length(Orders) > 0) then
      WriteLn(Format(
        'GetOrdersScheduledFor executed successfully, %d orders returned', [Length(Orders)]))
    else
      WriteLn(Format('GetOrdersScheduledFor error: "%s"', [ErrorString]));
  finally
    for i := Length(Orders) - 1 downto 0 do
      FreeAndNil(Orders[i]);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main(int argc, char* argv[])
{
    if (argc < 2) {
        cerr << "Pass date in format YYMMDD" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    ret = route.get_scheduled_orders(0, argv[1]);
    if (ret == 0)
        cout << "Orders on 11 Nov 2016: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "No order scheduled for this date: " << Json::FastWriter().write(route.get_json_resp()) << endl;


    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/order.php?api_key=...&scheduled_for_YYMMDD=...



See the sample JSON response of this method.


d) Get the orders showing only specific fields


PARAMETERS

Parameter Type Description
api_key string API key of the user
fields string A comma-separated list of field names to show.
For example, a value of “order_id, member_id” will display the values of these columns in the response. The fields that aren’t included won’t have their values shown.
offset integer The number of records to skip before searching.
limit integer The number of records to return.
ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111

:: The example demonstrates the process of retrieving orders and showing the values of specific fields.

SET "fields=order_id,member_id"

ECHO ON

curl -o file1.txt -X GET "%url%?api_key=%apikey%&fields=%fields%&offset=0&limit=20"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111

 # The example demonstrates the process of retrieving orders and showing the values of specific fields.

fields="order_id,member_id"

curl -o file1.txt -X GET "$url?api_key=$apikey&fields=$fields&offset=0&limit=20"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Show Orders using chosen fields' values
        /// </summary>
        public void GetOrdersByCustomFields(string CustomFields)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            OrderParameters oParams = new OrderParameters()
            { 
                Fields = CustomFields,
                Offset = 0,
                Limit = 20
            };

            string errorString = "";
            Order[] orders = route4Me.SearchOrders(oParams, out errorString);

            Console.WriteLine("");

            if (orders != null)
            {
                Console.WriteLine("GetOrdersByCustomFields executed successfully, orders searched total = {0}", orders.Length);
            }
            else
            {
                Console.WriteLine("GetOrdersByCustomFields error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get Orders by Custom Fields
        ''' </summary>
        Public Sub GetOrdersByCustomFields(CustomFields As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim oParams As New OrderParameters() With { _
                .Fields = CustomFields, _
                .Offset = 0, _
                .Limit = 20 _
            }

            Dim errorString As String = ""
            Dim results As List(Of Integer()) = route4Me.SearchOrdersByCustomFields(oParams, errorString)

            Console.WriteLine("")

            If results IsNot Nothing Then
                Console.WriteLine("GetOrderByCustomFields executed successfully, orders searched total = {0}", results.Count)
            Else
                Console.WriteLine("GetOrderByInsertedDate error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
package com.route4me.sdk.examples.orders;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.orders.Order;
import com.route4me.sdk.services.orders.OrderRequest;
import com.route4me.sdk.services.orders.OrdersManager;

import java.util.List;

public class GetOrdersByCustomFields {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        OrdersManager manager = new OrdersManager(apiKey);
        try {
            List<Order> orders = manager.getOrders(new OrderRequest().setFields("member_id,order_id"));
            System.out.println(orders);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  orders, err := service.GetAll(&Query{Fields:"order_id,member_id"}) 
  if err != nil {
    //handle error
    return
  }
  //do something with the orders it's []Order
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

// The example demonstrates the process of retrieving orders and showing the values of specific fields.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$orderParameters = Order::fromArray(array(
    "fields" => "order_id,member_id",
    "offset" => 0,
    "limit"  => 5
));

$order = new Order();

$response = $order->getOrder($orderParameters);

foreach ($response as $key => $order) {
    Route4Me::simplePrint($order);
}
<job id="Get Orders By Custom Fields">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      ' The example demonstrates the process of retrieving orders and showing the values of specific fields.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/order.php"
      apikey="11111111111111111111111111111111"
      
      fields="order_id,member_id"
      offset="0"
      limit="20"
      
      url=url&"?api_key="&apikey
      url=url&"&fields="&fields
      url=url&"&offset="&offset
      url=url&"&limit="&limit
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit GetOrdersWithCustomFieldsUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetOrdersWithCustomFields = class(TBaseExample)
  public
    procedure Execute(Fields: TArray<String>);
  end;

implementation
uses CommonTypesUnit, OrderActionsUnit;
procedure TGetOrdersWithCustomFields.Execute(Fields: TArray<String>);
var
  ErrorString: String;
  Orders: TOrdersCustomFields;
  Offset, Limit: integer;
  Total: integer;
begin
  Limit := 10;
  Offset := 0;
  Orders := Route4MeManager.Order.GetOrdersWithCustomFields(
    Fields, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (Orders.Count > 0) then
      WriteLn(Format(
        'GetOrdersWithCustomFields executed successfully, %d orders returned, %d total',
          [Orders.Count, Total]))
    else
      WriteLn(Format('GetOrdersWithCustomFields error: "%s"', [ErrorString]));
  finally
      FreeAndNil(Orders);
  end;
end;

end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main(int argc, char* argv[])
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    int ret = route.get_custom_orders("order_id,member_id", 0, 100);
    if (ret == 0)
        cout << "Orders with custom fields: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "No order with custom fields: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/order.php?api_key=...&fields=...&offset=...&limit=...

You can expect this API response:

{
  "results": [
    [7205711, 1],
    [7205710, 1],
    [7205709, 1],
    [7205708, 1],
    [7205707, 1],
    [7205706, 1],
    [7205705, 1],
    [7205704, 1],
    [7205703, 1],
    [7205702, 1],
    [7205701, 1],
    [7205700, 1],
    [7205699, 1],
    [7205698, 1],
    [7205697, 1],
    [7205696, 1],
    [7205695, 1],
    [7205694, 1],
    [7205693, 1],
    [7205692, 1]
  ],
  "total": 148,
  "fields": ["order_id",
  "member_id"]
}

e) Get the orders that contain the specified text in any of its fields


PARAMETERS

Parameter Type Description
api_key string API key of the user
query string The text to search. All fields will be searched containing this text.
offset integer The number of records to skip before searching.
limit integer The number of records to return.
ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111

:: The example demonstrates the process of retrieving orders that contain the specified text in any of its fields.

SET query="David"

ECHO ON

curl -o file1.txt -X GET "%url%?api_key=%apikey%&query=%query%&offset=0&limit=20"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111

 # The example demonstrates the process of retrieving orders that contain the specified text in any of its fields.

query="David"

curl -o file1.txt -X GET "$url?api_key=$apikey&query=$query&offset=0&limit=20"

echo "Finished.."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Orders be containing specified text in any text field
        /// </summary>
        public void GetOrdersBySpecifiedText(string query)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            OrderParameters oParams = new OrderParameters()
            {
                Query = query,
                Offset = 0,
                Limit = 20
            };

            string errorString = "";
            Order[] orders = route4Me.SearchOrders(oParams, out errorString);

            Console.WriteLine("");

            if (orders != null)
            {
                Console.WriteLine("GetOrdersByCustomFields executed successfully, orders searched total = {0}", orders.Length);
            }
            else
            {
                Console.WriteLine("GetOrdersByCustomFields error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get Orders By Specified Text
        ''' </summary>
        Public Sub GetOrdersBySpecifiedText(query As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim oParams As New OrderParameters() With { _
                .Query = query, _
                .Offset = 0, _
                .Limit = 20 _
            }

            Dim errorString As String = ""
            Dim orders As Order() = route4Me.SearchOrders(oParams, errorString)

            Console.WriteLine("")

            If orders IsNot Nothing Then
                Console.WriteLine("GetOrderByInsertedDate executed successfully, orders searched total = {0}", orders.Count)
            Else
                Console.WriteLine("GetOrderByInsertedDate error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
package com.route4me.sdk.examples.orders;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.orders.Order;
import com.route4me.sdk.services.orders.OrderRequest;
import com.route4me.sdk.services.orders.OrdersManager;

import java.util.List;

public class GetOrdersByQuery {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        OrdersManager manager = new OrdersManager(apiKey);
        try {
            List<Order> orders = manager.getOrders(new OrderRequest().setQuery("Arthur Kill Rd & Clay Pit Rd"));
            System.out.println(orders);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  orders, err := service.GetAll(&Query{Query:"Address here"}) 
    //handle error
    return
  }
  //do something with the orders it's []Order
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

// The example demonstrates the process of retrieving orders that contain the specified text in any of its fields.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$orderParameters = Order::fromArray(array(
    "query"   => "Automated Order",
    "offset"  => 0,
    "limit"   => 5
));

$order = new Order();

$response = $order->getOrder($orderParameters);

foreach ($response['results'] as $key => $order) {
    Route4Me::simplePrint($order);
    echo "<br>";
}
<job id="Get Orders By Text">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      ' The example demonstrates the process of retrieving orders that contain the specified text in any of its fields.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/order.php"
      apikey="11111111111111111111111111111111"
      
      query="David"
      offset="0"
      limit="20"
      
      url=url&"?api_key="&apikey
      url=url&"&query="&query
      url=url&"&offset="&offset
      url=url&"&limit="&limit
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main(int argc, char* argv[])
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    int ret = route.get_orders_query("progman", 0, 100);
    if (ret == 0)
        cout << "Orders with text 'progman': " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "No order with text 'progman': " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/order.php?api_key=...&query=...&offset=...&limit=...



See the sample JSON response of this method.


Update an Order

Updates an order based on the values of the parameters passed.

See the sample input JSON data for this method.

Parameter Type Description
api_key string API key of the user
redirect integer If equal to 1, it will be redirected. Use 0 for no redirection.
input data PUT data A valid JSON object string. See the Order JSON Schema as a guide.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of updating an order using data from a file and using the HTTP PUT method.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@update_order_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111

# The example demonstrates the process of updating an order using data from a file and using the HTTP PUT method.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@update_order_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Update Order
    /// </summary>
    /// <param name="order"> Order with updated attributes </param>
    public void UpdateOrder(Order order)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Run the query
      string errorString;
      Order updatedOrder = route4Me.UpdateOrder(order, out errorString);

      Console.WriteLine("");

      if (updatedOrder != null)
      {
        Console.WriteLine("UpdateOrder executed successfully");
      }
      else
      {
        Console.WriteLine("UpdateOrder error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Update Order
        ''' </summary>
        ''' <param name="order"> Order with updated attributes </param>
        Public Sub UpdateOrder(order As Order)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim updatedOrder As Order = route4Me.UpdateOrder(order, errorString)

            Console.WriteLine("")

            If updatedOrder IsNot Nothing Then
                Console.WriteLine("UpdateOrder executed successfully")
            Else
                Console.WriteLine("UpdateOrder error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    order = route4me.order
    url = "http://www.bk.com/restaurants/ny/new-york/106-fulton-st-17871.html"
    data = {
        'address_1': '106 Fulton St, Farmingdale, NY 11735, USA',
        'cached_lat': 40.730730,
        'cached_lng': -73.459283,
        'address_alias': 'BK Restaurant #: 17871',
        'EXT_FIELD_phone': '(212) 566-5132',
        'day_scheduled_for_YYMMDD': '2016-07-01',
        'EXT_FIELD_custom_data': {
            'url': url,
        }
    }
    response = order.create_order(**data)
    print 'Member ID:\t{0}'.format(response.get('member_id'))
    print 'Order ID:\t{0}'.format(response.get('order_id'))
    print 'Order Status ID:\t{0}'.format(response.get('order_status_id'))
    print 'In Route Count:\t{0}'.format(response.get('in_route_count'))
    print 'Day Added:\t{0}'.format(response.get('day_added_YYMMDD'))
    print 'Is Pending:\t{0}'.format(response.get('is_pending'))
    print 'Is Accepted:\t{0}'.format(response.get('is_accepted'))
    print 'Is Started:\t{0}'.format(response.get('is_started'))
    print 'Is Validated:\t{0}'.format(response.get('is_validated'))
    print 'Is Completed:\t{0}'.format(response.get('is_completed'))
    print '********************************************************'
    print 'Updating'
    print '********************************************************'
    response.update({'is_pending': False,
                     'is_accepted': True,
                     'is_started': True,
                     })
    response = order.update_order(**response)
    print 'Member ID:\t{0}'.format(response.get('member_id'))
    print 'Order ID:\t{0}'.format(response.get('order_id'))
    print 'Order Status ID:\t{0}'.format(response.get('order_status_id'))
    print 'In Route Count:\t{0}'.format(response.get('in_route_count'))
    print 'Day Added:\t{0}'.format(response.get('day_added_YYMMDD'))
    print 'Is Pending:\t{0}'.format(response.get('is_pending'))
    print 'Is Accepted:\t{0}'.format(response.get('is_accepted'))
    print 'Is Started:\t{0}'.format(response.get('is_started'))
    print 'Is Validated:\t{0}'.format(response.get('is_validated'))
    print 'Is Completed:\t{0}'.format(response.get('is_completed'))

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.orders;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.orders.Order;
import com.route4me.sdk.services.orders.OrderRequest;
import com.route4me.sdk.services.orders.OrdersManager;

import java.util.List;

public class UpdateOrder {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        OrdersManager manager = new OrdersManager(apiKey);
        try {
            List<Order> orders = manager.getOrders(new OrderRequest().setQuery("Arthur Kill Rd & Clay Pit Rd"));
            Order old =orders.get(0);
            old.setColor("#333333");
            Order updated = manager.updateOrder(old);
            System.out.println(updated);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  order := //get order using Get, GetAll or constructing yourself.
  order.Field = "updated value"
  contact, err := service.Update(order)
  if err != nil {
    t.Error(err)
    return
  }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the process of updating an order.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random order
$order = new Order();

$randomOrder = $order->getRandomOrder(0, 30);

assert(!is_null($randomOrder), "Can't retrieve a random order");

// Update the order
$randomOrder['address_2'] = "Lviv";
$randomOrder['EXT_FIELD_phone'] = "032268593";
$randomOrder['EXT_FIELD_custom_data'] = array(
            0 => array(
               "customer_no" => "11"
            )
        );

$response = $order->updateOrder($randomOrder);

Route4Me::simplePrint($response, true);
<job id="Update Order">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example demonstrates the process of updating an order using data from a file and using the HTTP PUT method.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/order.php"
      apikey="11111111111111111111111111111111"
      redirect="0"
      routeid="CEAA81617489EC7F8972372F6248946D"
      
      url=url&"?api_key="&apikey
    
      jFile="update_order_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit UpdateOrderUnit;

interface

uses SysUtils, BaseExampleUnit, OrderUnit;

type
  TUpdateOrder = class(TBaseExample)
  public
    procedure Execute(Order: TOrder);
  end;

implementation

procedure TUpdateOrder.Execute(Order: TOrder);

var
  ErrorString: String;
  UpdatedOrder: TOrder;
begin
  UpdatedOrder := Route4MeManager.Order.Update(Order, ErrorString);
  try
    WriteLn('');

    if (UpdatedOrder <> nil) then
      WriteLn('UpdateOrder executed successfully')
    else
      WriteLn(Format('UpdateOrder error: "%s"', [ErrorString]));
  finally
    FreeAndNil(UpdatedOrder);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/order.php?api_key=...

You can expect this API response:

{
  "created_timestamp": 0,
  "order_id": 7205711,
  "order_status_id": 0,
  "day_added_YYMMDD": "2016-06-08",
  "day_scheduled_for_YYMMDD": null,
  "address_alias": "Auto test order",
  "address_1": "1358 E Luzerne St, Philadelphia, PA 19124, US",
  "address_2": "Lviv",
  "member_id": 1,
  "EXT_FIELD_first_name": "David",
  "EXT_FIELD_last_name": "Progman",
  "EXT_FIELD_email": "[email protected]",
  "EXT_FIELD_phone": "032268593",
  "address_city": "Philadelphia",
  "address_state_id": "",
  "address_country_id": "",
  "address_zip": "",
  "cached_lat": 41.592753,
  "cached_lng": -73.830487,
  "curbside_lat": 41.592753,
  "curbside_lng": -73.830487,
  "EXT_FIELD_custom_data": [{
    "customer_no": 11
  }],
  "in_route_count": 0,
  "last_visited_timestamp": 0,
  "last_routed_timestamp": 0,
  "local_time_window_start": 0,
  "local_time_window_end": 0,
  "local_time_window_start_2": 0,
  "local_time_window_end_2": 0,
  "service_time": 0,
  "local_timezone_string": null,
  "color": null,
  "order_icon": "NULL",
  "is_validated": false,
  "is_pending": false,
  "is_accepted": false,
  "is_started": false,
  "is_completed": false
}

Update an Order With Custom Data

Update an order with a custom user data to the user’s account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data POST data A valid JSON object string. See the Order JSON Schema as a guide.
<job id="Update Order With Custom User Field">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example demonstrates process of updating an order with a custom user data by sending HTPP PUT data.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/order.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
		
			jFile="update_order_data.json"
			
			Set r4m=New Route4Me
			
			r4m.HttpPutRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=http://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates process of updating an order with a custom user data by sending HTPP PUT data.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@update_order_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=http://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111

 # The example demonstrates process of updating an order with a custom user data by sending HTPP PUT data.

curl -o file1.txt -g -X PUT -H "Content-Type: application/json" -d "@update_order_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
public void UpdateCustomOrderData()
{
	var route4Me = new Route4MeManager(c_ApiKey);

	//Order order = null;
	string orderId = lsOrderIds.Count > 0 ? lsOrderIds[0] : "";

	var orderParameters = new OrderParameters()
	{
		order_id = orderId
	};

	Order order = route4Me.GetOrderByID(orderParameters, out string errorString);

	order.EXT_FIELD_last_name = "Updated " + (new Random()).Next().ToString();

	order.EXT_FIELD_custom_data =  new Dictionary<string, string>() { { "city", "London" } };

	// Run the query
	var updatedOrder = route4Me.UpdateOrder(order, out errorString);

	Assert.IsNotNull(updatedOrder, "UpdateOrderTest failed. " + errorString);
}
Public Sub UpdateCustomOrderData()
	Dim route4Me = New Route4MeManager(c_ApiKey)
	
	Dim order = lsOrders(lsOrders.Count - 1)

	order.EXT_FIELD_custom_data = New Dictionary(Of String, String)() From {{"order_type", "scheduled order"}},
	
	Dim errorString As String = Nothing
	Dim result = route4Me.UpdateOrder(order, errorString)
	
	Assert.IsNotNull(result, "AddOrdersToRouteTest failed... " & errorString)
End Sub
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
  
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// This example not available for demo API key
Route4Me::setApiKey(Constants::API_KEY);

// Get random order
$order = new Order();

$randomOrder = $order->getRandomOrder(0, 30);

assert(!is_null($randomOrder), "Cannot retrieve a random order");

// Update the order
$randomOrder['address_2'] = 'Lviv';
$randomOrder['EXT_FIELD_phone'] = '032268593';
$randomOrder['EXT_FIELD_custom_data'] = [
            0 => [
               'customer_no' => '11',
            ],
        ];

$response = $order->updateOrder($randomOrder);

Route4Me::simplePrint($response, true);
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.


HTTP Request

PUT
/api.v4/order.php?api_key=...

You can expect this API response:

{
	"created_timestamp": 0,
	"order_id": 7205711,
	"order_status_id": 0,
	"day_added_YYMMDD": "2016-06-08",
	"day_scheduled_for_YYMMDD": null,
	"address_alias": "Auto test order",
	"address_1": "1358 E Luzerne St, Philadelphia, PA 19124, US",
	"address_2": "Lviv",
	"member_id": 1,
	"EXT_FIELD_first_name": "David",
	"EXT_FIELD_last_name": "Progman",
	"EXT_FIELD_email": "[email protected]",
	"EXT_FIELD_phone": "032268593",
	"address_city": "Philadelphia",
	"address_state_id": "",
	"address_country_id": "",
	"address_zip": "",
	"cached_lat": 41.592753,
	"cached_lng": -73.830487,
	"curbside_lat": 41.592753,
	"curbside_lng": -73.830487,
	"EXT_FIELD_custom_data": [{
		"customer_no": 11
	}],
	"in_route_count": 0,
	"last_visited_timestamp": 0,
	"last_routed_timestamp": 0,
	"local_time_window_start": 0,
	"local_time_window_end": 0,
	"local_time_window_start_2": 0,
	"local_time_window_end_2": 0,
	"service_time": 0,
	"local_timezone_string": null,
	"color": null,
	"order_icon": "NULL",
	"is_validated": false,
	"is_pending": false,
	"is_accepted": false,
	"is_started": false,
	"is_completed": false
}

Remove an Order

Removes one or more orders from a Route4Me account.

See the sample input JSON data for this method.

Parameter Type Description HTTP method
api_key string API key of the user GET
redirect integer If equal to 1, it will be redirected. Use 0 for no redirection. GET
order_ids array An array of Order IDs. Use square brackets for both single or multiple Order IDs. POST
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of deleting an order using data from a file and using the HTTP DELETE method.

curl -o file1.txt -g -X DELETE -H "Content-Type: application/json" -d "@delete_order_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order.php
apikey=11111111111111111111111111111111

# The example demonstrates the process of deleting an order using data from a file and using the HTTP DELETE method.

curl -o file1.txt -g -X DELETE -H "Content-Type: application/json" -d "@delete_order_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Remove Orders
    /// </summary>
    /// <param name="orderIds"> Order Ids </param>
    public void RemoveOrders(string[] orderIds)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Run the query
      string errorString;
      bool removed = route4Me.RemoveOrders(orderIds, out errorString);

      Console.WriteLine("");

      if (removed)
      {
        Console.WriteLine("RemoveOrders executed successfully, {0} orders removed", orderIds.Length);
      }
      else
      {
        Console.WriteLine("RemoveOrders error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Remove Orders
        ''' </summary>
        ''' <param name="orderIds"> Order Ids </param>
        Public Sub RemoveOrders(orderIds As String())
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim removed As Boolean = route4Me.RemoveOrders(orderIds, errorString)

            Console.WriteLine("")

            If removed Then
                Console.WriteLine("RemoveOrders executed successfully, {0} orders removed", orderIds.Length)
            Else
                Console.WriteLine("RemoveOrders error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    order = route4me.order
    url = "http://www.bk.com/restaurants/ny/new-york/106-fulton-st-17871.html"
    data = {'address_1': '106 Fulton St, Farmingdale, NY 11735, USA',
            'cached_lat': 40.730730,
            'cached_lng': -73.459283,
            'address_alias': 'BK Restaurant #: 17871',
            'EXT_FIELD_phone': '(212) 566-5132',
            'day_scheduled_for_YYMMDD': '2016-07-01',
            'EXT_FIELD_custom_data': {'url': url
                                      }
            }
    response = order.create_order(**data)
    print 'Member ID:\t{0}'.format(response.get('member_id'))
    print 'Order ID:\t{0}'.format(response.get('order_id'))
    print 'Order Status ID:\t{0}'.format(response.get('order_status_id'))
    print 'In Route Count:\t{0}'.format(response.get('in_route_count'))
    print 'Day Added:\t{0}'.format(response.get('day_added_YYMMDD'))
    print 'Is Pending:\t{0}'.format(response.get('is_pending'))
    print 'Is Accepted:\t{0}'.format(response.get('is_accepted'))
    print 'Is Started:\t{0}'.format(response.get('is_started'))
    print 'Is Validated:\t{0}'.format(response.get('is_validated'))
    print 'Is Completed:\t{0}'.format(response.get('is_completed'))
    print '********************************************************'
    print 'Deleting'
    print '********************************************************'
    order_id = response.get('order_id')
    if order_id:
        data = {'order_ids': [order_id]}
        response = order.delete_order(**data)
        print response
    else:
        print 'Error Getting Order'

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.orders;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.responses.StatusResponse;
import com.route4me.sdk.services.orders.Order;
import com.route4me.sdk.services.orders.OrderRequest;
import com.route4me.sdk.services.orders.OrdersManager;

import java.util.List;

public class DeleteOrder {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        OrdersManager manager = new OrdersManager(apiKey);
        try {
            List<Order> orders = manager.getOrders(new OrderRequest().setQuery("Arthur Kill Rd & Clay Pit Rd"));
            StatusResponse resp = manager.deleteOrders(orders.get(0).getId());
            System.out.println(resp);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/orders"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &orders.Service{Client: client}
  
  success, err := service.Delete([]uint64{orderid})
  if err != nil || !success {
    //handle issues
    return
  }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Order;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

// Get 2 random Order IDs
$order = new Order();

$randomOrderID1 = $order->getRandomOrderId(0, 30);
assert(!is_null($randomOrderID1), "Can't retrieve the first random order ID");

$randomOrderID2 = $order->getRandomOrderId(0, 30);
assert(!is_null($randomOrderID2), "Can't retrieve the second random order ID");

echo "Random order ID 1 -> $randomOrderID1 <br> Random order ID 2 -> $randomOrderID2 <br>";

// Remove 2 random orders
$orderParameters = Order::fromArray(array(
    'order_ids' => array (
        0 => $randomOrderID1,
        1 => $randomOrderID2,
      )
));

$response = $order->removeOrder($orderParameters);

Route4Me::simplePrint($response);
<job id="Remove Order">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example demonstrates the process of deleting an order using data from a file and using the HTTP DELETE method.

      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/order.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="delete_order_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpDeleteRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
unit RemoveOrdersUnit;

interface

uses SysUtils, BaseExampleUnit, CommonTypesUnit, OrderUnit;

type
  TRemoveOrders = class(TBaseExample)
  public
    procedure Execute(OrderIds: TStringArray);
  end;

implementation

uses OrderParametersUnit;

procedure TRemoveOrders.Execute(OrderIds: TStringArray);
var
  ErrorString: String;
  Removed: boolean;
begin
  Removed := Route4MeManager.Order.Remove(OrderIds, ErrorString);

  WriteLn('');

  if (Removed) then
    WriteLn(Format('RemoveOrders executed successfully, %d orders removed',
      [Length(OrderIds)]))
  else
    WriteLn(Format('RemoveOrders error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";

    ifstream inf("add_order_data.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }

    Json::Value body;
    inf >> body;
    int ret = route.add_order(body);
    if (ret == 0)
        cout << "Order added: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "Error adding order: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    Json::Value orders;
    orders.append("1247");
    orders.append("1248");
    ret = route.remove_order(1, orders);
    if (ret == 0)
       cout << "Order removed: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
       cout << "Error removing order: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api.v4/order.php?api_key=...

You can expect this API response:

{"status":true}

Custom User Fields

Route4Me is compatible with some e-commerce platforms and other resources that are widely used for supporting their e-commerce sites. To make your routing operations and logistics transactions as easy and fast as possible, Route4Me enables you to import all your orders from various e-commerce platforms and use them for planning efficient and optimized routes. In addition to planning entirely new routes with imported orders and inserting your orders into the best routes, you can also create bespoke order statuses to accommodate the particular needs of your business or unique business model.


Get User Custom Fields

You can retrieve all the user custom fields of the order entity.

Parameter Type Description HTTP method
api_key string API key of the user GET
<job id="Get Custom Order User Fields">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example refers to the process of getting a custom order user field by sending HTPP query request.
			' Note: this method allowed only for business and higher account types, you should use valid API key.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/order_custom_user_fields.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			Set r4m=New Route4Me
			
			r4m.outputFile="get_custom_order_fields_RESPONSE.json"
			
			r4m.HttpGetRequest url
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order_custom_user_fields.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates process of retrieving the custom order fields by sending HTPP GET data.

curl -o get_custom_order_fields_RESPONSE.json -g -k -X GET "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order_custom_user_fields.php
apikey=11111111111111111111111111111111

 # The example demonstrates process of geting all the custom order user fields by sending HTPP query request.

curl -o get_custom_order_fields_RESPONSE.json -k -g -X GET "$url?api_key=$apikey"

echo "Finished..."

sleep 15
public void GetOrderCustomUserFieldsTest()
{
	if (skip == "yes") return;

	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	string errorString;
	var orderCustomUserFields = route4Me.GetOrderCustomUserFields(out errorString);

	Assert.IsInstanceOfType(orderCustomUserFields, typeof(OrderCustomField[]), "GetOrderCustomUserFieldsTest failed. " + errorString);
}
Public Sub GetOrderCustomUserFieldsTest()
	If skip = "yes" Then Return
	
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	
	Dim errorString As String
	Dim orderCustomUserFields = route4Me.GetOrderCustomUserFields(errorString)
	
	Assert.IsInstanceOfType(orderCustomUserFields, GetType(OrderCustomField()), "GetOrderCustomUserFieldsTest failed. " & errorString)
	
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Example refers to getting of all the order custom user fields list with details.
// Set the api key in the Route4me class

// This example not available for demo API key
Route4Me::setApiKey('11111111111111111111111111111111');

$orderCustomField = new OrderCustomField();

$orderCustomFieldParameters = OrderCustomField::fromArray([]);

$response = $orderCustomField->getOrderCustomUserFields($orderCustomFieldParameters);

foreach ($response as $key => $orderCustomField) {
    Route4Me::simplePrint($orderCustomField);
    echo '<br>';
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/order_custom_user_fields.php?api_key=...

You can expect this API response:

[
	{
		"order_custom_field_id": 174,
		"order_custom_field_name": "CustomField3",
		"order_custom_field_label": "Custom Field 3",
		"order_custom_field_type": "checkbox",
		"root_owner_member_id": 1,
		"order_custom_field_type_info": {
			"short_label": "cFl3"
		}
	},
	{
		"order_custom_field_id": 175,
		"order_custom_field_name": "CustomField4",
		"order_custom_field_label": "Custom Field 44",
		"order_custom_field_type": "checkbox",
		"root_owner_member_id": 1,
		"order_custom_field_type_info": {
			"short_label": "Fld4"
		}
	}
]

Add User Custom Field

You can create a custom user field of the order entity.

See the sample input JSON data for this method.

Parameter Type Description HTTP method
api_key string API key of the user GET
order_custom_field_name string Custom user field’s name. POST
order_custom_field_label string Custom user field’s label. POST
order_custom_field_type string Custom user field’s type (default: ‘checkbox’). POST
order_custom_field_type_info JSON object Information about custom field. You can create any property but the property ‘short_label’ is reserved POST
<job id="Create Custom Order User Field">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example refers to the process of creating a custom order user field by sending HTPP POST data.
			' Note: this method allowed only for business and higher account types, you should use valid API key.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/order_custom_user_fields.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="add_custom_order_field_data.json"
			
			Set r4m=New Route4Me
			
			r4m.outputFile="add_custom_order_field_RESPONSE.json"
			
			r4m.HttpPostRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order_custom_user_fields.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates process of adding a custom order field by sending HTPP POST data.

curl -o add_custom_order_field_RESPONSE.json -g -k -X POST -H "Content-Type: application/json" -d "@add_custom_order_field_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order_custom_user_fields.php
apikey=11111111111111111111111111111111

 # The example demonstrates process of creating a custom order user field by sending HTPP POST data.

curl -o add_custom_order_field_RESPONSE.json -k -g -X POST -H "Content-Type: application/json" -d "@add_custom_order_field_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
public void CreateOrderCustomUserFieldTest()
{
	if (skip == "yes") return;

	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	var orderCustomFieldParams = new OrderCustomFieldParameters()
	{
		OrderCustomFieldName = "CustomField44",
		OrderCustomFieldLabel = "Custom Field 44",
		OrderCustomFieldType = "checkbox",
		OrderCustomFieldTypeInfo = new Dictionary<string, object>()
		{
			{"short_label", "cFl44" },
			{"description", "This is test order custom field" },
			{"custom field no", 11 }
		}
	};

	var orderCustomUserField = route4Me.CreateOrderCustomUserField(orderCustomFieldParams, out string errorString);

	Assert.IsInstanceOfType(orderCustomUserField, typeof(OrderCustomFieldCreateResponse), "CreateOrderCustomUserFieldTest failed. " + errorString);

	lsOrderCustomUserFieldIDs.Add(orderCustomUserField.Data.OrderCustomFieldId);
}
Public Sub CreateOrderCustomUserFieldTest()
	If skip = "yes" Then Return
	
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	
	Dim orderCustomFieldParams = New OrderCustomFieldParameters() With {
		.OrderCustomFieldName = "CustomField44",
		.OrderCustomFieldLabel = "Custom Field 44",
		.OrderCustomFieldType = "checkbox",
		.OrderCustomFieldTypeInfo = New Dictionary(Of String, Object)() From {
			{"short_label", "cFl44"},
			{"description", "This is test order custom field"},
			{"custom field no", 11}
		}
	}
	
	Dim errorString As String = Nothing
	Dim orderCustomUserField = route4Me.CreateOrderCustomUserField(orderCustomFieldParams, errorString)
	
	Assert.IsInstanceOfType(orderCustomUserField, GetType(OrderCustomFieldCreateResponse), "CreateOrderCustomUserFieldTest failed. " & errorString)
	
	lsOrderCustomUserFieldIDs.Add(orderCustomUserField.Data.OrderCustomFieldId)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');

require $root.'/vendor/autoload.php';

// Example refers to the process of creating an order custom user field.
// Set the api key in the Route4me class

// This example not available for demo API key
Route4Me::setApiKey('11111111111111111111111111111111');

$orderCustomField = new OrderCustomField();

$orderCustomFieldParameters = OrderCustomField::fromArray([
    'order_custom_field_name'      => 'CustomField4',
    'order_custom_field_label'     => 'Custom Field 4',
    'order_custom_field_type'      => 'checkbox',
    'order_custom_field_type_info' => ['short_label' => 'cFl4']
]);

$response = $orderCustomField->addOrderCustomUserField($orderCustomFieldParameters);

foreach ($response as $key => $orderCustomField) {
    Route4Me::simplePrint($orderCustomField);
    echo '<br>';
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/order_custom_user_fields.php?api_key=...

You can expect this API response:

{
	"result": "OK",
	"affected": 1,
	"data": {
		"order_custom_field_id": 175,
		"order_custom_field_name": "CustomField4",
		"order_custom_field_type": "checkbox",
		"order_custom_field_label": "Custom Field 4",
		"order_custom_field_type_info": {
			"short_label": "cFl4"
		},
		"root_owner_member_id": 1
	}
}

Update User Custom Field

You can update a custom user field of the order entity.

See the sample input JSON data for this method.

Parameter Type Description HTTP method
api_key string API key of the user GET
order_custom_field_id integer Unique ID of the order custom field. POST
order_custom_field_label string Custom user field’s label. POST
order_custom_field_type string Custom user field’s type (default: ‘checkbox’). POST
order_custom_field_type_info JSON object Information about custom field. You can create any property but the property ‘short_label’ is reserved POST
<job id="Update Custom Order User Field">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example refers to the process of updating a custom order user field by sending HTPP PUT data.
			' Note: this method allowed only for business and higher account types, you should use valid API key.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/order_custom_user_fields.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="update_custom_order_field_data.json"
			
			Set r4m=New Route4Me
			
			r4m.outputFile="update_custom_order_field_RESPONSE.json"
			
			r4m.HttpPutRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order_custom_user_fields.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates process of updating a custom order field by sending HTPP PUT data.

curl -o update_custom_order_field_RESPONSE.json -g -k -X PUT -H "Content-Type: application/json" -d "@update_custom_order_field_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order_custom_user_fields.php
apikey=11111111111111111111111111111111

 # The example demonstrates process of updating a custom order user field by sending HTPP PUT data.

curl -o update_custom_order_field_RESPONSE.json -k -g -X PUT -H "Content-Type: application/json" -d "@update_custom_order_field_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
public void UpdateOrderCustomUserFieldTest()
{
	if (skip == "yes") return;

	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	var orderCustomFieldParams = new OrderCustomFieldParameters()
	{
		OrderCustomFieldId = lsOrderCustomUserFieldIDs[lsOrderCustomUserFieldIDs.Count - 1],
		OrderCustomFieldLabel = "Custom Field 55",
		OrderCustomFieldType = "checkbox",
		OrderCustomFieldTypeInfo = new Dictionary<string, object>()
		{
			{"short_label", "cFl55" },
			{"description", "This is updated test order custom field" },
			{"custom field no", 12 }
		}
	};

	var orderCustomUserField = route4Me.UpdateOrderCustomUserField(orderCustomFieldParams, out string errorString);

	Assert.IsInstanceOfType(orderCustomUserField, typeof(OrderCustomFieldCreateResponse), "UpdateOrderCustomUserFieldTest failed. " + errorString);

	Assert.AreEqual("Custom Field 55", orderCustomUserField.Data.OrderCustomFieldLabel, "UpdateOrderCustomUserFieldTest failed. " + errorString);
}
Public Sub UpdateOrderCustomUserFieldTest()
	If skip = "yes" Then Return
	
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	
	Dim orderCustomFieldParams = New OrderCustomFieldParameters() With {
		.OrderCustomFieldId = lsOrderCustomUserFieldIDs(lsOrderCustomUserFieldIDs.Count - 1),
		.OrderCustomFieldLabel = "Custom Field 55",
		.OrderCustomFieldType = "checkbox",
		.OrderCustomFieldTypeInfo = New Dictionary(Of String, Object)() From {
			{"short_label", "cFl55"},
			{"description", "This is updated test order custom field"},
			{"custom field no", 12}
		}
	}
	
	Dim errorString As String = Nothing
	Dim orderCustomUserField = route4Me.UpdateOrderCustomUserField(orderCustomFieldParams, errorString)
	
	Assert.IsInstanceOfType(orderCustomUserField, GetType(OrderCustomFieldCreateResponse), "UpdateOrderCustomUserFieldTest failed. " & errorString)
	Assert.AreEqual("Custom Field 55", orderCustomUserField.Data.OrderCustomFieldLabel, "UpdateOrderCustomUserFieldTest failed. " & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Example refers to the process of updating an order custom user field.
// Set the api key in the Route4me class

// This example not available for demo API key
Route4Me::setApiKey('11111111111111111111111111111111');

$orderCustomField = new OrderCustomField();

$orderCustomFieldParameters = OrderCustomField::fromArray([
    'order_custom_field_id'        => 182,
    'order_custom_field_label'     => 'ustom Field 44',
    'order_custom_field_type'      => 'checkbox',
    'order_custom_field_type_info' => ['short_label' => 'cFl44']
]);

$response = $orderCustomField->updateOrderCustomUserField($orderCustomFieldParameters);

foreach ($response as $key => $orderCustomField) {
    Route4Me::simplePrint($orderCustomField);
    echo '<br>';
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/order_custom_user_fields.php?api_key=...

You can expect this API response:

{
	"result": "OK",
	"affected": 1,
	"data": {
		"order_custom_field_id": "175",
		"root_owner_member_id": "1",
		"order_custom_field_name": "CustomField4",
		"order_custom_field_label": "Custom Field 44",
		"order_custom_field_type": "checkbox",
		"order_custom_field_type_info": {
			"short_label": "Fld4"
		}
	}
}

Remove User Custom Field

You can remove a custom user field of the order entity.

See the sample input JSON data for this method.

Parameter Type Description HTTP method
api_key string API key of the user GET
order_custom_field_id integer Unique ID of the order custom field. DELETE
<job id="Delete Custom Order User Field">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example refers to the process of deleting a custom order user field by sending HTPP DELETE data.
			' Note: this method allowed only for business and higher account types, you should use valid API key.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/order_custom_user_fields.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="remove_custom_order_field_data.json"
			
			Set r4m=New Route4Me
			
			r4m.outputFile="remove_custom_order_field_RESPONSE.json"
			
			r4m.HttpDeleteRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/order_custom_user_fields.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates process of removing a custom order field by sending HTPP DELETE data.

curl -o remove_custom_order_field_RESPONSE.json -g -k -X DELETE -H "Content-Type: application/json" -d "@remove_custom_order_field_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/order_custom_user_fields.php
apikey=11111111111111111111111111111111

 # The example demonstrates process of removing a custom order user field by sending HTPP DELETE data.

curl -o remove_custom_order_field_RESPONSE.json -k -g -X DELETE -H "Content-Type: application/json" -d "@remove_custom_order_field_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
public void RemoveOrderCustomUserFieldTest()
{
	if (skip == "yes") return;

	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	int orderCustomFieldId = lsOrderCustomUserFieldIDs[lsOrderCustomUserFieldIDs.Count - 1];

	var orderCustomFieldParams = new OrderCustomFieldParameters()
	{
		OrderCustomFieldId = orderCustomFieldId
	};

	var response = route4Me.RemoveOrderCustomUserField(orderCustomFieldParams, out string errorString);

	Assert.IsTrue(response.Affected == 1, "RemoveOrderCustomUserFieldTest failed. " + errorString);

	lsOrderCustomUserFieldIDs.Remove(orderCustomFieldId);
}
Public Sub RemoveOrderCustomUserFieldTest()
	If skip = "yes" Then Return
	
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	Dim orderCustomFieldId As Integer = lsOrderCustomUserFieldIDs(lsOrderCustomUserFieldIDs.Count - 1)
	
	Dim orderCustomFieldParams = New OrderCustomFieldParameters() With {
		.OrderCustomFieldId = orderCustomFieldId
	}
	
	Dim errorString As String = Nothing
	Dim response = route4Me.RemoveOrderCustomUserField(orderCustomFieldParams, errorString)
	
	Assert.IsTrue(response.Affected = 1, "RemoveOrderCustomUserFieldTest failed. " & errorString)
	
	lsOrderCustomUserFieldIDs.Remove(orderCustomFieldId)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Example refers to the process of removing an order custom user field.
// Set the api key in the Route4me class

// This example not available for demo API key
Route4Me::setApiKey('11111111111111111111111111111111');

$orderCustomField = new OrderCustomField();

$orderCustomFieldParameters = OrderCustomField::fromArray([
    'order_custom_field_id' => 183
]);

$response = $orderCustomField->removeOrderCustomUserField($orderCustomFieldParameters);

Route4Me::simplePrint($response);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api.v4/order.php?api_key=...

You can expect this API response:

{
  "result":"OK",
  "affected":1
}

Addresses

An address refers to the information used for describing the location of a stop or destination. It should contain the following identifiers: street name and number, city, state, country, and ZIP Code.

An address is also referred to as a “Stop” or “Destination”.


Address Properties

Attribute Type Description
route_destination_id string Route destination ID
alias string Address alias
member_id integer Member ID
address string Address name
is_depot boolean If true, the address is a depot.
timeframe_violation_state integer The state of the timeframe violation.
timeframe_violation_time integer The moment of the timeframe violation.
timeframe_violation_rate number The rate of the timeframe violation.
priority integer 0 is the highest priority, 1 for a lesser one, and so on.
address_stop_type string The type of stop: “PICKUP”, “DELIVERY”, “BREAK”, “MEETUP”
geofence_detected_visited_timestamp integer The timestamp of a geofence detected visited.
geofence_detected_departed_timestamp integer The timestamp of a geofence detected departed.
geofence_detected_service_time integer The service time of a detected geofence.
geofence_detected_visited_lat number The latitude of a visited detected geofence.
geofence_detected_visited_lng number The longitude of a visited detected geofence.
geofence_detected_departed_lat number The latitude of a departed detected geofence.
geofence_detected_departed_lng number The longitude of a departed detected geofence.
lat number Latitude
lng number Longitude
curbside_lat number Curbside latitude
curbside_lng number Curbside longitude
route_id string Route ID
original_route_id string Original route ID
optimization_problem_id string Optimization problem ID
sequence_no integer A sequence number for an address.
geocoded boolean A value of true means the address field was successfully geocoded, false otherwise.
preferred_geocoding integer The index of the geocodings array that the user has chosen.
failed_geocoding boolean A value of true means there was a geocoding attempt that failed.
geocodings array Geocodings. See the Geocoding JSON Schema as a guide.
contact_id integer Address book contact ID
is_visited boolean If true, the driver pressed the ‘Visited’ button.
is_departed boolean If true, the driver pressed the ‘Departed’ button.
visited_lat number Latitude of the last known visited address.
visited_lng number Longitude of the last known visited address.
departed_lat number Latitude of the last known departed address.
departed_lng number Longitude of the last known departed address.
timestamp_last_visited integer The timestamp when the driver pressed ‘Visited’.
timestamp_last_departed integer The timestamp when the driver marked the stop as ‘Departed’.
customer_po string A customer purchase order for the address.
invoice_no string An invoice number for an address.
reference_no string A reference number for an address.
order_no string An order number for an address.
weight number Weight
cost number The cost of the order for an address.
revenue number The total revenue for an address.
cube number The cubic volume of cargo.
pieces integer Pieces
time integer The service time, in seconds.
email string A valid e-mail address assigned to this stop.
phone string Customer phone
udu_distance_to_next_destination number Distance to a next destination in the user distance unit
custom_data object Unclassified data goes here
destination_note_count integer The number of notes that have been added to this destination.
drive_time_to_next_destination integer The time to the next destination, in seconds.
abnormal_traffic_time_to_next_destination integer The abnormal traffic time to the next destination.
uncongested_time_to_next_destination integer The uncongested time to the next destination.
distance_to_next_destination number The distance to the next destination.
generated_time_window_start integer The generated time window start value, in seconds.
generated_time_window_end integer The generated time window end value, in seconds.
time_window_start integer The time window start value, in seconds.
time_window_end integer The time window end value, in seconds.
time_window_start_2 integer See time_window_start property
time_window_end_2 integer See time_window_end property
notes array Notes. See the Note JSON Schema as a guide.
custom_fields array Custom fields. This is a String array.
manifest object Manifest. See the Address JSON Schema as a guide.

Mark as Detected as Visited

Mark an address as “Detected as Visited”.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_id string Route ID GET
route_destination_id integer Route destination ID GET
is_visited boolean If true, the address will be marked as visited. POST
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Mark Address as Marked as Visited
        /// </summary>
        /// <returns> status </returns>
        public void MarkAddressAsMarkedAsVisited(AddressParameters aParams)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            // Run the query

            string errorString = "";
            Address resultAddress = route4Me.MarkAddressAsMarkedAsVisited(aParams, out errorString);

            Console.WriteLine("");

            if (resultAddress != null)
            {
                Console.WriteLine("MarkAddressAsMarkedAsVisited executed successfully");

                Console.WriteLine("Marked Address ID: {0}", resultAddress.RouteDestinationId);

            }
            else
            {
                Console.WriteLine("MarkAddressAsMarkedAsVisited error: {0}", errorString);

            }

        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Mark Address As Marked As Visited
        ''' </summary>
        ''' <returns> Address </returns>
        Public Sub MarkAddressAsMarkedAsVisited(aParams As AddressParameters)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim resultAddress As Address = route4Me.MarkAddressAsMarkedAsVisited(aParams, errorString)

            Console.WriteLine("")

            If resultAddress IsNot Nothing Then
                Console.WriteLine("MarkAddressAsMarkedAsVisited executed successfully")

                Console.WriteLine("Marked Address ID: {0}", resultAddress.RouteDestinationId)
            Else
                Console.WriteLine("MarkAddressAsMarkedAsVisited error: {0}", errorString)

            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    var address *routing.Address // fetch address
    address.IsVisited = true
    updated, err := service.UpdateAddress(address)
    if err != nil {
        // handle errors
        return
    }
    // do something with updated address
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Address;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route_id");

// Get a random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($routeId);

if (isset($addressRand['is_depot']))
{
    if ($addressRand['is_depot']) {
        echo "The randomly chosen address is a depot. It can't be marked! Try again.";
        return;
    }
}

$address_id = $addressRand['route_destination_id'];

assert(!is_null($address_id), "Can't retrieve random address");

// Mark the address as "detected as visited"
$addressParameters = (array)Address::fromArray(array(
    "route_id"              => $routeId,
    "route_destination_id"  => $address_id,
    "is_visited"            => TRUE
));

$address = new Address();

$result = $address->markAddress($addressParameters);

Route4Me::simplePrint($result);
<job id="Mark Address As Detected As Visited">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            WScript.Echo "Please, press OK and wait..."

            ' Setting is_visited=true means the address was visited, while is_visited=false means it wasn't.

            url="https://api.route4me.com/api.v4/address.php"
            apikey="11111111111111111111111111111111"
            ri="241466F15515D67D3F951E2DA38DE76D"
            rdi="167899269"
            
            url=url&"?api_key="&apikey
            url=url&"&route_id="&ri
            url=url&"&route_destination_id="&rdi
            
            jFile="mark_address_as_detected_as_visited_data.json"
            
            Set r4m=New Route4Me
            
            r4m.HttpPutRequest url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/address.php
SET apikey=11111111111111111111111111111111
SET routeid=241466F15515D67D3F951E2DA38DE76D
SET routedestinationid=167899269

ECHO ON

:: Setting is_visited=true means the address was visited, while is_visited=false means it wasn't.

curl -o file1.txt -k -g -X PUT -H "Content-Type: application/json" -d "@mark_address_as_detected_as_visited_data.json" "%url%?api_key=%apikey%&route_id=%routeid%&route_destination_id=%routedestinationid%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address.php
apikey=11111111111111111111111111111111
routeid=241466F15515D67D3F951E2DA38DE76D
routedestinationid=167899269

# Setting is_visited=true means the address was visited, while is_visited=false means it wasn't.

curl -o file1.txt -k -g -X PUT -H "Content-Type: application/json" -d "@mark_address_as_detected_as_visited_data.json" "$url?api_key=$apikey%&route_id=$routeid&route_destination_id=$routedestinationid"

echo "Finished..."

sleep 15
unit MarkAddressAsDetectedAsVisitedUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TMarkAddressAsDetectedAsVisited = class(TBaseExample)
  public
    procedure Execute(RouteId: String; RouteDestinationId: integer;
      IsVisited: boolean);
  end;

implementation

procedure TMarkAddressAsDetectedAsVisited.Execute(RouteId: String;

  RouteDestinationId: integer; IsVisited: boolean);

var
  ErrorString: String;
begin
  Route4MeManager.Address.MarkAsDetectedAsVisited(
    RouteId, RouteDestinationId, IsVisited, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
    WriteLn('MarkAddressAsDetectedAsVisited executed successfully')
  else
    WriteLn(Format('MarkAddressAsDetectedAsVisited error: "%s"', [ErrorString]));
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.

HTTP Request

PUT
/api.v4/address.php?api_key=...&route_id=...&route_destination_id=...

You can expect this API response:

{
    "route_destination_id": 167899269,
    "alias": "",
    "member_id": 1,
    "address": "559 W Aurora Rd, Northfield, OH 44067",
    "is_depot": false,
    "timeframe_violation_state": null,
    "timeframe_violation_time": 0,
    "timeframe_violation_rate": 0,
    "lat": 41.315116882324,
    "lng": -81.558746337891,
    "curbside_lat": 41.3151169,
    "curbside_lng": -81.5587463,
    "priority": null,
    "route_id": "241466F15515D67D3F951E2DA38DE76D",
    "original_route_id": null,
    "optimization_problem_id": "9949C283BC5E062C307A5985DCEEF622",
    "sequence_no": 1,
    "geocoded": false,
    "preferred_geocoding": null,
    "failed_geocoding": false,
    "geocodings": [],
    "contact_id": 0,
    "address_stop_type": "DELIVERY",
    "is_visited": true,
    "timestamp_last_visited": 1467820568,
    "visited_lat": null,
    "visited_lng": null,
    "is_departed": true,
    "departed_lat": null,
    "departed_lng": null,
    "timestamp_last_departed": 1467820841,
    "group": null,
    "customer_po": null,
    "invoice_no": null,
    "reference_no": null,
    "order_no": null,
    "weight": 0,
    "cost": 0,
    "revenue": 0,
    "cube": 0,
    "pieces": 0,
    "first_name": null,
    "last_name": null,
    "email": null,
    "phone": null,
    "destination_note_count": 0,
    "drive_time_to_next_destination": 0,
    "abnormal_traffic_time_to_next_destination": 0,
    "uncongested_time_to_next_destination": 0,
    "traffic_time_to_next_destination": 0,
    "distance_to_next_destination": 0,
    "channel_name": "aa3b11ccc1cda9e76175801421644645",
    "generated_time_window_start": null,
    "generated_time_window_end": null,
    "time_window_start": 48089,
    "time_window_end": 48449,
    "time_window_start_2": null,
    "time_window_end_2": null,
    "geofence_detected_visited_timestamp": null,
    "geofence_detected_departed_timestamp": null,
    "geofence_detected_service_time": null,
    "geofence_detected_visited_lat": null,
    "geofence_detected_visited_lng": null,
    "geofence_detected_departed_lat": null,
    "geofence_detected_departed_lng": null,
    "time": 300,
    "custom_fields": {},
    "custom_fields_str_json": "{}",
    "custom_fields_config": null,
    "custom_fields_config_str_json": "null",
    "notes": []
}

Mark as Detected as Departed

Mark an address as “Detected as Departed”.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
route_id string Route ID GET
route_destination_id integer Route destination ID GET
is_departed boolean If true, the address will be marked as departed. POST
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Mark Address as Marked as Departed
        /// </summary>
        /// <returns> status </returns>
        public void MarkAddressAsMarkedAsDeparted(AddressParameters aParams)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            // Run the query

            string errorString = "";
            Address resultAddress = route4Me.MarkAddressAsMarkedAsDeparted(aParams, out errorString);

            Console.WriteLine("");

            if (resultAddress != null)
            {
                Console.WriteLine("MarkAddressAsMarkedAsDeparted executed successfully");

                Console.WriteLine("Marked Address ID: {0}", resultAddress.RouteDestinationId);

            }
            else
            {
                Console.WriteLine("MarkAddressAsMarkedAsDeparted error: {0}", errorString);

            }

        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Mark Address As Marked As Departed
        ''' </summary>
        ''' <returns> Address </returns>
        Public Sub MarkAddressAsMarkedAsDeparted(aParams As AddressParameters)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim resultAddress As Address = route4Me.MarkAddressAsMarkedAsDeparted(aParams, errorString)

            Console.WriteLine("")

            If resultAddress IsNot Nothing Then
                Console.WriteLine("MarkAddressAsMarkedAsDeparted executed successfully")

                Console.WriteLine("Marked Address ID: {0}", resultAddress.RouteDestinationId)
            Else
                Console.WriteLine("MarkAddressAsMarkedAsDeparted error: {0}", errorString)

            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    var address *routing.Address // fetch address
    address.IsDeparted = true
    updated, err := service.UpdateAddress(address)
    if err != nil {
        // handle errors
        return
    }
    // do something with updated address
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Address;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route_id");

// Get a random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($routeId);

if (isset($addressRand['is_depot']))
{
    if ($addressRand['is_depot']) {
        echo "The randomly chosen address is a depot. It can't be marked! Try again.";
        return;
    }
}

// Get a random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($routeId);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

// Mark the address as "detected as departed"
$addressParameters = (array)Address::fromArray(array(
    "route_id"              => $routeId,
    "route_destination_id"  => $route_destination_id,
    "is_departed"           => TRUE
));

$address = new Address();

$result = $address->markAddress($addressParameters);

Route4Me::simplePrint($result);
<job id="Mark Address As Detected As Departed">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            WScript.Echo "Please, press OK and wait..."

            ' Setting is_departed=true means the address was departed, while is_departed=false means it wasn't.

            url="https://api.route4me.com/api.v4/address.php"
            apikey="11111111111111111111111111111111"
            ri="241466F15515D67D3F951E2DA38DE76D"
            rdi="167899269"
            
            url=url&"?api_key="&apikey
            url=url&"&route_id="&ri
            url=url&"&route_destination_id="&rdi
            
            jFile="mark_address_as_detected_as_departed_data.json"
            
            Set r4m=New Route4Me
            
            r4m.HttpPutRequest url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/address.php
SET apikey=11111111111111111111111111111111
SET routeid=241466F15515D67D3F951E2DA38DE76D
SET routedestinationid=167899269

ECHO ON

:: Setting is_departed=true means the address was departed, while is_departed=false means it wasn't.

curl -o file1.txt -k -g -X PUT -H "Content-Type: application/json" -d "@mark_address_as_detected_as_departed_data.json" "%url%?api_key=%apikey%&route_id=%routeid%&route_destination_id=%routedestinationid%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address.php
apikey=11111111111111111111111111111111
routeid=241466F15515D67D3F951E2DA38DE76D
routedestinationid=167899269

# Setting is_departed=true means the address was departed, while is_departed=false means it wasn't.

curl -o file1.txt -k -g -X PUT -H "Content-Type: application/json" -d "@mark_address_as_detected_as_departed_data.json" "$url?api_key=$apikey&route_id=$routeid&route_destination_id=$routedestinationid"

echo "Finished..."

sleep 15
unit MarkAddressAsDetectedAsDepartedUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TMarkAddressAsDetectedAsDeparted = class(TBaseExample)
  public
    procedure Execute(RouteId: String; RouteDestinationId: integer;
      IsDeparted: boolean);
  end;

implementation

procedure TMarkAddressAsDetectedAsDeparted.Execute(RouteId: String;

  RouteDestinationId: integer; IsDeparted: boolean);

var
  ErrorString: String;
begin
  Route4MeManager.Address.MarkAsDetectedAsDeparted(
    RouteId, RouteDestinationId, IsDeparted, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
    WriteLn('MarkAddressAsDetectedAsDeparted executed successfully')
  else
    WriteLn(Format('MarkAddressAsDetectedAsDeparted error: "%s"', [ErrorString]));
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.

HTTP Request

PUT
/api.v4/address.php?api_key=...&route_id=...&route_destination_id=...

You can expect this API response:

{
    "route_destination_id": 167899269,
    "alias": "",
    "member_id": 1,
    "address": "559 W Aurora Rd, Northfield, OH 44067",
    "is_depot": false,
    "timeframe_violation_state": null,
    "timeframe_violation_time": 0,
    "timeframe_violation_rate": 0,
    "lat": 41.315116882324,
    "lng": -81.558746337891,
    "curbside_lat": 41.3151169,
    "curbside_lng": -81.5587463,
    "priority": null,
    "route_id": "241466F15515D67D3F951E2DA38DE76D",
    "original_route_id": null,
    "optimization_problem_id": "9949C283BC5E062C307A5985DCEEF622",
    "sequence_no": 1,
    "geocoded": false,
    "preferred_geocoding": null,
    "failed_geocoding": false,
    "geocodings": [],
    "contact_id": 0,
    "address_stop_type": "DELIVERY",
    "is_visited": true,
    "timestamp_last_visited": 1467820568,
    "visited_lat": null,
    "visited_lng": null,
    "is_departed": true,
    "departed_lat": null,
    "departed_lng": null,
    "timestamp_last_departed": 1467820841,
    "group": null,
    "customer_po": null,
    "invoice_no": null,
    "reference_no": null,
    "order_no": null,
    "weight": 0,
    "cost": 0,
    "revenue": 0,
    "cube": 0,
    "pieces": 0,
    "first_name": null,
    "last_name": null,
    "email": null,
    "phone": null,
    "destination_note_count": 0,
    "drive_time_to_next_destination": 0,
    "abnormal_traffic_time_to_next_destination": 0,
    "uncongested_time_to_next_destination": 0,
    "traffic_time_to_next_destination": 0,
    "distance_to_next_destination": 0,
    "channel_name": "aa3b11ccc1cda9e76175801421644645",
    "generated_time_window_start": null,
    "generated_time_window_end": null,
    "time_window_start": 48089,
    "time_window_end": 48449,
    "time_window_start_2": null,
    "time_window_end_2": null,
    "geofence_detected_visited_timestamp": null,
    "geofence_detected_departed_timestamp": null,
    "geofence_detected_service_time": null,
    "geofence_detected_visited_lat": null,
    "geofence_detected_visited_lng": null,
    "geofence_detected_departed_lat": null,
    "geofence_detected_departed_lng": null,
    "time": 300,
    "custom_fields": {},
    "custom_fields_str_json": "{}",
    "custom_fields_config": null,
    "custom_fields_config_str_json": "null",
    "notes": []
}

Mark as Visited

Mark an address as visited.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
address_id integer Address ID
is_visited integer If equal to 1, the address was visited.
member_id integer Member ID
<job id="MarkAddressAsVisited">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            
            WScript.Echo "Please, press OK and wait..."
            
            url="https://api.route4me.com/actions/address/update_address_visited.php"
            apikey="11111111111111111111111111111111"
            route_id="5C15E83A4BE005BCD1537955D28D51D7"
            address_id="160940135"
            is_visited="1"
            
            url=url&"?api_key="&apikey
            url=url&"&route_id="&route_id
            url=url&"&address_id="&address_id
            url=url&"&is_visited="&is_visited
            url=url&"&member_id=1"
            
            Set r4m=New Route4Me
            
            r4m.HttpGetRequest(url)
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/actions/address/update_address_visited.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET addressid=160940135
SET isvisited=1
SET member=1

ECHO ON

:: Setting is_visited=1 means the address was visited, while is_visited=0 means it wasn't.

curl -o file1.txt -g -k -X PUT "%URL%?api_key=%apikey%&route_id=%routeid%&address_id=%addressid%&is_visited=%isvisited%&member=%member%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/address/update_address_visited.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
addressid=160940135
visited=1
member=1

# Setting is_visited=1 means the address was visited, while is_visited=0 means it wasn't.

curl -o file1.txt -g -k -X PUT "$url?api_key=$apikey&route_id=$routeid&address_id=$addressid&is_visited=$visited&member=$member"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Mark Address as Visited
        /// </summary>
        /// <returns> status </returns>
        public void MarkAddressVisited(AddressParameters aParams)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            // Run the query

            {
                string errorString = "";
                int result = route4Me.MarkAddressVisited(aParams, out errorString);

                Console.WriteLine("");

                if (result != null)
                {
                    if (result==1)
                    {
                        Console.WriteLine("MarkAddressVisited executed successfully");
                    }
                    else
                    {
                        Console.WriteLine("MarkAddressVisited error: {0}", errorString);
                    }
                }
                else
                {
                    Console.WriteLine("MarkAddressVisited error: {0}", errorString);
                }
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Mark Address Visited
        ''' </summary>
        ''' <returns> status </returns>
        Public Sub MarkAddressVisited(aParams As AddressParameters)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim result As Integer = route4Me.MarkAddressVisited(aParams, errorString)

            Console.WriteLine("")

            If result = 1 Then
                Console.WriteLine("MarkAddressVisited executed successfully")
            Else
                Console.WriteLine("MarkAddressVisited error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    var address *routing.Address // fetch address
    address.IsVisited = true
    updated, err := service.MarkAddressAsVisited(address)
    if err != nil {
        // handle errors
        return
    }
    // do something with updated address
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Address;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route_id");

// Get a random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($routeId);

if (isset($addressRand['is_depot'])) {
    if ($addressRand['is_depot']) {
        echo "The randomly chosen address is a depot. It can't be marked! Try again.";
        return;
    }
}

// Get a random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($routeId);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

// Mark the address as visited
$address = new Address();

$params = array(
    "route_id"    => $routeId,
    "address_id"  =>  $route_destination_id,
    "is_visited"  => 1,
    "member_id"   => 1
);

$result = $address->markAsVisited($params);

assert($result==1, "Can't mark the address as visited"); 

echo "<br> The address ".$route_destination_id." was marked as visited";
unit MarkAddressAsVisitedUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TMarkAddressAsVisited = class(TBaseExample)
  public
    procedure Execute(RouteId: String; AddressId, MemberId: integer;
      IsVisited: boolean);
  end;

implementation

procedure TMarkAddressAsVisited.Execute(RouteId: String;

  AddressId, MemberId: integer; IsVisited: boolean);

var
  ErrorString: String;
begin
  Route4MeManager.Address.MarkAsVisited(
    RouteId, AddressId, MemberId, IsVisited, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
    WriteLn('MarkAddressAsVisited executed successfully')
  else
    WriteLn(Format('MarkAddressAsVisited error: "%s"', [ErrorString]));
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


GET
/actions/address/update_address_visited.php?api_key=...&route_id=...&address_id=...&is_visited=...

You can expect this API response:

{"status": "true"}

Mark as Departed

Mark a destination of a route as departed.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
address_id integer Address ID
is_departed integer If equal to 1, the address was departed.
member_id integer Member ID
@ECHO OFF

SET url=https://api.route4me.com/api/route/mark_address_departed.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET addressid=160940135
SET isdeparted=1
SET member=1

ECHO ON

:: Setting is_departed=1 means the address was visited, while is_departed=0 means it wasn't.

curl -o file1.txt -g -k -X PUT "%url%?api_key=%apikey%&route_id=%routeid%&address_id=%addressid%&is_departed=%isdeparted%&member_id=%member%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api/route/mark_address_departed.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
addressid=160940135
departed=1
member=1

# Setting is_departed=1 means the address was visited, while is_departed=0 means it wasn't.

curl -o file1.txt -g -k -X PUT "$url?api_key=$apikey&route_id=$routeid&address_id=$addressid&is_departed=$departed=$departed&member_id=$member"

echo "Finished..."

sleep 15
<job id="Mark Address As Departed">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            
            WScript.Echo "Please, press OK and wait..."
            
            url="https://api.route4me.com/api/route/mark_address_departed.php"
            apikey="11111111111111111111111111111111"
            route_id="5C15E83A4BE005BCD1537955D28D51D7"
            address_id="160940135"
            is_departed="1"
            
            url=url&"?api_key="&apikey
            url=url&"&route_id="&route_id
            url=url&"&address_id="&address_id
            url=url&"&is_departed="&is_departed
            url=url&"&member_id=1"
            
            Set r4m=New Route4Me
            
            r4m.HttpGetRequest(url)
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Mark Address as Departed
        /// </summary>
        /// <returns> status </returns>
        public void MarkAddressDeparted(AddressParameters aParams)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            // Run the query

            {
                string errorString = "";
                int result = route4Me.MarkAddressDeparted(aParams, out errorString);

                Console.WriteLine("");

                if (result != null)
                {
                    if (result == 1)
                    {
                        Console.WriteLine("MarkAddressDeparted executed successfully");
                    }
                    else
                    {
                        Console.WriteLine("MarkAddressDeparted error: {0}", errorString);
                    }
                }
                else
                {
                    Console.WriteLine("MarkAddressDeparted error: {0}", errorString);
                }
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Mark Addressas as Departed
        ''' </summary>
        ''' <returns> status </returns>
        Public Sub MarkAddressDeparted(aParams As AddressParameters)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim result As Integer = route4Me.MarkAddressDeparted(aParams, errorString)

            Console.WriteLine("")

            If result = 1 Then
                Console.WriteLine("MarkAddressDeparted executed successfully")
            Else
                Console.WriteLine("MarkAddressDeparted error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    var address *routing.Address // fetch address
    address.IsDeparted = true
    updated, err := service.MarkAddressAsDeparted(address)
    if err != nil {
        // handle errors
        return
    }
    // do something with updated address
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Address;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route_id");

// Get a random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($routeId);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

// Mark the address as departed
$address = new Address();

$params = array(
    "route_id"     => $routeId,
    "address_id"   => $route_destination_id,
    "is_departed"  => 1,
    "member_id"    => 1
);

$result = $address->markAsDeparted($params);

var_dump($result);
unit MarkAddressAsDepartedUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TMarkAddressAsDeparted = class(TBaseExample)
  public
    procedure Execute(RouteId: String; AddressId, MemberId: integer;
      IsDeparted: boolean);
  end;

implementation

procedure TMarkAddressAsDeparted.Execute(RouteId: String;

  AddressId, MemberId: integer; IsDeparted: boolean);

var
  ErrorString: String;
begin
  Route4MeManager.Address.MarkAsDeparted(
    RouteId, AddressId, MemberId, IsDeparted, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
    WriteLn('MarkAddressAsDeparted executed successfully')
  else
    WriteLn(Format('MarkAddressAsDeparted error: "%s"', [ErrorString]));
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


GET
/api/route/mark_address_departed.php?api_key=...&route_id=...&address_id=...&is_visited=...

You can expect this API response:

{"status": "true"}

Geocoding

Geocoding is the process of converting addresses (like “1600 Amphitheatre Parkway, Mountain View, CA”) into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can then use to place markers on a map or position the map.

See the Geocoding JSON Schema in our GitHub repository.

Geocoding Properties

Attribute Type Description
key string A unique identifier for the geocoding.
name string The specific description of the geocoding result.
bbox array Boundary box. Datatype
lat number Latitude
lng number Longitude
confidence string Confidence
type string Is used for tooltip
postalCode string Postal code
countryRegion string Country region
curbside_coordinates array Curbside coordinates. Datatype

Forward Geocode Address

Forward geocoding is the process of converting place name information into latitude and longitude values.


PARAMETERS

Parameter Type Description
api_key string API key of the user
addresses string A comma-separated list of addresses.
format string Response format
<job id="Forward Geocoding">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            ' The example refers to the process of forward geocoding.
            
            WScript.Echo "Please, press OK and wait..."
            
            url="https://api.route4me.com/api/geocoder.php"
            apikey="11111111111111111111111111111111"
            format="xml"
            addrs="Los20%Angeles20%International20%Airport,20%CA"
            
            url=url&"?api_key="&apikey
            url=url&"&format="&format
            url=url&"&addresses="&addrs
            
            jFile=""
            
            Set r4m=New Route4Me
            
            r4m.HttpPostRequest url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF
setlocal enableDelayedExpansion

SET url=https://api.route4me.com/api/geocoder.php
SET apikey=11111111111111111111111111111111
SET format=json
SET "address=Los Angeles International Airport, CA"

SET "address=!address: =%%20!"

ECHO ON

:: The example refers to the process of forward geocoding.

curl -o file1.txt -k -g -X POST "%URL%?api_key=%apikey%&format=%format%&addresses=%address%" 

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api/geocoder.php
apikey=11111111111111111111111111111111
format=xml
addrs="Los20%Angeles20%International20%Airport,20%CA"

 # The example refers to the process of forward geocoding.

curl -o file1.txt -g -X POST "$url?api_key=$apikey&format=$format&addresses=$addrs" 

echo "Finished..."

sleep 15
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$geocodingParameters = array(
    'strExportFormat'  => 'json',
    'addresses'        => 'Los20%Angeles20%International20%Airport,20%CA'
);

$fGeoCoding = new Geocoding();

$fgResult = $fGeoCoding->forwardGeocoding($geocodingParameters);

if ($geocodingParameters['strExportFormat']=='json') {
    Route4Me::simplePrint($fgResult);
} else {
    Route4Me::simplePrint($fgResult['destination']);
}
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Forward Geocoding
        /// </summary>
        /// <returns> XML object </returns>
        public void GeocodingForward(GeocodingParameters geoParams)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            // Run the query
            string errorString = "";
            string result = route4Me.Geocoding(geoParams, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("GeocodingForward executed successfully");
            }
            else
            {
                Console.WriteLine("GeocodingForward error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Forward geocoding
        ''' </summary>
        ''' <returns> XML object </returns>
        Public Sub GeocodingForward(geoParams As GeocodingParameters)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim result As String = route4Me.Geocoding(geoParams, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("GeocodingForward executed successfully")
            Else
                Console.WriteLine("GeocodingForward error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    response = route4me.address.geocode(addresses="Boston-Cambridge-Quincy, MA-NH, USA")
    print response

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/geocoding"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &geocoding.Service{Client: client}
    geo, err := service.ForwardAddress("Los20%Angeles20%International20%Airport,20%CA")
    if err != nil {
        //handle error
    }
    //do something with geo
}
unit ForwardGeocodeAddressUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TForwardGeocodeAddress = class(TBaseExample)
  public
    procedure Execute(Address: String);
  end;

implementation
uses GeocodingUnit;
procedure TForwardGeocodeAddress.Execute(Address: String);
var
  ErrorString: String;
  Geocoding: TGeocoding;
begin
  Geocoding := Route4MeManager.Geocoding.ForwardGeocodeAddress(Address, ErrorString);
  try
    WriteLn('');

    if (Geocoding <> nil) and
      (Geocoding.Latitude.IsNotNull) and (Geocoding.Longitude.IsNotNull) then
    begin
      WriteLn('ForwardGeocodeAddress executed successfully');
      WriteLn(Format('Latitude: %f, Longitude: %f',
        [Geocoding.Latitude.Value, Geocoding.Longitude.Value]));
    end
    else
      WriteLn(Format('ForwardGeocodeAddress error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Geocoding);
  end;
end;
end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY, true);

    const char* addrs = "Los20%Angeles20%International20%Airport,20%CA";
    const char* format = "json";

    if(route.batch_geocoding(addrs, format) == 0)
    {
        cout << "Geocoding done:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Geocoding failed: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
"use strict"

const path = require("path")
const debug = require("debug")("route4me-node:examples")

require("../init-examples-suite")
const helper  = require("./../../test/helper")

helper.describeIntegration(helper.toSuiteName(__filename), function T() {
    this.timeout(5000)
    this.slow(3000)
    it(path.basename(__filename), (done) => {
        // const Route4Me = require("route4me-node")

        const apiKey   = "11111111111111111111111111111111"
        const route4me = new Route4Me(apiKey)

        const address = "Los Angeles International Airport, CA"

        route4me.Geocoding.forward(address, (err, coordinates) => {
            debug("error  ", err)
            debug("result ", coordinates)

            // Expectations about result
            expect(err).is.null

            expect(coordinates).is.not.empty
            expect(coordinates).to.have.length.at.least(1)

            const c = coordinates[0]
            expect(c).has.property("lat", 33.9415889)
            expect(c).has.property("lng", -118.40853)
            expect(c).has.property("original", "Los Angeles International Airport, CA")

            // TODO: remove `done` call from examples
            done()
        })
    })
})
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);

    const char addrs[] = "Los20%25Angeles20%25International20%25Airport%2C20%25CA";
    const char format[] = "json";

    if (!batch_geocoding(addrs, format))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}


POST
/api/geocoder.php?api_key=...&addresses=...&format=...

You can expect this API response (in XML format):

 <?xml version="1.0" encoding="UTF-8" ?>
 <destinations>
    <destination  
        destination="20 International Rd, Los Angeles, CA 90045, USA" 
        lat="33.9439897" 
        lng="-118.3815557" 
        type="street_address" 
        confidence="high" 
        original="Los20International20CA"
    />
 </destinations>

Reverse Geocode Address

With reverse geocoding, you can retrieve an address name from a geographical location point (latitude, longitude). Using this method, you can get the nearest locations to a specific address name. You can also get larger scale objects (such as street addresses, places, neighborhoods, county, state or country) which include a specified address.


PARAMETERS

Parameter Type Description
api_key string API key of the user
addresses string Geographic location
format string Response format
<job id="Reverse Geocoding">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            ' The example refers to the process of reverse geocoding.
            
            WScript.Echo "Please, press OK and wait..."
            
            url="https://api.route4me.com/api/geocoder.php"
            apikey="11111111111111111111111111111111"
            format="xml"
            addrs="42.35863,-71.05670"
            
            url=url&"?api_key="&apikey
            url=url&"&format="&format
            url=url&"&addresses="&addrs
            
            jFile=""
            
            Set r4m=New Route4Me
            
            r4m.HttpPostRequest url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api/geocoder.php
SET apikey=11111111111111111111111111111111
SET format=xml
SET addrs="42.35863,-71.05670"

ECHO ON

:: The example refers to the process of reverse geocoding.

curl -o file1.txt -g -X POST "%url%?api_key=%apikey%&format=%format%&addresses=%addrs%" 

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api/geocoder.php
apikey=11111111111111111111111111111111
format=json
addrs="33.945705,-118.391105"

 # The example refers to the process of reverse geocoding.

curl -o file1.txt -g -X POST "$url?api_key=$apikey&addresses=$addrs" 

echo "Finished..."

sleep 15
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$geocodingParameters = array(
    'format'    => 'xml',
    'addresses' => '42.35863,-71.05670'
);

$fGeoCoding = new Geocoding();

$fgResult = $fGeoCoding->reverseGeocoding($geocodingParameters);

if ($geocodingParameters['format']=='json') {
    foreach ($fgResult as $dest) {
        Route4Me::simplePrint($dest);
        echo "<br>";
    }
}  else {
    foreach ($fgResult['destination'] as $dest) {
        Route4Me::simplePrint($dest);
        echo "<br>";
    }
}
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Reverse Geocoding
        /// </summary>
        /// <returns> XML object </returns>
        public void ReverseGeocoding()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            GeocodingParameters geoParams = new GeocodingParameters { Addresses = "42.35863,-71.05670" };
            // Run the query
            string errorString = "";
            string result = route4Me.Geocoding(geoParams, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("ReverseGeocoding executed successfully");
            }
            else
            {
                Console.WriteLine("ReverseGeocoding error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Reverse geocoding
        ''' </summary>
        ''' <returns> XML object </returns>
        Public Sub ReverseGeocoding()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)
            Dim geoParams As New GeocodingParameters With { _
                 .Addresses = "42.35863,-71.05670"
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As String = route4Me.Geocoding(geoParams, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("ReverseGeocoding executed successfully")
            Else
                Console.WriteLine("ReverseGeocoding error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    response = route4me.address.geocode(addresses="42.35863,-71.05670")
    print response

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/geocoding"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &geocoding.Service{Client: client}
    geo, err := service.ReverseAddress(33.945705, -118.391105)
    if err != nil {
        //handle error
    }
    //do something with geo
}
unit ReverseGeocodeAddressUnit;

interface

uses SysUtils, BaseExampleUnit, DirectionPathPointUnit;

type
  TReverseGeocodeAddress = class(TBaseExample)
  public
    procedure Execute(Location: TDirectionPathPoint);
  end;

implementation
uses GeocodingUnit;
procedure TReverseGeocodeAddress.Execute(Location: TDirectionPathPoint);
var
  ErrorString: String;
  Geocoding: TGeocodingList;
  i: integer;
begin
  Geocoding := Route4MeManager.Geocoding.ReverseGeocodeAddress(Location, ErrorString);
  try
    WriteLn('');

    if (Geocoding.Count > 0) then
    begin
      WriteLn('ReverseGeocodeAddress executed successfully');
      for i := 0 to Geocoding.Count - 1 do
        if Geocoding[i].Destination.IsNotNull then
          WriteLn(Format('Destination: %s', [Geocoding[i].Destination.Value]));
    end
    else
      WriteLn(Format('ReverseGeocodeAddress error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Geocoding);
  end;
end;
end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY, true);

    const char* addrs = "33.945705,-118.391105";
    const char* format = "json";

    if(route.batch_geocoding(addrs, format) == 0)
    {
        cout << "Geocoding done:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Geocoding failed: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);

    const char* addrs = "33.945705,-118.391105";
    const char* format = "json";

    if (!reverse_geocoding(addrs, format))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}


HTTP Request

POST
/api/geocoder.php?api_key=...&addresses=...&format=...


See the sample XML response of this method.


Batch Geocode Addresses

Batch geocoding is the process of getting geographic addresses by sending many address objects simultaneously. In the case of a small number of addresses (n <= 10), you can use the string with the addresses delimited by a double pipe “||” character and send HTTP data as usual (in both cases: forward and reverse geocoding). For a large number of addresses (n > 10), you can delimit the addresses using the newline character “\n” and send HTTP data as form data.


PARAMETERS

Parameter Type Description
api_key string API key of the user
addresses string Geographic location
strExportFormat string Response format
An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF
setlocal enableDelayedExpansion

SET url=https://api.route4me.com/api/geocoder.php
SET apikey=11111111111111111111111111111111
SET format=json

:: You can specify many addresses, delimited by /n, in one string.

SET addrs="Los Angeles International Airport, CA\nn512,Florida Pl,Barberton,OH,44203\n3495,Purdue St,Cuyahoga Falls,OH,44221"

SET "addrs=!addrs: =%%20!"

ECHO ON

:: The example refers to the process of forward geocoding.

curl -o file1.txt -k -g -X POST -F "strExportFormat=json" -F "addresses=%addrs%" "%url%?api_key=%apikey%" 

timeout /t 30
An example for this language will be added in the future. For now, please see the other languages available for reference.
public void BatchGeocodingForward()
{
    Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

    GeocodingParameters geoParams = new GeocodingParameters
    {
        Addresses ="Los Angeles International Airport, CA\n3495 Purdue St, Cuyahoga Falls, OH 44221",
        Format = "json"
    };

    // Run the query
    string errorString = "";
    string result = route4Me.BatchGeocoding(geoParams, out errorString);
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Example refers to the process of batch geocoding of the addresses

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$addressList = array(
    "Los Angeles International Airport, CA",
    "n512,Florida Pl,Barberton,OH,44203",
    "3495,Purdue St,Cuyahoga Falls,OH,44221"
);

$addressesString = implode('\n', $addressList);

$geocodingParameters = array(
    'strExportFormat'  => 'json',
    'addresses'        => $addressesString
);

$fGeoCoding = new Geocoding();

$bgResults = $fGeoCoding->forwardGeocoding($geocodingParameters);

if ($geocodingParameters['strExportFormat']=='json') {
    foreach ($bgResults as $bgResult) {
        Route4Me::simplePrint($bgResult);
        echo "<br>";
    }
} else {
    foreach ($bgResults['destination'] as $bgResult) {
        Route4Me::simplePrint($bgResult);
        echo "<br>";
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api/geocoder.php?api_key=...

You can expect this API response:

{
[{
    "address": "Los Angeles International Airport (LAX), 1 World Way, Los Angeles, CA 90045, USA",
    "lat": 33.9415889,
    "lng": -118.40853,
    "type": "airport, establishment, point_of_interest",
    "confidence": "medium",
    "original": "Los%20Angeles%20International%20Airport,%20CA"
},
{
    "address": "Florida Pl, Barberton, OH 44203, United States",
    "lat": 41.00379,
    "lng": -81.59904,
    "type": "street",
    "confidence": "medium",
    "original": "n512,Florida%20Pl,Barberton,OH,44203"
},
{
    "address": "3495 Purdue St, Cuyahoga Falls, OH 44221, United States",
    "lat": 41.16297,
    "lng": -81.47905,
    "type": "houseNumber",
    "confidence": "medium",
    "original": "3495,Purdue%20St,Cuyahoga%20Falls,OH,44221"
}]
}


Tracking

GPS Tracking refers to the surveillance of location through the use of a Global Positioning System (GPS) to track the location of an entity or object remotely. This technology can pinpoint longitude, latitude, ground speed, and course direction of a target.

See the Tracking History JSON Schema in our GitHub repository.


Tracking Properties

Attribute Type Description
s number Speed
lt number Latitude
lg number Longitude
d string Direction/Heading
ts string Timestamp
ts_friendly string Friendly timestamp

Get Asset Tracking Data

A user has many assets (such as a package) that they must deliver. The user uploads a list of generated tracking numbers and the corresponding delivery addresses, and Route4Me creates one or more delivery routes. As packages are added to each batch, the routes are re-balanced until all the packages have been added to the system. Now that all the tracking numbers are in the system, the user needs to label and sequence each package. Doing it by hand is tedious because they don’t know which route each package goes on. By re-scanning each package manually, or on a conveyor, the client application will automatically output the route ID and the sequence number in the route that the package is found in, querying the system with the package’s unique ID.


PARAMETERS

Parameter Type Description
api_key string API key of the user
tracking string Tracking number
<job id="Asset Tracking">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      ' You should insert real test data and your API key for accurate testing.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://route4me.com/api.v4/status.php"
      apikey="11111111111111111111111111111111"
      tracking="Q7G9P1L9"
      
      url=url&"?api_key="&apikey
      url=url&"&tracking="&tracking
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
#!/usr/bin/python

from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    r4m = Route4Me(KEY)
    route = r4m.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route_tracking(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Optimization Problem ID: {}'.format(response.optimization_problem_id)
            print 'Route ID: {}'.format(response.route_id)
            for i, address in enumerate(response.addresses):
                print 'Address #{}'.format(i)
                print '\tAddress: {0}'.format(address.address)
                print '\tRoute Destination ID: {0}'.format(address.route_destination_id)
            print 'Tracking History: {}'.format(','.join(response.tracking_history))

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root=realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Enum\DeviceType;
use Route4Me\Enum\Format;
use Route4Me\TrackSetParams;
use Route4Me\Track;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example refers to the process of retrieving asset tracking data.

Route4Me::setApiKey('11111111111111111111111111111111');

$trackingNumber = null;

// Get a tracking number from a random route destination
$route = new Route();

$routeId = $route->getRandomRouteId(0, 20);
assert(!is_null($routeId), "Can't retrieve a random route ID");

$addresses = $route->GetAddressesFromRoute($routeId);
assert(!is_null($addresses), "Can't retrieve a random route ID");

foreach ($addresses as $addr1) {
  if (!is_null($addr1->tracking_number)) {
      $trackingNumber = $addr1->tracking_number;
      break;
  }
}

assert(!is_null($trackingNumber), "Can't select a tracking number");

$params = array(
    'tracking'  => $trackingNumber
);

$route = new Route();

$result = $route->GetAssetTracking($params);

foreach ($result as $key => $value)
{
    if (is_array($value)) {
        Route4Me::simplePrint($value, true);
    } else {
        echo "$key => $value <br>";
    }
}
@ECHO OFF

SET url=https://route4me.com/api.v4/status.php

SET apikey=11111111111111111111111111111111
SET tracking="Q7G9P1L9"

:: The example refers to the process of retrieving asset tracking data.

ECHO ON

curl -o file1.txt -g -X GET -k "%url%?api_key=%apikey%&tracking=%tracking%"

timeout /t 30
#!/bin/bash

url=https://route4me.com/api.v4/status.php
apikey=11111111111111111111111111111111
tracking="Q7G9P1L9"

# The example refers to the process of retrieving asset tracking data.

curl -o file1.txt -g -X GET -k "$url?api_key=$apikey&tracking=$tracking"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Find Asset (Asset tracking)
        /// </summary>
        public void FindAsset()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);
            string tracking = "Q7G9P1L9";
            // Run the query
            string errorString = "";
            FindAssetResponse result = route4Me.FindAsset(tracking, out errorString);
            DateTime nDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("FindAsset executed successfully");
                Console.WriteLine("tracking_number: " + result.TrackingNumber);
                foreach (FindAssetResponseLocations loc1 in result.Locations)
                {
                    Console.WriteLine("lat: " + loc1.Latitude);
                    Console.WriteLine("lng: " + loc1.Longitude);
                    Console.WriteLine("icon: " + loc1.Icon);
                }

                foreach (KeyValuePair<string, string> kvp in result.CustomData)
                {
                    Console.WriteLine(kvp.Key + ": " + kvp.Value);
                }

                foreach (FindAssetResponseArrival arriv1 in result.Arrival)
                {
                    Console.WriteLine("from_unix_timestamp: " + nDateTime.AddSeconds(arriv1.FromUnixTimestamp>=0 ? (double)arriv1.FromUnixTimestamp : 0));
                    Console.WriteLine("to_unix_timestamp: " + nDateTime.AddSeconds(arriv1.ToUnixTimestamp>=0 ? (double)arriv1.ToUnixTimestamp : 0));
                }
                Console.WriteLine("delivered: " + result.Delivered);
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("FindAsset error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Find Asset (Asset tracking)
        ''' </summary>
        Public Sub FindAsset()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)
            Dim tracking As String = "Q7G9P1L9"
            ' Run the query
            Dim errorString As String = ""
            Dim result As FindAssetResponse = route4Me.FindAsset(tracking, errorString)
            Dim nDateTime As DateTime = New DateTime(1970, 1, 1, 0, 0, 0, 0)
            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("FindAsset executed successfully")
                Console.WriteLine("tracking_number: " & result.TrackingNumber)
                For Each loc1 As FindAssetResponseLocations In result.Locations
                    Console.WriteLine("lat: " & loc1.Latitude)
                    Console.WriteLine("lng: " & loc1.Longitude)
                    Console.WriteLine("icon: " & loc1.Icon)
                Next

                For Each kvp As KeyValuePair(Of String, String) In result.CustomData
                    Console.WriteLine(kvp.Key & ": " & kvp.Value)
                Next

                For Each arriv1 As FindAssetResponseArrival In result.Arrival
                    Console.WriteLine("from_unix_timestamp: " & nDateTime.AddSeconds(arriv1.FromUnixTimestamp))
                    Console.WriteLine("to_unix_timestamp: " & nDateTime.AddSeconds(arriv1.ToUnixTimestamp))
                Next
                Console.WriteLine("delivered: " & result.Delivered)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("FindAsset error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/tracking"
    "github.com/route4me/route4me-go-sdk/routing" //You might need routing for device type
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &tracking.Service{Client: client}
    assetTracking, err := service.TrackAssets(`tracking-code`)
    if err != nil {
        //handle errors
    }
    //assetTracking contains all tracking data
}
unit GetAssetTrackingDataUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAssetTrackingData = class(TBaseExample)
  public
    procedure Execute(TrackingNumber: String);
  end;

implementation
uses
  TrackingHistoryUnit, TrackingHistoryResponseUnit, TrackingDataUnit;
procedure TGetAssetTrackingData.Execute(TrackingNumber: String);
var
  ErrorString: String;
  TrackingData: TTrackingData;
begin
  TrackingData := Route4MeManager.Tracking.GetAssetTrackingData(
    TrackingNumber, ErrorString);
  try
    WriteLn('');

    if (TrackingData <> nil) then
    begin
      WriteLn('GetAssetTrackingData executed successfully');
      WriteLn('');

      if TrackingData.Delivered.IsNotNull then
        if TrackingData.Delivered.Value then
          WriteLn('Package was delivered')
        else
          WriteLn('Package was not delivered');
    end
    else
      WriteLn(Format('GetAssetTrackingData error: "%s"', [ErrorString]));
  finally
    FreeAndNil(TrackingData);
  end;
end;
end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *id = "Q7G9P1L9";

    int ret = route.asset_tracking(id);
    if (ret == 0)
        cout << "Tracking: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "Tracking error: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);
    const char id[] = "Q7G9P1L9";

    if (!asset_tracking(id))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api.v4/status.php?api_key=...&tracking=...

You can expect this API response:

{
  "tracking_number": "Q7G9P1L9",
  "status_history": [],
  "locations": [{
    "lat": 41.162971,
    "lng": -81.47905,
    "icon": "destination"
  }],
  "custom_data": {
    "package": "Books"
  },
  "arrival": [{
    "from_unix_timestamp": 1465965432,
    "to_unix_timestamp": 1465969032
  }],
  "delivered": false
}

Get Route Tracking Data

a) Get the device’s last location history.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
<job id="Get Device Last Location History">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      'The example refers to the process of getting the last location history of a GPS device.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/route.php"
      apikey="11111111111111111111111111111111"
      routeid="fgfg4f56g4fd54gfdgdfgf4654"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void TrackDeviceLastLocationHistory(string routeId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Create the GPS parameters
      GPSParameters gpsParameters = new GPSParameters()
      {
        Format          = Format.Csv.Description(),
        RouteId         = routeId,
        Latitude        = 33.14384,
        Longitude       = -83.22466,
        Course          = 1,
        Speed           = 120,
        DeviceType      = DeviceType.IPhone.Description(),
        MemberId        = 1,
        DeviceGuid      = "TEST_GPS",
        DeviceTimestamp = "2014-06-14 17:43:35"
      };

      string errorString;
      string response = route4Me.SetGPS(gpsParameters, out errorString);

      if (!string.IsNullOrEmpty(errorString))
      {
        Console.WriteLine("SetGps error: {0}", errorString);
        return;
      }

      Console.WriteLine("SetGps response: {0}", response);

      GenericParameters genericParameters = new GenericParameters();
      genericParameters.ParametersCollection.Add("route_id", routeId);
      genericParameters.ParametersCollection.Add("device_tracking_history", "1");

      var dataObject = route4Me.GetLastLocation(genericParameters, out errorString);

      Console.WriteLine("");

      if (dataObject != null)
      {
        Console.WriteLine("TrackDeviceLastLocationHistory executed successfully");
        Console.WriteLine("");

        Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId);
        Console.WriteLine("State: {0}", dataObject.State);
        Console.WriteLine("");

        dataObject.TrackingHistory.ForEach(th =>
        {
          Console.WriteLine("Speed: {0}",      th.Speed);
          Console.WriteLine("Longitude: {0}",  th.Longitude);
          Console.WriteLine("Latitude: {0}",   th.Latitude);
          Console.WriteLine("Time Stamp: {0}", th.TimeStampFriendly);
          Console.WriteLine("");
        });
      }
      else
      {
        Console.WriteLine("TrackDeviceLastLocationHistory error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub TrackDeviceLastLocationHistory(routeId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Create the GPS parameters
            Dim gpsParameters As New GPSParameters() With { _
                .Format = EnumHelper.GetEnumDescription(Format.Csv), _
                .RouteId = routeId, _
                .Latitude = 33.14384, _
                .Longitude = -83.22466, _
                .Course = 1, _
                .Speed = 120, _
                .DeviceType = EnumHelper.GetEnumDescription(DeviceType.IPhone), _
                .MemberId = 1, _
                .DeviceGuid = "TEST_GPS", _
                .DeviceTimestamp = "2014-06-14 17:43:35" _
            }

            Dim errorString As String = ""
            Dim response As String = route4Me.SetGPS(gpsParameters, errorString)

            If Not String.IsNullOrEmpty(errorString) Then
                Console.WriteLine("SetGps error: {0}", errorString)
                Return
            End If

            Console.WriteLine("SetGps response: {0}", response)

            Dim genericParameters As New GenericParameters()
            genericParameters.ParametersCollection.Add("route_id", routeId)
            genericParameters.ParametersCollection.Add("device_tracking_history", "1")

            Dim dataObject = route4Me.GetLastLocation(genericParameters, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("TrackDeviceLastLocationHistory executed successfully")
                Console.WriteLine("")

                Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId)
                Console.WriteLine("State: {0}", dataObject.State)
                Console.WriteLine("")
                For Each th As TrackingHistory In dataObject.TrackingHistory
                    Console.WriteLine("Speed: {0}", th.Speed)
                    Console.WriteLine("Longitude: {0}", th.Longitude)
                    Console.WriteLine("Latitude: {0}", th.Latitude)
                    Console.WriteLine("Time Stamp: {0}", th.TimeStampFriendly)
                    Console.WriteLine("")
                Next
            Else
                Console.WriteLine("TrackDeviceLastLocationHistory error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import (
    FORMAT,
    DEVICE_TYPE
)
import datetime as dt

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    gps = route4me.setGPS
    route = route4me.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        gps.add(params={'format': FORMAT.CSV,
                        'route_id': response[0].route_id,
                        'lng': -109.0803888,
                        'course': 1,
                        'device_type': DEVICE_TYPE.IPHONE,
                        'member_id': 1,
                        'device_guid': 'qweqweqwe',
                        })
        # SET GPS
        for i in xrange(4):
            gps.add(params={
                'speed': 120 + i,
                'device_timestamp': dt.datetime.strftime(dt.datetime.now(),
                                                         "%Y-%m-%d %H:%M:%S"),
                'lat': 41.8927521 + i,
            })
            print gps.params
            print 'GPS Params SET %s' % gps.set_gps_track()
        route.add(params={
            'route_id': response[0].route_id,
            'device_tracking_history': 1,
        })
        response = route.get_route()
        for history in response.tracking_history:
            print 'lng: %s lat: %s time: %s speed: %s ' % (history.lg,
                                                           history.lt,
                                                           history.ts_friendly,
                                                           history.s)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.tracking;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.DataObject;
import com.route4me.sdk.services.tracking.TrackingManager;

public class TrackDeviceLastLocationHistory {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        TrackingManager manager = new TrackingManager(apiKey);
        try {
            DataObject obj = manager.getLastLocation("1402075EBA9A32939B2696DB1D7EE48E");
            System.out.println(obj.getTrackingHistory());
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;
    
$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Enum\DeviceType;
use Route4Me\Enum\Format;
use Route4Me\TrackSetParams;
use Route4Me\Track;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get a random route ID
$route = new Route();

$routeId = $route->getRandomRouteId(0, 20);
assert(!is_null($routeId), "Can't retrieve a random route ID");
echo "routeId -> $routeId <br><br>"; 

// Set GPS position to the selected route and use the correct member_id corresponding to the API key.
$params = TrackSetParams::fromArray(array(
    'format'           => Format::SERIALIZED,
    'route_id'         => $routeId,
    'member_id'        => 105323,
    'course'           => 3,
    'speed'            => 100,
    'lat'              => 41.8927521,
    'lng'              => -109.0803888,
    'device_type'      => DeviceType::IPHONE,
    'device_guid'      => 'qweqweqwe',
    'device_timestamp' => date('Y-m-d H:i:s')
));

$status = Track::set($params);

assert(!is_null($status), "Can't send GPS position to the selected route");
assert(isset($status['status']), "Can't send GPS position to the selected route");
assert($status['status'], "Can't send GPS position to the selected route");

if (!$status) {
    echo "Setting of GPS position failed";
    return;
}

$params = array(
    'route_id'                 =>  $routeId,
    'device_tracking_history'  =>  '1'
);

$result = $route->GetLastLocation($params);

if (isset($result->tracking_history))
foreach ($result->tracking_history as $history) {
    echo "Speed --> ".$history['s']."<br>";
    echo "course --> ".$history['d']."<br>";
    echo "Timestamp --> ".$history['ts_friendly']."<br>";
    echo "Latitude --> ".$history['lt']."<br>";
    echo "Longitude --> ".$history['lg']."<br>";
    echo "========================================<br><br>";
}
package TrackDeviceLastLocationHistory;
use strict;
use warnings FATAL => 'all';
use Data::Dumper;
use Route4MeSDK::DataTypes::OptimizationState;

sub TrackDeviceLastLocationHistory {
    my ($self, $routeId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $gpsParameters = GPSParameters->new(
        format => Format->Csv,
        route_id => $routeId,
        lat => 33.14384,
        lng => -83.22466,
        course => 1,
        speed => 120,
        device_type => DeviceType->IPhone,
        member_id => 1,
        device_guid => "TEST_GPS",
        device_timestamp => "2014-06-14 17:43:35"
    );

    my $errorString="";
    my $response = $route4Me->setGPS($gpsParameters, $errorString);

    print "\n";

    if (!$response->{'status'}) {
        print "SetGps not available for this account\n";
        return;
    } elsif (!$errorString) {
        printf "SetGps response: %s\n\n", $response;
    } else {
        printf "SetGps error: %s\n\n", $errorString;
        return;
    }

    my $dataObject = $route4Me->getLastLocation({route_id => $routeId, device_tracking_history => 1}, $errorString);

    print "\n";

    if ($dataObject)
    {
        printf "TrackDeviceLastLocationHistory executed successfully";
        print "\n";

        printf "Optimization Problem ID: %s\n", $dataObject->optimization_problem_id;
        printf "State: %s\n", OptimizationState->get_optimization_state($dataObject->state);
        print "\n";

        foreach my $th (@{$dataObject->tracking_history}) {
          printf "Speed: %s\n",      $th->s;
          printf "Longitude: %s\n",  $th->lg;
          printf "Latitude: %s\n",   $th->lt;
          printf "Time Stamp: %s\n", $th->ts_friendly;
          print "\n";
        };
    }
    else
    {
        printf "TrackDeviceLastLocationHistory error: %s\n", $errorString;
    }
}
1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/route.php
SET apikey=11111111111111111111111111111111
SET routeid=32F63FD03B08A5754CF2D516198FC8BA

:: The example refers to the process of getting the last location history of a GPS device.

ECHO ON

curl -o file1.txt -k -g -X GET "%url%?route_id=%routeid%&api_key=%apikey%&device_tracking_history=1" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/route.php
apikey=11111111111111111111111111111111
routeid=32F63FD03B08A5754CF2D516198FC8BA

# The example refers to the process of getting the last location history of a GPS device.

curl -o file1.txt -g -X GET "$url?route_id=$routeid&api_key=$apikey&device_tracking_history=1" 

echo "Finished..."

sleep 15
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/tracking"
    "github.com/route4me/route4me-go-sdk/routing" //You might need routing for device type
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &tracking.Service{Client: client}
  
  dataObject, err := service.GetLastLocation("route-id")
  if err != nil {
    //handle errors
  }
  //dataObject.TrackingHistory contains all tracking history
}
unit TrackDeviceLastLocationHistoryUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TTrackDeviceLastLocationHistory = class(TBaseExample)
  public
    procedure Execute(RouteId: String);
  end;

implementation

uses GPSParametersUnit, EnumsUnit, GenericParametersUnit, DataObjectUnit,

  TrackingHistoryUnit;

procedure TTrackDeviceLastLocationHistory.Execute(RouteId: String);

var
  ErrorString: String;
  Parameters: TGPSParameters;
  GenericParameters: TGenericParameters;
  Response: String;
  DataObject: TDataObject;
  HistoryStep: TTrackingHistory;
begin
  Parameters := TGPSParameters.Create();
  try
    Parameters.Format := TFormatDescription[TFormatEnum.Csv];
    Parameters.RouteId := RouteId;
    Parameters.Latitude := 33.14384;
    Parameters.Longitude := -83.22466;
    Parameters.Course := 1;
    Parameters.Speed := 120;
    Parameters.DeviceType := TDeviceTypeDescription[TDeviceType.IPhone];
    Parameters.MemberId := 1;
    Parameters.DeviceGuid := 'TEST_GPS';
    Parameters.DeviceTimestamp := '2014-06-14 17:43:35';

    Response := Route4MeManager.Tracking.SetGPS(Parameters, ErrorString);

    if (ErrorString <> EmptyStr) then
    begin
      WriteLn(Format('SetGps error: "%s"', [ErrorString]));
      Exit;
    end;

    WriteLn(Format('SetGps response: %s', [Response]));

    GenericParameters := TGenericParameters.Create();
    try
      GenericParameters.AddParameter('route_id', RouteId);
      GenericParameters.AddParameter('device_tracking_history', '1');

      DataObject := Route4MeManager.Tracking.GetLastLocation(GenericParameters, ErrorString);
      try
        WriteLn('');

        if (DataObject <> nil) then
        begin
          WriteLn('TrackDeviceLastLocationHistory executed successfully');
          WriteLn('');

          WriteLn(Format('Optimization Problem ID: %s', [DataObject.OptimizationProblemId]));
            WriteLn(Format('State: %s',
              [TOptimizationDescription[TOptimizationState(DataObject.State)]]));
          WriteLn('');

          for HistoryStep in DataObject.TrackingHistories do
          begin
            WriteLn(Format('Speed: %f', [HistoryStep.Speed.Value]));
            WriteLn(Format('Longitude: %f', [HistoryStep.Longitude.Value]));
            WriteLn(Format('Latitude: %f', [HistoryStep.Latitude.Value]));
            WriteLn(Format('Time Stamp: %s', [HistoryStep.TimeStamp.Value]));
            WriteLn('');
          end;
        end
        else
          WriteLn(Format('TrackDeviceLastLocationHistory error: "%s"', [ErrorString]));
      finally
        FreeAndNil(DataObject);
      end;
    finally
      FreeAndNil(GenericParameters);
    end;
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
////////////////////////////////////////////////////////////////////////////////
// Track device location history
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const int POINTS = 3;
    const char *t[POINTS] = {"2014-07-28 17:23:35", "2014-07-28 17:33:35", "2014-07-28 17:43:35"};
    double speed0 = 120;
    double lng0 = -83.22466;
    const char *route_id = "AC16E7D338B551013FF34266FE81A5EE";
    Json::Value params(Json::objectValue);
    params["route_id"] = route_id;
    params["format"] = CRoute4Me::Csv;
    params["lat"] = 33.14384;
    params["course"] = 1;
    params["device_type"] = CRoute4Me::IPhone;
    params["device_guid"] = "TEST_GPS";
    params["member_id"] = 1;
    int ret = 0;
    for(int i = 0; i < POINTS; i++)
    {
        params["lng"] = lng0 - (double)i / 10;
        params["speed"] = speed0 + i * 10;
        params["device_timestamp"] = t[i];
        if(route.set_gps(params) != 0)
        {
            cout << "Err: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
            ret = -1;
            break;
        }
    }
    if(ret == 0)
    {
        Json::Value params2(Json::objectValue);
        params2["route_id"] = route_id;
        params2["device_tracking_history"] = 1;
        if(route.get_route(params2) == 0)
        {
            cout << "Track device location history:" << endl << Json::StyledWriter().write(route.get_json_resp()) << endl;
        }
        else
        {
            cout << "Err: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
            ret = -1;
        }
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
"use strict"

const path = require("path")
const debug = require("debug")("route4me-node:examples")

require("../init-examples-suite")
const helper  = require("./../../test/helper")

helper.describeIntegration(helper.toSuiteName(__filename), function T() {
  this.timeout(5000)
  this.slow(3000)
  it(path.basename(__filename), (done) => {
    // const Route4Me = require("route4me-node")

    const apiKey   = "11111111111111111111111111111111"
    const route4me = new Route4Me(apiKey)

    const routeId = "32F63FD03B08A5754CF2D516198FC8BA"
    const options = { includeTracking: true }

    route4me.Routes.get(routeId, options, (err, route) => {
      debug("error  ", err)
      debug("result ", route)

      // Expectations about result
      expect(err).is.null

      expect(route).is.not.empty
      expect(route).has.property("route_id", "32F63FD03B08A5754CF2D516198FC8BA")
      expect(route).has.property("tracking_history")
        .that.is.an("array")

      // TODO: remove `done` call from examples
      done()
    })
  })
})
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/route.php?api_key=...&route_id=...&device_tracking_history=...



See the sample JSON response of this method.


b) Get the device’s location history from a time range.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
time_period string If equal to ‘custom’, you can get the device’s location history from a time range.
start_date integer Start of the time range in Epoch format
end_date integer End of the time range in Epoch format
<job id="Get Device Location History From Time Range">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      ' The example refers to the process of getting the last location history of a device based on a specified time range.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api/track/get_device_location.php"
      apikey="11111111111111111111111111111111"
      route_id="814FB49CEA8188D134E9D4D4B8B0DAF7"
      format="json"
      time_period="custom"
      start=UDATE("20/10/2016 00:00:00")
      tend=UDATE("26/10/2016 23:59:59")
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&route_id
      url=url&"&format="&format
      url=url&"&time_period="&time_period
      url=url&"&start_date="&start
      url=url&"&end_date="&tend
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
    
    function UDate(oldDate)
      UDate = DateDiff("s", "01/01/1970 00:00:00", oldDate)
    end function
  </script>
</job>
@ECHO OFF
SET url=https://api.route4me.com/api/track/get_device_location.php
SET apikey=11111111111111111111111111111111

SET routeid=814FB49CEA8188D134E9D4D4B8B0DAF7
SET time_period=custom

call get_unix_time 2016-10-20_00:00:00 start

call get_unix_time 2016-10-26_23:59:59 end

:: The example refers to the process of getting the last location history of a device based on a specified time range.

:: See the other parameters at: https://github.com/route4me/route4me-json-schemas/blob/master/TrackingHistory_request.json

ECHO ON

curl -o file1.txt -k -g -X GET "%url%?route_id=%routeid%&api_key=%apikey%&format=json&time_period=%time_period%&start_date=%start%&end_date=%end%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api/track/get_device_location.php
apikey=11111111111111111111111111111111
routeid=814FB49CEA8188D134E9D4D4B8B0DAF7
time_period=custom

start=$(date -d"2016-10-20T00:00" +%s)
end=$(date -d"2016-10-26T23:59" +%s)

# The example refers to the process of getting the last location history of a device based on a specified time range.

# See other parameters at: https://github.com/route4me/route4me-json-schemas/blob/master/TrackingHistory_request.json

curl -o file1.txt -k -g -X GET "$url?route_id=$routeid&api_key=$apikey&format=json&time_period=$time_period&start_date=$start&end_date=$end"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Device History from Time Range
        /// </summary>
        public void GetDeviceHistoryTimeRange(string routeId)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            int uStartTime = 0;
            int uEndTime = 0;
            uStartTime = (int)(new DateTime(2016, 10, 20, 0, 0, 0) - (new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds;
            uEndTime = (int)(new DateTime(2016, 10, 26, 23, 59, 59) - (new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds;

            GPSParameters gpsParameters = new GPSParameters
            {
                Format = "csv",
                RouteId = routeId,
                time_period = "custom",
                start_date = uStartTime,
                end_date = uEndTime
            };

            string errorString = "";
            string response = route4Me.SetGPS(gpsParameters, out errorString);

            if (!string.IsNullOrEmpty(errorString))
            {
                Console.WriteLine("SetGps error: {0}", errorString);
                return;
            }

            Console.WriteLine("SetGps response: {0}", response);

            GenericParameters genericParameters = new GenericParameters();
            genericParameters.ParametersCollection.Add("route_id", routeId);
            genericParameters.ParametersCollection.Add("device_tracking_history", "1");

            var dataObject = route4Me.GetLastLocation(genericParameters, out errorString);

            Console.WriteLine("");

            if (dataObject != null)
            {
                Console.WriteLine("GetDeviceHistoryTimeRange executed successfully");
                Console.WriteLine("");

                Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId);
                Console.WriteLine("State: {0}", dataObject.State);
                Console.WriteLine("");
                foreach (TrackingHistory th in dataObject.TrackingHistory)
                {
                    Console.WriteLine("Speed: {0}", th.Speed);
                    Console.WriteLine("Longitude: {0}", th.Longitude);
                    Console.WriteLine("Latitude: {0}", th.Latitude);
                    Console.WriteLine("Time Stamp: {0}", th.TimeStampFriendly);
                    Console.WriteLine("");
                }
            }
            else
            {
                Console.WriteLine("GetDeviceHistoryTimeRange error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetDeviceHistoryTimeRange(routeId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Create the GPS parameters
            Dim uStartTime As Integer
            Dim uEndTime As Integer
            uStartTime = ((New DateTime(2016, 10, 20, 0, 0, 0)) - (New DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds
            uEndTime = ((New DateTime(2016, 10, 26, 23, 59, 59)) - (New DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds

            Dim gpsParameters As New GPSParameters() With { _
                .Format = EnumHelper.GetEnumDescription(Format.Csv), _
                .RouteId = routeId, _
                .time_period = "custom", _
                .start_date = uStartTime, _
                .end_date = uEndTime _
            }

            Dim errorString As String = ""
            Dim response As String = route4Me.SetGPS(gpsParameters, errorString)

            If Not String.IsNullOrEmpty(errorString) Then
                Console.WriteLine("SetGps error: {0}", errorString)
                Return
            End If

            Console.WriteLine("SetGps response: {0}", response)

            Dim genericParameters As New GenericParameters()
            genericParameters.ParametersCollection.Add("route_id", routeId)
            genericParameters.ParametersCollection.Add("device_tracking_history", "1")

            Dim dataObject = route4Me.GetLastLocation(genericParameters, errorString)

            Console.WriteLine("")

            If dataObject IsNot Nothing Then
                Console.WriteLine("GetDeviceHistoryTimeRange executed successfully")
                Console.WriteLine("")

                Console.WriteLine("Optimization Problem ID: {0}", dataObject.OptimizationProblemId)
                Console.WriteLine("State: {0}", dataObject.State)
                Console.WriteLine("")
                For Each th As TrackingHistory In dataObject.TrackingHistory
                    Console.WriteLine("Speed: {0}", th.Speed)
                    Console.WriteLine("Longitude: {0}", th.Longitude)
                    Console.WriteLine("Latitude: {0}", th.Latitude)
                    Console.WriteLine("Time Stamp: {0}", th.TimeStampFriendly)
                    Console.WriteLine("")
                Next
            Else
                Console.WriteLine("GetDeviceHistoryTimeRange error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/tracking"
    "github.com/route4me/route4me-go-sdk/routing" //You might need routing for device type
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &tracking.Service{Client: client}
    trackingHistory, err := service.GetDeviceLocationHistory(&tracking.TrackingHistoryQuery{
        TimePeriod: tracking.TimePeriodCustom,
        StartDate:  unix-time-start-date,
        EndDate:    unix-time-end-date,
        RouteID:    `route-id`,
    })
    if err != nil {
        //handle errors
    }
    //trackingHistory contains all tracking history
}
<?php
namespace Route4Me;
    
$root=realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Enum\DeviceType;
use Route4Me\Enum\Format;
use Route4Me\TrackSetParams;
use Route4Me\Track;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get a random route ID
$route = new Route();

$routeId = $route->getRandomRouteId(0, 20);
assert(!is_null($routeId), "Can't retrieve a random route ID");
echo "routeId -> $routeId <br><br>"; 

// Set GPS position to the selected route and use the correct member_id corresponding to the API key.
$params = TrackSetParams::fromArray(array(
    'format'           => Format::SERIALIZED,
    'route_id'         => $routeId,
    'member_id'        => 1,
    'course'           => 1,
    'speed'            => 120,
    'lat'              => 41.8927521,
    'lng'              => -109.0803888,
    'device_type'      => 'android_phone',
    'device_guid'      => 'qweqweqwe',
    'device_timestamp' => date('Y-m-d H:i:s', strtotime('-2 day'))
));

$status = Track::set($params);

assert(!is_null($status), "Can't send GPS position to the selected route");
assert(isset($status['status']), "Can't send GPS position to the selected route");
assert($status['status'], "Can't send GPS position to the selected route");

// Get the device tracking history from a time range
$startDate = time() - 30*24*3600;
$endDate = time() + 1*24*3600;

$params = array(
    'route_id'     => $routeId,
    'format'       => Format::JSON,
    'time_period'  => 'custom',
    'start_date'   => $startDate,
    'end_date'     => $endDate
);

$result = $route->GetTrackingHistoryFromTimeRange($params);

foreach ($result as $key => $value)
{
    if (is_array($value)) {
        Route4Me::simplePrint($value);
    } else {
        echo "$key => $value <br>";
    }
}
unit GetLocationHistoryFromTimeRangeUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetLocationHistoryFromTimeRange = class(TBaseExample)
  public
    procedure Execute(RouteId: String; StartDate, EndDate: TDateTime);
  end;

implementation
uses
  TrackingHistoryUnit, TrackingHistoryResponseUnit;
procedure TGetLocationHistoryFromTimeRange.Execute(
  RouteId: String; StartDate, EndDate: TDateTime);
var
  ErrorString: String;
  Response: TTrackingHistoryResponse;
  HistoryStep: TTrackingHistory;
  LastPositionOnly: boolean;
begin
  LastPositionOnly := False;
  Response := Route4MeManager.Tracking.GetLocationHistory(
    RouteId, StartDate, EndDate, LastPositionOnly, ErrorString);
  try
    WriteLn('');

    if (Response <> nil) then
    begin
      WriteLn('GetLocationHistoryFromTimeRange executed successfully');
      WriteLn('');

      WriteLn(Format('Total location history steps: %d', [Length(Response.TrackingHistories)]));
      WriteLn('');

      for HistoryStep in Response.TrackingHistories do
      begin
        WriteLn(Format('Speed: %f', [HistoryStep.Speed.Value]));
        WriteLn(Format('Longitude: %f', [HistoryStep.Longitude.Value]));
        WriteLn(Format('Latitude: %f', [HistoryStep.Latitude.Value]));
        WriteLn(Format('Time Stamp: %s', [HistoryStep.TimeStamp.Value]));
        WriteLn('');
      end;
    end
    else
      WriteLn(Format('GetLocationHistoryFromTimeRange error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Response);
  end;
end;
end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main(int argc, char* argv[])
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY, true);

    const char *route_id = "AC16E7D338B551013FF34266FE81A5EE";

    // Dates are in Unix format
    int start_date = 1476910800;
    int end_date = 1477515540;

    const char* period = "custom";

    int ret = route.get_device_location(route_id, start_date, end_date, period);
    if (ret == 0)
        cout << "Device location history: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "No history for device found: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
.../get_device_location.php?api_key=...&route_id=...&time_period=...&$start_date=...&$end_date=...

You can expect this API response:

{
    {
  "data": [{
    "s": "60",
    "lt": "41.00478",
    "m": 0,
    "lg": "-81.59004",
    "d": 70,
    "ts": "1477488852",
    "ts_friendly": "2016-10-26 09:34:12",
    "src": "R4M",
    "cd": null
  },
  {
    "s": "60",
    "lt": "41.00478",
    "m": 0,
    "lg": "-81.59004",
    "d": 70,
    "ts": "1477489979",
    "ts_friendly": "2016-10-26 09:52:59",
    "src": "R4M",
    "cd": null
  },
  {
    "s": "60",
    "lt": "41.003672",
    "m": 0,
    "lg": "-81.598461",
    "d": 70,
    "ts": "1477490169",
    "ts_friendly": "2016-10-26 09:56:09",
    "src": "R4M",
    "cd": null
  }],
  "mmd": {
    "status": 0,
    "matchings": [{
      "trace_time": 4294966169,
      "trace_distance": 0,
      "matched_points": [[41.004784,-81.590042],
      [41.004784,-81.590042]],
      "indices": [1,2],
      "matched_time": 0,
      "instructions": [
      ["10", "Phlox Place", 0,0,6, "0m", "N", 0,1],
      ["15","",0,1,0, "0m","N", 0]],
      "matched_distance": 0,
      "geometry": "}mvemArpzrzC??"
    }],
    "summary": {
      "total_distance": 717,
      "matched_time": 0,
      "matched_distance": 0,
      "total_time": -190,
      "trace_time": 4294965979,
      "trace_distance": 718
    }
  }
}
}

Insert Route Tracking Data

Set the GPS position of a device.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
member_id integer Member ID
course integer Movement course
speed integer Movement speed
lat number Latitude
lng number Longitude
device_type string Device type
device_guid string Device GUID
<job id="Set GPS Position">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      ' The example refers to the process of setting the GPS position of a device by sending HTTP parameters.

      ' You can also use these optional parameters: tx_id, vehicle_id altitude, device_timestamp, and app_version.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/track/set.php"
      apikey="11111111111111111111111111111111"
      membid="1"
      route_id="114B01238180A4227FD187E128C056F5"
      course="70"
      speed="60"
      lat="55.6884868"
      lng="12.5366426"
      devtype="android_phone"
      devguid="HK5454H0K454564WWER445"
      
      url=url&"?api_key="&apikey
      url=url&"&member_id="&membid
      url=url&"&route_id="&route_id
      url=url&"&course="&course
      url=url&"&speed="&speed
      url=url&"&lat="&lat
      url=url&"&lng="&lng
      url=url&"&device_type="&devtype
      url=url&"&device_guid="&devguid
      
      ' There are also several optional parameters: tx_id, vehicle_id altitude, device_timestamp, app_version
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void SetGPSPosition(string routeId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Create the GPS parameters
      GPSParameters gpsParameters = new GPSParameters()
      {
        Format = Format.Csv.Description(),
        RouteId = routeId,
        Latitude = 33.14384,
        Longitude = -83.22466,
        Course = 1,
        Speed = 120,
        DeviceType = DeviceType.IPhone.Description(),
        MemberId = 1,
        DeviceGuid = "TEST_GPS",
        DeviceTimestamp = "2014-06-14 17:43:35"
      };

      string errorString;
      string response = route4Me.SetGPS(gpsParameters, out errorString);

      Console.WriteLine("");

      if (string.IsNullOrEmpty(errorString))
      {
        Console.WriteLine("SetGps response: {0}", response);
      }
      else
      {
        Console.WriteLine("SetGps error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SetGPSPosition(routeId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Create the GPS parameters
            Dim gpsParameters As New GPSParameters() With { _
                .Format = Format.Csv, _
                .RouteId = routeId, _
                .Latitude = 33.14384, _
                .Longitude = -83.22466, _
                .Course = 1, _
                .Speed = 120, _
                .DeviceType = EnumHelper.GetEnumDescription(DeviceType.IPhone), _
                .MemberId = 1, _
                .DeviceGuid = "TEST_GPS", _
                .DeviceTimestamp = "2014-06-14 17:43:35" _
            }

            Dim errorString As String = ""
            Dim response As String = route4Me.SetGPS(gpsParameters, errorString)

            Console.WriteLine("")

            If String.IsNullOrEmpty(errorString) Then
                Console.WriteLine("SetGps response: {0}", response)
            Else
                Console.WriteLine("SetGps error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import (
    FORMAT,
    DEVICE_TYPE
)

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    route = route4me.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        setGPS = route4me.setGPS
        setGPS.format(FORMAT.CSV)
        setGPS.route_id(response[0].route_id)
        setGPS.lat(33.14384),
        setGPS.lng(-83.22466)
        setGPS.course(1)
        setGPS.speed(120)
        setGPS.device_type(DEVICE_TYPE.IPHONE, 'param')
        setGPS.member_id(1, 'param')
        setGPS.device_guid('TEST_GPS')
        setGPS.device_timestamp('2014-06-14 17:43:35')
        print setGPS.params
        print setGPS.set_gps_track()


if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.tracking;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Constants;
import com.route4me.sdk.services.tracking.GPSPosition;
import com.route4me.sdk.services.tracking.TrackingManager;

public class SetGPSPosition {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        TrackingManager manager = new TrackingManager(apiKey);
        GPSPosition position = new GPSPosition().setLatitude(33.14384).setLongitude(-83.22466).setAltitude(10D);
        position.setFormat(Constants.Format.CSV);
        position.setRouteId("1402075EBA9A32939B2696DB1D7EE48E");
        position.setCourse(1);
        position.setSpeed(120F);
        position.setDeviceType(Constants.DeviceType.IPAD)
                .setDeviceGUID("TEST_GPS")
                .setDeviceTimestamp("2014-06-14 17:43:35");
        position.setMemberId("1");
        try {
            manager.setGPS(position);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;
    
$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Enum\DeviceType;
use Route4Me\Enum\Format;
use Route4Me\TrackSetParams;
use Route4Me\Track;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get a random route ID
$route = new Route();

$routeId = $route->getRandomRouteId(0, 20);
assert(!is_null($routeId), "Can't retrieve a random route ID");
echo "routeId -> $routeId <br><br>"; 

// Set GPS position to the selected route and use the correct member_id corresponding to the API key.
$params = TrackSetParams::fromArray(array(
    'format'           => Format::CSV,
    'route_id'         => $routeId,
    'member_id'        => 1,
    'course'           => 1,
    'speed'            => 120,
    'lat'              => 41.8927521,
    'lng'              => -109.0803888,
    'device_type'      => 'android_phone',
    'device_guid'      => 'qweqweqwe',
    'device_timestamp' => date('Y-m-d H:i:s', strtotime('-1 day'))
));

$status = Track::set($params);

assert(!is_null($status), "Can't send GPS position to the selected route");
assert(isset($status['status']), "Can't send GPS position to the selected route");
assert($status['status'], "Can't send GPS position to the selected route");

Route4Me::simplePrint($status);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/tracking"
    "github.com/route4me/route4me-go-sdk/routing" //You might need routing for device type
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &tracking.Service{Client: client}
  
  query := &tracking.GPS{
    RouteID:         "route-id",
    Latitude:        33.14384,
    Longitude:       -83.22466,
    Course:          1,
    Speed:           120,
    DeviceType:      routing.IPad,
    MemberID:        1,
    DeviceGUID:      "TEST_GPS",
    DeviceTimestamp: "2014-06-14 17:43:35",
  }
  _, err = service.SetGPS(query)
  if err != nil {
    //handle errors
    return
  }
}
package SetGPSPosition;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::DataTypes::Format;
use Route4MeSDK::QueryTypes::GPSParameters;
use Data::Dumper;

sub SetGPSPosition{
    my ($self, $routeId) = @_;
    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $gpsParameters = GPSParameters->new(
        format => Format->Csv,
        route_id => $routeId,
        lat => 33.14384,
        lng => -83.22466,
        course => 1,
        speed => 120,
        device_type => DeviceType->IPhone,
        member_id => 1,
        device_guid => "TEST_GPS",
        device_timestamp => "2014-06-14 17:43:35"
    );

    my $errorString="";
    my $response = $route4Me->setGPS($gpsParameters, $errorString);

    print "\n";

    print Dumper($response);

    if (!$response->{'status'}) {
        print "SetGps not available for this account\n";
    } elsif (!$errorString) {
        printf "SetGps response: %s\n", $response;
    } else {
        printf "SetGps error: %s\n", $errorString;
    }
}
1;
@ECHO OFF

SET url=https://api.route4me.com/track/set.php
SET apikey=11111111111111111111111111111111
SET membid=1
SET route_id=114B01238180A4227FD187E128C056F5
SET course=70
SET speed=60
SET lat=55.6884868
SET lng=12.5366426
SET devtype=android_phone
SET devguid="HK5454H0K454564WWER445"

ECHO ON

:: The example refers to the process of setting the GPS position of a device by sending HTTP parameters.

:: You can also use these optional parameters: tx_id, vehicle_id altitude, device_timestamp, and app_version.

curl -o file1.txt -g -X GET -k "%url%?api_key=%apikey%&member_id=%membid%&route_id=%route_id%&course=%course%&speed=%speed%&lat=%lat%&lng=%lng%&device_type=%devtype%&device_guid=%devguid%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/track/set.php
apikey=11111111111111111111111111111111
membid=1
route_id=114B01238180A4227FD187E128C056F5
course=70
speed=60
lat=55.6884868
lng=12.5366426
devtype=android_phone
devguid="HK5454H0K454564WWER445"

# The example refers to the process of setting the GPS position of a device by sending HTTP parameters.

# You can also use these optional parameters: tx_id, vehicle_id altitude, device_timestamp, and app_version.

curl -o file1.txt -g -X GET -k "$url?api_key=$apikey&member_id=$membid&route_id=$route_id&course=$course&speed=$speed&lat=$lat&lng=$lng&device_type=$devtype&device_guid=$devguid"

echo "Finished..."

sleep 15
unit SetGPSPositionUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TSetGPSPosition = class(TBaseExample)
  public
    procedure Execute(RouteId: String);
  end;

implementation

uses GPSParametersUnit, EnumsUnit;

procedure TSetGPSPosition.Execute(RouteId: String);

var
  ErrorString: String;
  Parameters: TGPSParameters;
  Response: String;
begin
  Parameters := TGPSParameters.Create();
  try
    Parameters.Format := TFormatDescription[TFormatEnum.Csv];
    Parameters.RouteId := RouteId;
    Parameters.Latitude := 33.14384;
    Parameters.Longitude := -83.22466;
    Parameters.Course := 1;
    Parameters.Speed := 120;
    Parameters.DeviceType := TDeviceTypeDescription[TDeviceType.IPhone];
    Parameters.MemberId := 1;
    Parameters.DeviceGuid := 'TEST_GPS';
    Parameters.DeviceTimestamp := '2014-06-14 17:43:35';

    Response := Route4MeManager.Tracking.SetGPS(Parameters, ErrorString);

    WriteLn('');

    if (ErrorString = EmptyStr) then
      WriteLn(Format('SetGps response: %s', [Response]))
    else
      WriteLn(Format('SetGps error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
////////////////////////////////////////////////////////////////////////////////
// Set GPS
////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    Json::Value params(Json::objectValue);
    params["route_id"] = "AC16E7D338B551013FF34266FE81A5EE";
    params["format"] = CRoute4Me::Csv;
    params["lat"] = 33.14384;
    params["lng"] = -83.22466;
    params["course"] = 1;
    params["speed"] = 120;
    params["device_type"] = CRoute4Me::IPhone;
    params["device_guid"] = "TEST_GPS";
    params["device_timestamp"] = "2014-06-14 17:43:35";
    params["member_id"] = 1;
    int ret = 0;
    if(route.set_gps(params) == 0)
    {
        // use Json::StyledWriter instead of Json::FastWriter for a human friendly output
        cout << "GPS point is set:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Err: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    struct MapPoint point = {33.143840, -83.224660};

    json_object* props = json_object_new_object();
    json_object_object_add(props, "route_id", json_object_new_string("AC16E7D338B551013FF34266FE81A5EE"));
    json_object_object_add(props, "lat", json_object_new_double(point.lat));
    json_object_object_add(props, "lng", json_object_new_double(point.lng));
    json_object_object_add(props, "course", json_object_new_int(1));
    json_object_object_add(props, "speed", json_object_new_int(120));
    json_object_object_add(props, "device_type", json_object_new_string("iphone"));
    json_object_object_add(props, "device_guid", json_object_new_string("TEST_GPS"));
    json_object_object_add(props, "device_timestamp", json_object_new_string("2014-06-14%2017%3A43%3A35"));
    json_object_object_add(props, "member_id", json_object_new_int(1));
    json_object_object_add(props, "format", json_object_new_string("csv"));

    init(key, 1);

    if (!set_gps(props))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/track/set.php?api_key=...&route_id=...&member_id=...&course=...&speed=...&lat=...&lng=...

You can expect this API response:

{"status":true}

Get All User Locations

You can retrieve all user locations.


PARAMETERS

Parameter Type Description
api_key string API key of the user
<job id="Get All User Locations">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			
			'You should insert real test data and your API key for accurate testing
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api/track/view_user_locations.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			Set r4m=New Route4Me
			r4m.outputFile="user_locations_get_all_RESPONSE.json"
			
			r4m.HttpGetRequest(url)
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api/track/view_user_locations.php
SET apikey=11111111111111111111111111111111

:: Example refers to the process of getting all user locations.

ECHO ON

curl -o user_locations_get_all_RESPONSE.json -k -g -X GET "%URL%?route_id=%routeid%&api_key=%apikey%" 

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api/track/view_user_locations.php
apikey=11111111111111111111111111111111

 # Example refers to the process of getting all user locations.

curl -o user_locations_get_all_RESPONSE.json -g -k -X GET "$url?api_key=$apikey" 

echo "Finished..."

sleep 15
public void GetAllUserLocationsTest()
{
	var route4Me = new Route4MeManager(ApiKeys.actualApiKey);

	var genericParameters = new GenericParameters();

	var userLocations = route4Me.GetUserLocations(genericParameters, out string errorString);

	Assert.IsNotNull(userLocations, "GetAllUserLocationsTest failed... " + errorString);
}
Public Sub GetAllUserLocationsTest()
	Dim route4Me = New Route4MeManager(ApiKeys.actualApiKey)

	Dim genericParameters = New GenericParameters()

	Dim errorString As String = Nothing
	Dim userLocations = route4Me.GetUserLocations(genericParameters, errorString)

	Assert.IsNotNull(userLocations, "GetAllUserLocationsTest failed... " & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the api key in the Route4me class
Route4Me::setApiKey('11111111111111111111111111111111');

$track = new Track();

$userLocations = $track->getUserLocations();

foreach ($userLocations As $memberId => $userLocation) {
    echo $userLocation['member_data']['member_first_name'].' '.$userLocation['member_data']['member_last_name']." --> ";
	
    if (isset($userLocation['tracking']['position_lng'])) {
        echo "Longitude: ".$userLocation['tracking']['position_lng'].", Latitude: ".$userLocation['tracking']['position_lat'];
    }
	
    echo "<br>";
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/track/view_user_locations.php?api_key=...

You can expect this API response:

{
	"1": {
		"member_data": {
			"member_id": 1,
			"member_first_name": "David",
			"member_last_name": "Progman",
			"member_email": "[email protected]",
			"account_type_id": 126,
			"member_type": "PRIMARY_ACCOUNT",
			"phone_number": null,
			"readonly_user": 0,
			"show_superuser_addresses": 1
		},
		"tracking": {
			"route_id": "26057d4c12aadc95399c5ef828abeeba",
			"device_id": "a77096d71abbc18e08dc8581f7365dbbc736d230",
			"activity_timestamp": 1570211723,
			"device_timestamp": "2019-10-04 13:55:23",
			"device_type": "iphone",
			"member_id": 1,
			"vehicle_id": 0,
			"direction": 1,
			"speed": 268.4328,
			"day_id": 3564,
			"position_lat": 40.7669692,
			"position_lng": -73.9693864,
			"altitude": 0,
			"footsteps": null,
			"data_source_name": "R4M",
			"custom_data": "",
			"device_timezone": "America/New_York",
			"device_timezone_offset": 0,
			"activity_timestamp_friendly": "10/04/2019 01:10:23",
			"LAST_KNOWN": 1570211723
		},
		"from_cache": true
	},
	"2": {
		"member_data": {
			"member_id": 2,
			"member_first_name": "Gill",
			"member_last_name": "Shchredinger",
			"member_email": "[email protected]",
			"account_type_id": 126,
			"member_type": "PRIMARY_ACCOUNT",
			"phone_number": null,
			"readonly_user": 0,
			"show_superuser_addresses": 1
		},
		"tracking": []
	},
	"3": {
		"member_data": {
			"member_id": 3,
			"member_first_name": "Edil",
			"member_last_name": "Corone",
			"member_email": "[email protected]",
			"account_type_id": 126,
			"member_type": "PRIMARY_ACCOUNT",
			"phone_number": null,
			"readonly_user": 0,
			"show_superuser_addresses": null
		},
		"tracking": []
	},
	"4": {
		"member_data": {
			"member_id": 4,
			"member_first_name": "Nat",
			"member_last_name": "Coll",
			"member_email": "[email protected]",
			"account_type_id": 126,
			"member_type": "SUB_ACCOUNT_DRIVER",
			"phone_number": null,
			"readonly_user": 1,
			"show_superuser_addresses": 1
		},
		"tracking": []
	},
	"5": {
		"member_data": {
			"member_id": 5,
			"member_first_name": "Driver",
			"member_last_name": "Driverson",
			"member_email": "[email protected]",
			"account_type_id": 126,
			"member_type": "SUB_ACCOUNT_DRIVER",
			"phone_number": null,
			"readonly_user": 0,
			"show_superuser_addresses": 0
		},
		"tracking": []
	}
}

Search User Locations

You can search the locations by query text (email, name, memebr ID etc).


PARAMETERS

Parameter Type Description
api_key string API key of the user
query string Query text
<job id="Search User Locations">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			
			'You should insert real test data and your API key for accurate testing
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api/track/view_user_locations.php"
			apikey="11111111111111111111111111111111"
			[email protected]
			
			url=url&"?api_key="&apikey
			url=url&"&query="&query
			
			Set r4m=New Route4Me
			r4m.outputFile="user_locations_query_RESPONSE.json"
			
			r4m.HttpGetRequest(url)
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api/track/view_user_locations.php
SET apikey=11111111111111111111111111111111
SET [email protected]

:: Example refers to the process of getting user locations by query.
:: Note: you can query by member_id, user email, member_type etc.

ECHO ON

curl -o user_locations_query_RESPONSE.json -k -g -X GET "%url%?api_key=%apikey%&query=%query%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api/track/view_user_locations.php
apikey=11111111111111111111111111111111
[email protected]

 # Example refers to the process of getting user locations by query.
 # Note: you can query by member_id, user email, member_type etc.

curl -o user_locations_query_RESPONSE.json -g -k -X GET "$url?api_key=$apikey&query=$query" 

echo "Finished..."

sleep 15
public void QueryUserLocationsTest()
{
	var route4Me = new Route4MeManager(ApiKeys.actualApiKey);

	var genericParameters = new GenericParameters();

	var userLocations = route4Me.GetUserLocations(genericParameters, out string errorString);

	Assert.IsNotNull(userLocations, "GetAllUserLocationsTest failed... " + errorString);

	var userLocation = userLocations.Where(x => x.Value.UserTracking != null).FirstOrDefault().Value;

	if (userLocation==null) userLocation = userLocations[userLocations.Keys.First()];

	string email = userLocation.MemberData.MemberEmail;

	genericParameters.ParametersCollection.Add("query", email);

	var queriedUserLocations = route4Me.GetUserLocations(genericParameters, out errorString);

	Assert.IsNotNull(queriedUserLocations, "QueryUserLocationsTest failed... " + errorString);

	Assert.IsTrue(queriedUserLocations.Count()==1, "QueryUserLocationsTest failed... " + errorString);
}
Public Sub QueryUserLocationsTest()
	Dim route4Me = New Route4MeManager(ApiKeys.actualApiKey)

	Dim genericParameters = New GenericParameters()

	Dim errorString As String = Nothing
	Dim userLocations = route4Me.GetUserLocations(genericParameters, errorString)

	Assert.IsNotNull(userLocations, "GetAllUserLocationsTest failed... " & errorString)

	Dim userLocation = userLocations.Where(Function(x) x.Value.UserTracking IsNot Nothing).FirstOrDefault().Value

	If userLocation Is Nothing Then userLocation = userLocations(userLocations.Keys.First())

	Dim email As String = userLocation.MemberData.MemberEmail

	genericParameters.ParametersCollection.Add("query", email)

	Dim queriedUserLocations = route4Me.GetUserLocations(genericParameters, errorString)

	Assert.IsNotNull(queriedUserLocations, "QueryUserLocationsTest failed... " & errorString)
	Assert.IsTrue(queriedUserLocations.Count() = 1, "QueryUserLocationsTest failed... " & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the api key in the Route4me class
Route4Me::setApiKey('11111111111111111111111111111111');

$track = new Track();

$userLocation = reset($track->getUserLocations());

$email = $userLocation['member_data']['member_email'];

$queriedUserLocations = $track->getUserLocations($email);

foreach ($queriedUserLocations As $memberId => $userLocation) {
    echo $userLocation['member_data']['member_first_name'].' '.$userLocation['member_data']['member_last_name']." --> ";
	
    if (isset($userLocation['tracking']['position_lng'])) {
        echo "Longitude: ".$userLocation['tracking']['position_lng'].", Latitude: ".$userLocation['tracking']['position_lat'];
    }
	
    echo "<br>";
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/track/view_user_locations.php?api_key=...&query=...

You can expect this API response:

[
	{
		"member_data": {
			"member_id": 1,
			"member_first_name": "David",
			"member_last_name": "Progman",
			"member_email": "[email protected]",
			"account_type_id": 126,
			"member_type": "PRIMARY_ACCOUNT",
			"phone_number": null,
			"readonly_user": 0,
			"show_superuser_addresses": 1
		},
		"tracking": {
			"route_id": "26057d4c12aadc95399c5ef828abeeba",
			"device_id": "a77096d71abbc18e08dc8581f7365dbbc736d230",
			"activity_timestamp": 1570211723,
			"device_timestamp": "2019-10-04 13:55:23",
			"device_type": "iphone",
			"member_id": 1,
			"vehicle_id": 0,
			"direction": 1,
			"speed": 268.4328,
			"day_id": 3564,
			"position_lat": 40.7669692,
			"position_lng": -73.9693864,
			"altitude": 0,
			"footsteps": null,
			"data_source_name": "R4M",
			"custom_data": "",
			"device_timezone": "America/New_York",
			"device_timezone_offset": 0,
			"activity_timestamp_friendly": "10/04/2019 01:10:23",
			"LAST_KNOWN": 1570211723
		},
		"from_cache": true
	}
]

Members

A member refers to an authorized user of the Route4Me API.

See the Member (User) JSON Schema in our GitHub repository.

Member Properties

Attribute Type Description
member_id string Unique ID of the member
member_first_name string First name of the member
member_last_name string Last name of the member
member_email string Member’s email address
account_type_id string Account type ID of the member
member_type string Type of member
phone_number string Member’s phone number
readonly_user string True, if the value is ‘1’.
show_superuser_addresses boolean Show superuser addresses
api_key string API key of the user
hashed_member_id string Hashed member ID string

Authentication

Authenticates a user through email and password.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
strEmail string Email of the user POST
strPassword string Password POST
format string Response format POST
<job id="MemberAutheticate">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/actions/authenticate.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="member_authenticate_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest2 url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/actions/authenticate.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example refers to the authentication process into Route4Me's official web application.

curl -o file1.txt -k -g -X POST -H "Content-Type: multipart/form-data;" -F "[email protected]" -F "strPassword=111111" -F "format=json" "%url%?api_key=%apikey%" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/authenticate.php
apikey=11111111111111111111111111111111

# The example refers to the authentication process into Route4Me's official web application.

curl -o file1.txt -k -g -X POST  -H "Content-Type: multipart/form-data;" -F "[email protected]" -F "strPassword=1111111" -F "format=json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// User Authentication
        /// </summary>
        public void UserAuthentication()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberParameters @params = new MemberParameters
            {
                StrEmail = "[email protected]",
                StrPassword = "1111111",
                Format = "json"
            };
            // Run the query
            string errorString = "";
            MemberResponse result = route4Me.UserAuthentication(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("UserAuthentication executed successfully");
                Console.WriteLine("status: " + result.Status);
                Console.WriteLine("api_key: " + result.ApiKey);
                Console.WriteLine("member_id: " + result.MemberId);
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("UserAuthentication error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' User Authentication
        ''' </summary>
        Public Sub UserAuthentication()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberParameters = New MemberParameters() With { _
                .StrEmail = "[email protected]", _
                .StrPassword = "1111111", _
                .Format = "json" _
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberResponse = route4Me.UserAuthentication(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("UserAuthentication executed successfully")
                Console.WriteLine("status: " & result.Status)
                Console.WriteLine("api_key: " & result.ApiKey)
                Console.WriteLine("member_id: " & result.MemberId)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("UserAuthentication error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    members = route4me.members
    data = {"email": "[email protected]",
            "password": "ultrasecretword",
            "format": "json"}
    response = members.member_authenticate(**data)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print response

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
  
  session, err := service.Authenticate("email","password")
  if err != nil {
    // auth unsuccessful
    return
  }
  if !session.Status {
    // session invalid
    return
  }
  //session valid
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

// Example refers to member authentication.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$Parameters = Member::fromArray(array(
    'strEmail'    => '[email protected]',
    'strPassword' => 'dddddddd',
    'format'      => 'json',
));

$member = new Member();

$response = $member->memberAuthentication($Parameters);

Route4Me::simplePrint($response);
unit AuthenticationUnit;

interface

uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit, UserParametersUnit;

type
  TAuthentication = class(TBaseExample)
  public
    function Execute(EMail, Password: String): NullableString;
  end;

implementation
function TAuthentication.Execute(EMail, Password: String): NullableString;
var
  ErrorString: String;
  SessionId: NullableInteger;
begin
  Route4MeManager.User.Authentication(EMail, Password, ErrorString, SessionId, Result);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    WriteLn(Format('Authentication executed successfully, SessionId = %d', [Result.Value]));
    WriteLn('');
  end
  else
    WriteLn(Format('Authentication error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY, true);

    int ret = 0;

    Member member;
    member.email = "[email protected]";
    member.password1 = "123456";
    member.format = "json";

    if(route.authenticate_user(&member) == 0)
    {
        cout << "Login attempted:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Failed to login: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);

    struct Member member = {0};
    strcpy(member.email, "[email protected]");
    strcpy(member.format, "json");
    strcpy(member.first_name, "Alex");
    strcpy(member.last_name, "Hardworker");
    strcpy(member.password1, "crypto1");

    if (!authenticate_user(&member))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

POST
/actions/authenticate.php?api_key=...

You can expect this API response:

{
  "status": true,
  "geocoding_service": "http:\/\/validator.route4me.com",
  "session_id": 3436431,
  "session_guid": "ad9001f33ed6875b5f0e75bce52cbc34",
  "member_id": "11111",
  "api_key": "11111111111111111111111111111111",
  "tracking_ttl": 10,
  "geofence_polygon_shape": "rect",
  "geofence_polygon_size": 30,
  "geofence_time_onsite_trigger_secs": 21,
  "geofence_minimum_trigger_speed": 3,
  "is_subscription_past_due": null,
  "visited_departed_enabled": "true",
  "long_press_enabled": "true",
  "account_type_id": "126",
  "account_type_alias": "Enterprise",
  "member_type": "PRIMARY_ACCOUNT",
  "max_stops_per_route": "1000",
  "max_routes": "1000",
  "routes_planned": "13",
  "preferred_units": "MI",
  "preferred_language": "en",
  "HIDE_ROUTED_ADDRESSES": "FALSE",
  "HIDE_VISITED_ADDRESSES": "FALSE",
  "HIDE_NONFUTURE_ROUTES": "FALSE",
  "READONLY_USER": "FALSE",
  "auto_logout_ts": 7200
}

Member’s Sub-users

View existing sub-users in a member’s account.


PARAMETERS

Parameter Type Description
api_key string API key of the user
<job id="Members - Get Sub-users">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example refers to the process of getting the existing sub-users.
      
      url="https://api.route4me.com/api.v4/user.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetUsers()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      GenericParameters parameters = new GenericParameters()
      {
      };

      // Run the query
      string errorString;
      User[] dataObjects = route4Me.GetUsers(parameters, out errorString);

      Console.WriteLine("");

      if (dataObjects != null)
      {
        Console.WriteLine("GetUsers executed successfully, {0} users returned", dataObjects.Length);
        Console.WriteLine("");

        //dataObjects.ForEach(user =>
        //{
        //  Console.WriteLine("User ID: {0}", user.MemberId);
        //});
      }
      else
      {
        Console.WriteLine("GetUsers error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetUsers()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim parameters As New GenericParameters()

            ' Run the query
            Dim errorString As String = ""
            Dim dataObjects As User() = route4Me.GetUsers(parameters, errorString)

            Console.WriteLine("")

            If dataObjects IsNot Nothing Then
                Console.WriteLine("GetUsers executed successfully, {0} users returned", dataObjects.Length)

                Console.WriteLine("")
            Else
                Console.WriteLine("GetUsers error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    members = route4me.members
    response = members.get_users(limit=5, offset=0)
    if 'errors' in list(response.keys()):
        print '. '.join(response.get('errors'))
    else:
        for i, member in enumerate(response):
            print('Member #{}'.format(i + 1))
            print('\tName: {0}, {1}'.format(member.get('member_first_name'), member.get('member_last_name')))
            print('\tEmail: {}'.format(member.get('member_email')))


if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.users;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.users.User;
import com.route4me.sdk.services.users.UsersManager;

import java.util.List;

public class GetUsers {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        UsersManager manager = new UsersManager(apiKey);
        try {
            List<User> users = manager.getUsers(10, 10);
            for (User user : users) {
                System.out.println(user);
            }
        } catch (APIException e) {
            e.printStackTrace();
        }
    }
}
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
  
  users, err := service.GetSubusers()
  if err != nil {
    // could not fetch users
    return
  }
  //do something with users, it's []*Member
}
package GetUsers;
use strict;
use warnings FATAL => 'all';

sub GetUsers {
    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $errorString = "";

    my @dataObject = $route4Me->getUsers( \$errorString );

    print "\n";

    if (@dataObject) {
        printf "GetUsers executed successfully, %s users returned\n\n", scalar @dataObject;

    } else {
        printf "GetRoutes error: %s\n", $errorString;
    }
}
1;
@ECHO OFF
SET url=https://api.route4me.com/api.v4/user.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of getting the existing sub-users.

ECHO ON

curl -o file1.txt -g -X GET -k "%URL%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/user.php
apikey=11111111111111111111111111111111

# The example refers to the process of getting the existing sub-users.

curl -o file1.txt -g -X GET -k "$url?api_key=$apikey"

echo "Finished..."

sleep 15
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

// The example refers to the process of getting the existing sub-users.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$member = new Member();

$response = $member->getUsers();

foreach ($response['results'] as $key => $member) {
    Route4Me::simplePrint($member);
    echo "<br>";
}
unit GetUsersUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetUsers = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses UserUnit;

procedure TGetUsers.Execute;

var
  ErrorString: String;
  Users: TArray<TUser>;
  i: integer;
begin
  Users := Route4MeManager.User.Get(ErrorString);
  try
    WriteLn('');

    if (Length(Users) > 0) then
    begin
      WriteLn(Format('GetUsers executed successfully, %d users returned',
        [Length(Users)]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetUsers error: "%s"', [ErrorString]));
  finally
    for i := Length(Users) - 1 downto 0 do
      FreeAndNil(Users[i]);
  end;
end;
end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY, true);

    if(route.get_subusers() == 0)
    {
        cout << "Sub-users:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Failed: " << route.get_err_code() << ": " << route.get_err_msg() << endl;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);

    if (!get_all_users())
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api/member/view_users.php?api_key=...

You can expect this API response:

{
  "results": [{
    "member_id": "45837",
    "OWNER_MEMBER_ID": "44194",
    "member_type": "SUB_ACCOUNT_DRIVER",
    "member_first_name": "Tony",
    "member_last_name": "Stark",
    "member_email": "[email protected]",
    "preferred_units": "MI",
    "preferred_language": "en",
    "HIDE_ROUTED_ADDRESSES": "TRUE",
    "HIDE_VISITED_ADDRESSES": "TRUE",
    "HIDE_NONFUTURE_ROUTES": "FALSE",
    "SHOW_ALL_DRIVERS": "FALSE",
    "SHOW_ALL_VEHICLES": "0",
    "READONLY_USER": "TRUE",
    "member_phone": "",
    "member_zipcode": null,
    "timezone": "America\/New_York",
    "date_of_birth": "1980-01-01",
    "user_reg_state_id": "4",
    "user_reg_country_id": "223",
    "member_picture": null,
    "level": 4
  },
  {
    "member_id": "45839",
    "OWNER_MEMBER_ID": "44194",
    "member_type": "SUB_ACCOUNT_DRIVER",
    "member_first_name": "Steve",
    "member_last_name": "Rogers",
    "member_email": "[email protected]",
    "preferred_units": "MI",
    "preferred_language": "en",
    "HIDE_ROUTED_ADDRESSES": "TRUE",
    "HIDE_VISITED_ADDRESSES": "TRUE",
    "HIDE_NONFUTURE_ROUTES": "TRUE",
    "SHOW_ALL_DRIVERS": "FALSE",
    "SHOW_ALL_VEHICLES": "0",
    "READONLY_USER": "TRUE",
    "member_phone": "",
    "member_zipcode": null,
    "timezone": "America\/New_York",
    "date_of_birth": "1980-01-01",
    "user_reg_state_id": "4",
    "user_reg_country_id": "223",
    "member_picture": null,
    "level": 4
  }
]}

Validate a Session

Check if a session is valid.


PARAMETERS

Parameter Type Description
api_key string API key of the user
session_guid string Session ID
member_id integer Member ID
format string Response format
<job id="MemberValidateSession">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example refers to the process of validating a user's working session in the Route4Me application.
      
      url="https://api.route4me.com/datafeed/session/validate_session.php"
      apikey="11111111111111111111111111111111"
      sesid="4552222222"
      memid="787544566"
      format="json"
      
      url=url&"?api_key="&apikey
      url=url&"&session_guid="&sesid
      url=url&"&member_id="&memid
      url=url&"&format="&format
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com
SET apikey=11111111111111111111111111111111
SET sesid=4552222222
SET memid=787544566

:: The example refers to the process of validating a user's working session in the Route4Me application.

ECHO ON

curl -o file1.txt -g -X GET -k "%URL%/datafeed/session/validate_session.php?api_key=%apikey%&session_guid=%sesid%&member_id=%memid%&format=json"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/datafeed/session/validate_session.php
apikey=11111111111111111111111111111111
sesid=4552222222
memid=787544566
frmt=json

# The example refers to the process of validating a user's working session in the Route4Me application.

curl -o file1.txt -g -X GET -k "$url?api_key=$apikey&session_guid=$sesid&member_id=$memid&$frmt=json"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Validate Session
        /// </summary>
        public void ValidateSession()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberParameters @params = new MemberParameters
            {
                SessionGuid = "ad9001f33ed6875b5f0e75bce52cbc34",
                MemberId = 1,
                Format = "json"
            };
            // Run the query
            string errorString = "";
            MemberResponse result = route4Me.ValidateSession(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("ValidateSession executed successfully");
                Console.WriteLine("status: " + result.Status);
                Console.WriteLine("api_key: " + result.ApiKey);
                Console.WriteLine("member_id: " + result.MemberId);
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("ValidateSession error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Validate Session
        ''' </summary>
        Public Sub ValidateSession()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberParameters = New MemberParameters() With { _
                .SessionGuid = "ad9001f33ed6875b5f0e75bce52cbc34", _
                .MemberId = 1, _
                .Format = "json" _
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberResponse = route4Me.ValidateSession(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("ValidateSession executed successfully")
                Console.WriteLine("status: " & result.Status)
                Console.WriteLine("api_key: " & result.ApiKey)
                Console.WriteLine("member_id: " & result.MemberId)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("ValidateSession error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    members = route4me.members
    data = {"session_guid": "4552222222",
            "member_id": "787544566",
            "format": "json"}
    response = members.validate_session(**data)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print response

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
  
  success, err := service.ValidateSession("GUID",memberID)
  if err != nil {
    // session invalid, error making request
    return
  }
  if !success {
    // session invalid
    return
  }
  // session valid
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example refers to validating a user's session.
 
// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$member = new Member();

// Authenticate a user and get session GUID
$recordParameters = Member::fromArray(array(
    'strEmail'    => '[email protected]',
    'strPassword' => 'ddddddddddd',
    'format'      => 'json',
));

$response = $member->memberAuthentication($recordParameters);

assert(!is_null($response), "Can't authenticate a user");
assert(isset($response['session_guid']), "Can't authenticate a user");
assert(isset($response['member_id']), "Can't authenticate a user");

$sessionGuid = $response['session_guid'];
$memberID = $response['member_id'];

echo "Member ID -> $memberID <br> Session GUID -> $sessionGuid <br>";

// Validate the session
$params = Member::fromArray(array(
    'session_guid' => $sessionGuid,
    'member_id'    => $memberID,
    'format'       => 'json',
));

$response = $member->validateSession($params);

var_dump($response);
unit ValidateSessionUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TValidateSession = class(TBaseExample)
  public
    procedure Execute(SessionGuid: String; MemberId: integer);
  end;

implementation
uses UserUnit;
procedure TValidateSession.Execute(SessionGuid: String; MemberId: integer);
var
  ErrorString: String;
  IsSessionValid: boolean;
  IsSessionValidStr: String;
begin
  IsSessionValid := Route4MeManager.User.IsSessionValid(
    SessionGuid, MemberId, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    if IsSessionValid then
      IsSessionValidStr := 'is valid'
    else
      IsSessionValidStr := 'is not valid';

    WriteLn(Format('ValidateSession executed successfully, session %s',
      [IsSessionValidStr]));
    WriteLn('');
  end
  else
    WriteLn(Format('ValidateSession error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    const char* session_id="4552222222";
    const char* member_id="787544566";

    int ret = route.validate_session(session_id, member_id);
    if (ret == 0)
      cout << "Session validated:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
      cout << "Validation failed:" << route.get_err_code() << ": " << route.get_err_msg() << endl;

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    const char session_id[] = "4552222222";
    const char member_id[] = "787544566";
    const char format[] = "json";
    init(key, 1);

    if (!validate_session(session_id, member_id, format))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/datafeed/session/validate_session.php?api_key=...&session_guid=...&member_id=...&$frmt=...

You can expect this API response:

{"authenticated":true,"member_id":1}

Register an Account

Registers a new Route4Me account.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
plan string Account plan GET
strIndustry string The industry where the user is currently associated. POST
strFirstName string First name POST
strLastName string Last name POST
strEmail string User’s email POST
format string Response format POST
chkTerms integer If equal to 1, the user agrees on the registration terms. POST
device_type string Device type POST
strPassword_1 string User’s password POST
strPassword_2 string Password confirmation POST
<job id="NewAccountRegistration">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/actions/register_action.php"
      apikey="11111111111111111111111111111111"
      
      ' Note: example requires additional testing
      
      url=url&"?api_key="&apikey
      
      jFile="new_account_registration_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/actions/register_action.php
SET apikey=11111111111111111111111111111111
SET plan=enterprise_plan

:: The example demonstrates the registration of a new Route4Me account.

ECHO ON

curl -o file1.txt -k -X POST -H "Content-Type: multipart/form-data;" -F "strIndustry=Gifting" -F "strFirstName=Olman" -F "strLastName=Oland" -F "[email protected]" -F "format=json" -F "chkTerms=1" -F "device_type=web" -F "strPassword_1=111111" -F "strPassword_2=111111" "%url%?plan=%plan%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/register_action.php
apikey=11111111111111111111111111111111
plan=enterprise_plan

# The example demonstrates the registration of a new Route4Me account.

curl -o file1.txt -k -X POST -H "Content-Type: multipart/form-data;" -F "strIndustry=Gifting" -F "strFirstName=Olman" -F "strLastName=Oland" -F "[email protected]" -F "format=json" -F "chkTerms=1" -F "device_type=web" -F "strPassword_1=111111" -F "strPassword_2=111111" "$url?plan=$plan"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// User Registration
        /// </summary>
        public void UserRegistration()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberParameters @params = new MemberParameters
            {
                StrEmail = "[email protected]",
                StrPassword_1 = "11111111",
                StrPassword_2 = "11111111",
                StrFirstName = "Olman",
                StrLastName = "Progman",
                StrIndustry = "Transportation",
                Format = "json",
                ChkTerms = 1,
                DeviceType = "web",
                Plan = "free",
                MemberType = 5
            };
            // Run the query
            string errorString = "";
            MemberResponse result = route4Me.UserRegistration(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("UserRegistration executed successfully");
                Console.WriteLine("status: " + result.Status);
                Console.WriteLine("api_key: " + result.ApiKey);
                Console.WriteLine("member_id: " + result.MemberId);
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("UserRegistration error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' User Registration
        ''' </summary>
        Public Sub UserRegistration()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberParameters = New MemberParameters() With { _
                .StrEmail = "[email protected]", _
                .StrPassword_1 = "11111111", _
                .StrPassword_2 = "11111111", _
                .StrFirstName = "Olman", _
                .StrLastName = "Progman", _
                .StrIndustry = "Transportation", _
                .Format = "json", _
                .ChkTerms = 1, _
                .Plan = "free" _
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberResponse = route4Me.UserRegistration(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("UserRegistration executed successfully")
                Console.WriteLine("status: " & result.Status)
                Console.WriteLine("api_key: " & result.ApiKey)
                Console.WriteLine("member_id: " & result.MemberId)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("UserRegistration error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    members = route4me.members
    data = {"email_address": "[email protected]",
            "first_name": "Jhon",
            "last_name": "Route4Me",
            "check_terms": "1",
            "industry": "Python SDK",
            "device_type": "web",
            "plan": "enterprise_plan",
            "password_1": "ultrasecret",
            "password_2": "ultrasecret",
            "format": "json", }
    response = members.register(**data)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print response

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
    account, err := service.Register(&users.MemberBase{
        FirstName:            "John",
        LastName:             "Example",
        Email:                "[email protected]",
        Type:                 users.SubAccountDispatcher,
        Password:             "123",
        HideRouteAddresses:   true,
        HideVisitedAddresses: true,
    })
    if err != nil {
        // error making request
        return
    }
    // do something with the account
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

// The example demonstrates the registration of a new Route4Me account.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$registrParameters = Member::fromArray(array(
    'strEmail'      => '[email protected]',
    'strPassword_1' => 'ooo111111',
    'strPassword_2' => 'ooo111111',
    'strFirstName'  => 'Driver',
    'strLastName'   => 'Driverson',
    'format'        => 'json',
    'strIndustry'   => 'Gifting',
    'chkTerms'      => 1,
    'device_type'   => 'web',
    'plan'          => 'free'
));

$member = new Member();

$response = $member->newAccountRegistration($registrParameters);

Route4Me::simplePrint($response);
unit RegisterAccountUnit;

interface

uses SysUtils, BaseExampleUnit, EnumsUnit;

type
  TRegisterAccount = class(TBaseExample)
  public
    procedure Execute(Plan, Industry, FirstName, LastName, Email: String;
      Terms: boolean; DeviceType: TDeviceType;
      Password, PasswordConfirmation: String);
  end;

implementation

uses NullableBasicTypesUnit;

procedure TRegisterAccount.Execute(

  Plan, Industry, FirstName, LastName, Email: String;

  Terms: boolean; DeviceType: TDeviceType;
  Password, PasswordConfirmation: String);

var
  ErrorString: String;
  MemberId: NullableInteger;
begin
  MemberId := Route4MeManager.User.RegisterAccount(Plan, Industry, FirstName, LastName,
    Email, Terms, DeviceType, Password, PasswordConfirmation, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    WriteLn(Format('Account registered successfully, MemberId = %d', [MemberId.Value]));
    WriteLn('');
  end
  else
    WriteLn(Format('RegisterAccount error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("member_create_v4_data.json");
    if(!inf.is_open())
    {
        cout << "Can't find data file" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    int ret = 0;

    Json::Value member;
    inf >> member;

    if(route.modify_member(member, CRoute4Me::REQ_POST) == 0)
    {
        cout << "User registered:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Failed to register " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/actions/register_action.php?api_key=...

You can expect this API response:

{
    "status": true,
    "session_id": "75888c43f8525bab7f8bbf6f4f85b0ec",
    "session_guid": "75888c43f8525bab7f8bbf6f4f85b0ec",
    "member_id": 315948,
    "api_key": "0216bfd6245454545f2756a9556d98a8",
    "account_type_id": 24,
    "account_type_alias": 0,
    "max_stops_per_route": 10000,
    "max_routes": 10,
    "routes_planned": 0
}

Get User’s Details

Get a user using the member_id parameter.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
member_id integer Member ID GET
<job id="Member Get Single Subuser">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' View an existing single sub-user in a Member's account.
      
      url="https://api.route4me.com/api.v4/user.php"
      apikey="11111111111111111111111111111111"
      member_id=45844
      
      url=url&"?api_key="&apikey
      url=url&"&member_id="&member_id
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF
SET url=https://api.route4me.com/api.v4/user.php
SET apikey=11111111111111111111111111111111
SET member_id=45844

:: View an existing single sub-user in a Member's account.

ECHO ON

curl -o file1.txt -g -X GET -k "%url%?api_key=%apikey%&member_id=%member_id%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/user.php
apikey=11111111111111111111111111111111
member_id=45844

# View an existing single sub-user in a Member's account.

curl -o file1.txt -g -X GET -k "$url?api_key=$apikey&member_id=$member_id"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get User By ID
        /// </summary>
        public void GetUserById()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberParametersV4 @params = new MemberParametersV4 { member_id = 45844 };

            // Run the query
            string errorString = "";
            MemberResponseV4 result = route4Me.GetUserById(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("GetUserById executed successfully");
                Console.WriteLine("User: " + result.member_first_name + " " + result.member_last_name);
                Console.WriteLine("member_id: " + result.member_id);
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("GetUserById error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get User By ID
        ''' </summary>
        Public Sub GetUserById()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberParametersV4 = New MemberParametersV4() With { _
                .member_id = 45844 _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberResponseV4 = route4Me.GetUserById(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("GetUserById executed successfully")
                Console.WriteLine("User: " & result.member_first_name & " " & result.member_last_name)
                Console.WriteLine("member_id: " & result.member_id)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("GetUserById error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
  
  users, err := service.GetUserByID(id)
  if err != nil {
    // could not fetch a user
    return
  }
  // do something with the user, it's *Member
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates getting a user with its details.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$member = new Member();

// Get users list
$users = $member->getUsers();

assert(!is_null($users), "Can't retrieve the list of users");
assert(sizeof($users)==2, "Can't retrieve the list of users");
assert(isset($users['results']), "Can't retrieve the list of users");
assert(isset($users['total']), "Can't retrieve the list of users");

$randIndex = rand(0, $users["total"] - 1);

$randomUserID = $users['results'][$randIndex]["member_id"];

echo "Random user ID -> $randomUserID <br><br>";
unit GetUserDetailsUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetUserDetails = class(TBaseExample)
  public
    procedure Execute(MemberId: integer);
  end;

implementation

uses UserUnit;

procedure TGetUserDetails.Execute(MemberId: integer);

var
  ErrorString: String;
  User: TUser;
begin
  User := Route4MeManager.User.Get(MemberId, ErrorString);
  try
    WriteLn('');

    if (User <> nil) then
    begin
      WriteLn('GetUserDetails executed successfully');
      WriteLn('');
    end
    else
      WriteLn(Format('GetUserDetails error: "%s"', [ErrorString]));
  finally
    FreeAndNil(User);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/user.php?api_key=...&member_id=...

You can expect this API response:

{
  "member_first_name": "Clint",
  "member_id": "45844",
  "member_last_name": "Bbbbbbbb",
  "member_email": "[email protected]",
  "preferred_units": "MI",
  "preferred_language": "en",
  "timezone": "America\/New_York",
  "member_zipcode": null,
  "OWNER_MEMBER_ID": "1",
  "member_type": "SUB_ACCOUNT_DRIVER",
  "member_phone": "",
  "user_reg_state_id": "4",
  "user_reg_country_id": "223",
  "date_of_birth": "1980-01-01",
  "HIDE_ROUTED_ADDRESSES": "TRUE",
  "HIDE_VISITED_ADDRESSES": "TRUE",
  "HIDE_NONFUTURE_ROUTES": "TRUE",
  "READONLY_USER": "TRUE",
  "SHOW_ALL_DRIVERS": "FALSE",
  "SHOW_ALL_VEHICLES": "FALSE",
  "member_picture": null
}

Create a User

Creates a new user.

See the Member JSON Schema in our GitHub repository.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
HIDE_ROUTED_ADDRESSES boolean If true, hide the routed addresses. POST
member_phone string User’s phone number POST
member_zipcode string The 5-7 digit ZIP Code POST
route_count integer Route count POST
member_email string Member’s email address POST
HIDE_VISITED_ADDRESSES boolean If true, hide the visited addresses. POST
READONLY_USER boolean If true, the user is read-only. POST
member_type string Type of member POST
date_of_birth string Date of birth POST
member_first_name string First name POST
member_password string Member’s password POST
HIDE_NONFUTURE_ROUTES boolean If true, hide non-future routes. POST
member_last_name string Last name POST
SHOW_ALL_VEHICLES boolean If true, show all vehicles. POST
SHOW_ALL_DRIVERS boolean If true, show all drivers. POST
<job id="Create a Member V4">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example refers to the process of creating a sub-user in a member's account.
      
      url="https://api.route4me.com/api.v4/user.php"
      apikey="11111111111111111111111111111111"
      
      jFile="member_create_v4_data.json"
      
      url=url&"?api_key="&apikey
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://route4me.com/api.v4/user.php
SET apikey=11111111111111111111111111111111
SET [email protected]

:: The example refers to the process of creating a sub-user in a member's account.

ECHO ON

curl -o file1.txt -g -H "Content-Type: application/json" -X POST -k -d "@member_create_v4_data.json" "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/user.php
apikey=11111111111111111111111111111111

# The example refers to the process of creating a sub-user in a member's account.

curl -o file1.txt -g -H "Content-Type: application/json" -X POST -d "@member_create_v4_data.json" -k "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// User Registration (v4)
        /// </summary>
        public void CreateUser()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberParametersV4 @params = new MemberParametersV4
            {
                HIDE_ROUTED_ADDRESSES = false,
                member_phone = "571-259-5939",
                member_zipcode = "22102",
                member_email = "[email protected]",
                HIDE_VISITED_ADDRESSES = false,
                READONLY_USER = false,
                member_type = "SUB_ACCOUNT_DISPATCHER",
                date_of_birth = "2010",
                member_first_name = "Clay",
                member_password = "123456",
                HIDE_NONFUTURE_ROUTES = false,
                member_last_name = "Abraham",
                SHOW_ALL_VEHICLES = false,
                SHOW_ALL_DRIVERS = false
            };

            // Run the query
      string errorString = "";
      MemberResponseV4 result = route4Me.CreateUser(@params, out errorString);

      Console.WriteLine("");

      if (result != null)
      {
        Console.WriteLine("UserRegistration executed successfully");
        Console.WriteLine("User: " + result.member_first_name + " " + result.member_last_name);
        Console.WriteLine("member_id: " + result.member_id);
        Console.WriteLine("---------------------------");
      }
      else
      {
        Console.WriteLine("UserRegistration error: {0}", errorString);
      }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' User Registration (v4)
        ''' </summary>
        Public Sub CreateUser()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberParametersV4 = New MemberParametersV4() With { _
                .HIDE_ROUTED_ADDRESSES = "FALSE", _
                .member_phone = "571-259-5939", _
                .member_zipcode = "22102", _
                .member_email = "[email protected]", _
                .HIDE_VISITED_ADDRESSES = "FALSE", _
                .READONLY_USER = "FALSE", _
                .member_type = "SUB_ACCOUNT_DISPATCHER", _
                .date_of_birth = "2010", _
                .member_first_name = "Clay", _
                .member_password = "123456", _
                .HIDE_NONFUTURE_ROUTES = "FALSE", _
                .member_last_name = "Abraham", _
                .SHOW_ALL_VEHICLES = "FALSE", _
                .SHOW_ALL_DRIVERS = "FALSE" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberResponseV4 = route4Me.CreateUser(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("UserRegistration executed successfully")
                Console.WriteLine("User: " & result.member_first_name & " " & result.member_last_name)
                Console.WriteLine("member_id: " & result.member_id)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("UserRegistration error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
    success, err := service.Create(&Account{
        Industry:  "Gifting",
        FirstName: "Olman",
        LastName:  "Oland",
        Email:     "[email protected]",
        AcceptTOS: true,
        Password:  "111111",
        Plan:      "enterprise_plan",
    })
    if err != nil {
        // error making request
        return
    }
    if !success {
        // error occured, while creating an account
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

// The example demonstrates the creation of a new user.

// NOTE: For this example to work, please replace the demo API key `11111...` with your Route4Me API key.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$params = Member::fromArray(array (
    "HIDE_ROUTED_ADDRESSES" => "FALSE",
    "member_phone"          => "571-259-5939",
    "member_zipcode"        => "22102",
    "route_count"           => null,
    "member_email"          => "[email protected]",
    "HIDE_VISITED_ADDRESSES"=> "FALSE",
    "READONLY_USER"         => "FALSE",
    "member_type"           => "SUB_ACCOUNT_DRIVER",
    "date_of_birth"         => "1994-10-01",
    "member_first_name"     => "Clay",
    "member_password"       => "123456",
    "HIDE_NONFUTURE_ROUTES" => "FALSE",
    "member_last_name"      => "Abraham",
    "SHOW_ALL_VEHICLES"     => "FALSE",
    "SHOW_ALL_DRIVERS"      => "FALSE"
));

$member = new Member();

$response = $member->createMember($params);

Route4Me::simplePrint($response);
unit AddNewUserUnit;

interface

uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit, UserParametersUnit;

type
  TAddNewUser = class(TBaseExample)
  public
    function Execute(Parameters: TUserParameters): NullableInteger;
  end;

implementation

function TAddNewUser.Execute(Parameters: TUserParameters): NullableInteger;

var
  ErrorString: String;
begin
  Result := Route4MeManager.User.AddNewUser(Parameters, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    WriteLn(Format('New user added successfully, MemberId = %d', [Result.Value]));
    WriteLn('');
  end
  else
    WriteLn(Format('AddNewUser error: "%s"', [ErrorString]));
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/user.php?api_key=...

You can expect this API response:

{
    "HIDE_NONFUTURE_ROUTES": "FALSE",
    "HIDE_ROUTED_ADDRESSES": "FALSE",
    "HIDE_VISITED_ADDRESSES": "FALSE",
    "member_id": "147824",
    "OWNER_MEMBER_ID": "1116",
    "READONLY_USER": "FALSE",
    "SHOW_ALL_DRIVERS": "FALSE",
    "SHOW_ALL_VEHICLES": "TRUE",
    "date_of_birth": "2010-00-00",
    "member_email": "[email protected]",
    "member_first_name": "Clay",
    "member_last_name": "Abraham",
    "member_phone": "571-259-5939",
    "member_picture": null,
    "member_type": "SUB_ACCOUNT_DISPATCHER",
    "member_zipcode": "22102",
    "preferred_language": "en",
    "preferred_units": null,
    "timezone": "America/New_York",
    "user_reg_country_id": null,
    "user_reg_state_id": null
}

Update a User

Updates an existing user.

See the Member JSON Schema in our GitHub repository.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
member_id integer Member ID POST
HIDE_ROUTED_ADDRESSES boolean If true, hide the routed addresses. POST
member_phone string User’s phone number POST
member_zipcode string The 5-7 digit ZIP Code POST
route_count integer Route count POST
member_email string Member’s email address POST
HIDE_VISITED_ADDRESSES boolean If true, hide the visited addresses. POST
READONLY_USER boolean If true, the user is read-only. POST
member_type string Type of member POST
date_of_birth string Date of birth POST
member_first_name string First name POST
member_password string Member’s password POST
HIDE_NONFUTURE_ROUTES boolean If true, hide non-future routes. POST
member_last_name string Last name POST
SHOW_ALL_VEHICLES boolean If true, show all vehicles. POST
SHOW_ALL_DRIVERS boolean If true, show all drivers. POST
<job id="Update Member's Account">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of updating an existing user account.
      
      url="https://api.route4me.com/api.v4/user.php"
      apikey="11111111111111111111111111111111"
      
      jFile="member_edit_data.json"
      
      url=url&"?api_key="&apikey
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/user.php
SET apikey=11111111111111111111111111111111
SET member_id=220461

:: The example demonstrates the process of updating an existing user account.

ECHO ON

curl -o file1.txt -g -X PUT -d "@member_edit_data.json" -k "%url%?api_key=%apikey%&member_id=%member_id%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/user.php
apikey=11111111111111111111111111111111

# The example demonstrates the process of updating an existing user account.

curl -o file1.txt -g -X PUT -d "@member_edit_data.json" -k "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Update a User
        /// </summary>
        public void UpdateUser()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberParametersV4 @params = new MemberParametersV4
            {
                member_id = 220461,
                member_phone = "571-259-5939"
            };

            // Run the query
            string errorString = "";
            MemberResponseV4 result = route4Me.UserUpdate(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("UpdateUser executed successfully");
                Console.WriteLine("status: " + result.member_first_name + " " + result.member_last_name);
                Console.WriteLine("member_id: " + result.member_id);
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("UpdateUser error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Update a User
        ''' </summary>
        Public Sub UpdateUser()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberParametersV4 = New MemberParametersV4() With { _
                .member_id = 220461, _
                .member_phone = "571-259-5939" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberResponseV4 = route4Me.UserUpdate(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("UpdateUser executed successfully")
                Console.WriteLine("status: " & result.member_first_name & " " & result.member_last_name)
                Console.WriteLine("member_id: " & result.member_id)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("UpdateUser error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
  
  // fetch users to edit later
  users, err := service.GetSubusers()
  if err != nil {
    // could not get users
  }
  // get the last one
  user := users[len(users)-1]
  // change the phone number
  user.Phone = "123452"
  // call "edit"
  member, err := service.Edit(user)
  if err != nil {
    // editing failed
  }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the updating of a user.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$member = new Member();

// Get a random member ID from a member with a type of SUB_ACCOUNT_DRIVER.
$randomMemberID = $member->getRandomMemberByType('SUB_ACCOUNT_DRIVER');

assert(!is_null($randomMemberID), "There is no member of the type SUB_ACCOUNT_DRIVER in the user's account");

// Update member
$params = Member::fromArray(array (
    "member_id"    => $randomMemberID,
    "member_phone" => "555-777-888"
));

$response = $member->updateMember($params);

Route4Me::simplePrint($response);
unit UpdateUserUnit;

interface

uses SysUtils, BaseExampleUnit, UserParametersUnit;

type
  TUpdateUser = class(TBaseExample)
  public
    procedure Execute(Parameters: TUserParameters);
  end;

implementation

procedure TUpdateUser.Execute(Parameters: TUserParameters);

var
  ErrorString: String;
begin
  Route4MeManager.User.Update(Parameters, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    WriteLn('User updated successfully');
    WriteLn('');
  end
  else
    WriteLn(Format('UpdateUser error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("member_edit_data.json");
    if(!inf.is_open())
    {
        cout << "Can't find data file" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    int ret = 0;

    Json::Value member;
    inf >> member;

    if(route.modify_member(member, CRoute4Me::REQ_PUT) == 0)
    {
        cout << "User edited:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Failed to modify member data " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/user.php?api_key=...

You can expect this API response:

{
  "member_first_name": "Dumbo",
  "member_id": "220461",
  "member_last_name": "The Elephant",
  "member_email": "[email protected]",
  "preferred_units": "MI",
  "preferred_language": "en",
  "timezone": "America\/New_York",
  "member_zipcode": null,
  "OWNER_MEMBER_ID": "38392",
  "member_type": "SUB_ACCOUNT_ADMIN",
  "member_phone": "555-777-888",
  "user_reg_state_id": "2",
  "user_reg_country_id": "223",
  "date_of_birth": "1980-01-01",
  "HIDE_ROUTED_ADDRESSES": "FALSE",
  "HIDE_VISITED_ADDRESSES": "FALSE",
  "HIDE_NONFUTURE_ROUTES": "FALSE",
  "READONLY_USER": "FALSE",
  "SHOW_ALL_DRIVERS": "FALSE",
  "SHOW_ALL_VEHICLES": "TRUE",
  "member_picture": null
}

Add Custom Data to a User

Add/edit custom data to a user.

See the Member JSON Schema in our GitHub repository.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
member_id integer Member ID POST
HIDE_ROUTED_ADDRESSES boolean If true, hide the routed addresses. POST
member_phone string User’s phone number POST
member_zipcode string The 5-7 digit ZIP Code POST
route_count integer Route count POST
member_email string Member’s email address POST
HIDE_VISITED_ADDRESSES boolean If true, hide the visited addresses. POST
READONLY_USER boolean If true, the user is read-only. POST
member_type string Type of member POST
date_of_birth string Date of birth POST
member_first_name string First name POST
member_password string Member’s password POST
HIDE_NONFUTURE_ROUTES boolean If true, hide non-future routes. POST
member_last_name string Last name POST
SHOW_ALL_VEHICLES boolean If true, show all vehicles. POST
SHOW_ALL_DRIVERS boolean If true, show all drivers. POST
custom_data array An array of custom key value pairs. POST
<job id="Edit Member's Account">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			
			WScript.Echo "Please, press OK and wait..."
			
			' Edit/Add custom data of/to a member's account.
			
			url="https://api.route4me.com/api.v4/user.php"
			apikey="11111111111111111111111111111111"
			
			jFile="member_edit_custom_data_data.json"
			
			url=url&"?api_key="&apikey
			
			Set r4m=New Route4Me
			
			r4m.HttpPutRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/user.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of adding/editing custom data to/of an existing user account.

ECHO ON

curl -o member_edit_custom_data_RESPONSE.json -g -X PUT -d "@member_edit_custom_data_data.json" -k "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/user.php
apikey=11111111111111111111111111111111

# The example refers to the process of adding/editing custom data to/of an existing user account.

curl -o member_edit_custom_data_RESPONSE.json -g -X PUT -d "@member_edit_custom_data_data.json" -k "$url?api_key=$apikey"

echo "Finished..."

sleep 15
public void AddEditCustomDataToUserTest()
{
	if (skip == "yes") return;

	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	MemberParametersV4 @params = new MemberParametersV4
	{
		HIDE_ROUTED_ADDRESSES = "FALSE",
		member_phone = "571-259-5939",
		member_zipcode = "22102",
		member_email = "regression.autotests+" + DateTime.Now.ToString("yyyyMMddHHmmss") + "@gmail.com",
		HIDE_VISITED_ADDRESSES = "FALSE",
		READONLY_USER = "FALSE",
		member_type = "SUB_ACCOUNT_DISPATCHER",
		date_of_birth = "2010",
		member_first_name = "Clay",
		member_password = "123456",
		HIDE_NONFUTURE_ROUTES = "FALSE",
		member_last_name = "Abraham",
		SHOW_ALL_VEHICLES = "FALSE",
		SHOW_ALL_DRIVERS = "FALSE"
	};

	// Run the query
	string errorString = "";
	var result = route4Me.CreateUser(@params, out errorString);

	// For successful testing of creating a user, you should provide a valid email address. Otherwise, you'll get the error "Email is used in system".
	string rightResponse = result != null ? "ok" : ((errorString == "Email is used in system" || errorString == "Registration: The email address is missing or invalid.") ? "ok" : "");

	Assert.IsTrue(rightResponse == "ok", "CreateUserTest failed... " + errorString);

	lsMembers.Add(Convert.ToInt32(result.member_id));

	MemberParametersV4 @customParams = new MemberParametersV4
	{
		member_id = result.member_id != null ? Convert.ToInt32(result.member_id) : -1,
		custom_data = new Dictionary<string,string>() {{"Custom Key 2", "Custom Value 2"}}
	};

	errorString = "";
	MemberResponseV4 result2 = route4Me.UserUpdate(@customParams, out errorString);

	Assert.IsTrue(result2!=null, "UpdateUserTest failed... " + errorString);

	Dictionary<string, string> customData = result2.custom_data;

	Assert.IsTrue(customData.Keys.ElementAt(0) == "Custom Key 2", "Custom Key is not 'Custom Key 2'");

	Assert.IsTrue(customData["Custom Key 2"] == "Custom Value 2", "Custom Value is not 'Custom Value 2'");
}
Public Sub AddEditCustomDataToUserTest()
	If skip = "yes" Then Return

	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)

	Dim params As MemberParametersV4 = New MemberParametersV4 With {
		.HIDE_ROUTED_ADDRESSES = "FALSE",
		.member_phone = "571-259-5939",
		.member_zipcode = "22102",
		.member_email = "regression.autotests+" & DateTime.Now.ToString("yyyyMMddHHmmss") & "@gmail.com",
		.HIDE_VISITED_ADDRESSES = "FALSE",
		.READONLY_USER = "FALSE",
		.member_type = "SUB_ACCOUNT_DISPATCHER",
		.date_of_birth = "2010",
		.member_first_name = "Clay",
		.member_password = "123456",
		.HIDE_NONFUTURE_ROUTES = "FALSE",
		.member_last_name = "Abraham",
		.SHOW_ALL_VEHICLES = "FALSE",
		.SHOW_ALL_DRIVERS = "FALSE"
	}

	Dim errorString As String = ""
	Dim result = route4Me.CreateUser(params, errorString)
	Dim rightResponse As String = If(result IsNot Nothing, "ok", (If((errorString = "Email is used in system" OrElse errorString = "Registration: The email address is missing or invalid."), "ok", "")))

	Assert.IsTrue(rightResponse = "ok", "CreateUserTest failed... " & errorString)

	lsMembers.Add(Convert.ToInt32(result.member_id))

	Dim customParams As MemberParametersV4 = New MemberParametersV4 With {
	.member_id = If(result.member_id IsNot Nothing, Convert.ToInt32(result.member_id), -1),
	.custom_data = New Dictionary(Of String, String)() From {
		{"Custom Key 2", "Custom Value 2"}
		}
	}

	errorString = ""
	Dim result2 As MemberResponseV4 = route4Me.UserUpdate(customParams, errorString)

	Assert.IsTrue(result2 IsNot Nothing, "UpdateUserTest failed... " & errorString)

	Dim customData As Dictionary(Of String, String) = result2.custom_data

	Assert.IsTrue(customData.Keys.ElementAt(0) = "Custom Key 2", "Custom Key is not 'Custom Key 2'")
	Assert.IsTrue(customData("Custom Key 2") = "Custom Value 2", "Custom Value is not 'Custom Value 2'")
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.

<?php
namespace Route4Me;
$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example refers to the process of adding/editing custom data to/of an existing user account.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');
$member = new Member();

// Get random member ID of the member type SUB_ACCOUNT_DRIVER
$randomMemberID = $member->getRandomMemberByType('SUB_ACCOUNT_DRIVER');
assert(!is_null($randomMemberID), "There is no member of the type SUB_ACCOUNT_DRIVER in the user's account");

// Update member
$params = Member::fromArray(array (
    "member_id"    => $randomMemberID,
    "custom_data" => array("Custom Key 2" => "Custom Value 2")
));
$response = $member->updateMember($params);
Route4Me::simplePrint($response["custom_data"]);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/address.php?api_key=...&route_id=...&route_destination_id=...

You can expect this API response:

{
	"member_first_name": "Medvedson",
	"member_id": "2",
	"member_last_name": "David",
	"member_email": "[email protected]",
	"preferred_units": "MI",
	"preferred_language": "en",
	"timezone": "America/New_York",
	"member_zipcode": null,
	"OWNER_MEMBER_ID": "1",
	"member_type": "SUB_ACCOUNT_DRIVER",
	"member_phone": "+333333333333",
	"user_reg_state_id": "2",
	"user_reg_country_id": "223",
	"date_of_birth": "1948-08-08",
	"HIDE_ROUTED_ADDRESSES": "FALSE",
	"HIDE_VISITED_ADDRESSES": "FALSE",
	"HIDE_NONFUTURE_ROUTES": "FALSE",
	"READONLY_USER": "TRUE",
	"SHOW_ALL_DRIVERS": "FALSE",
	"SHOW_ALL_VEHICLES": "FALSE",
	"member_picture": null,
	"api_key": "11111111111111111111111111111111",
	"custom_data": {
		"Custom Key 2": "Custom Value 2"
	}
}

Remove a User

Removes an existing user from a member’s account.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
member_id integer Member ID POST
<job id="Remove a Sub-user">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of removing an existing sub-user from a member's account.
      
      url="https://api.route4me.com/api.v4/user.php"
      apikey="11111111111111111111111111111111"
      
      jFile="member_delete_data.json"
      
      url=url&"?api_key="&apikey
      
      Set r4m=New Route4Me
      
      r4m.HttpDeleteRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF
SET url=https://api.route4me.com/api.v4/user.php
SET apikey=11111111111111111111111111111111
SET member_id=147824

:: The example demonstrates the process of removing an existing sub-user from a member's account.

ECHO ON

curl -o file1.txt -g -X DELETE -d "@member_delete_data.json" -k "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/user.php
apikey=11111111111111111111111111111111

# The example demonstrates the process of removing an existing sub-user from a member's account.

curl -o file1.txt -g -X DELETE -d "@member_delete_data.json" -k "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Remove User
        /// </summary>
        public void DeleteUser()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberParametersV4 @params = new MemberParametersV4 { member_id = 147824 };

            // Run the query
            string errorString = "";
            bool result = route4Me.UserDelete(@params, out errorString);

            Console.WriteLine("");

            if (result)
            {
                Console.WriteLine("DeleteUser executed successfully");
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("DeleteUser error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Remove User
        ''' </summary>
        Public Sub DeleteUser()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberParametersV4 = New MemberParametersV4() With { _
                .member_id = 147824 _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim result As Boolean = route4Me.UserDelete(params, errorString)

            Console.WriteLine("")

            If result Then
                Console.WriteLine("DeleteUser executed successfully")
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("DeleteUser error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}

    users, err := service.GetSubusers()
    if err != nil {
        // could not get users
    }
    // get the last one
    user := users[len(users)-1]

    resp, err := service.Delete(user.ID)
    if err != nil {
        // handle error
    }
    if !resp.Status {
        // something undefined went wrong
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the process of removing an existing sub-user from a member's account.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$member = new Member();

// Get a random member ID from a member with a type of SUB_ACCOUNT_DRIVER.
$randomMemberID = $member->getRandomMemberByType('SUB_ACCOUNT_DRIVER');

assert(!is_null($randomMemberID), "There is no member of the type SUB_ACCOUNT_DRIVER in the user's account");

// Delete member from the user's account
$params = Member::fromArray(array (
    "member_id"  => $randomMemberID
));

$response = $member->deleteMember($params);

Route4Me::simplePrint($response);
unit RemoveUserUnit;

interface

uses SysUtils, BaseExampleUnit, UserParametersUnit;

type
  TRemoveUser = class(TBaseExample)
  public
    procedure Execute(MemberId: integer);
  end;

implementation

procedure TRemoveUser.Execute(MemberId: integer);

var
  ErrorString: String;
begin
  Route4MeManager.User.Remove(MemberId, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    WriteLn('User removed successfully');
    WriteLn('');
  end
  else
    WriteLn(Format('RemoveUser error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("member_delete_data.json");
    if(!inf.is_open())
    {
        cout << "Can't find data file" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    int ret = 0;

    Json::Value member;
    inf >> member;

    if(route.modify_member(member, CRoute4Me::REQ_DELETE) == 0)
    {
        cout << "User data deleted:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Failed to delete user data " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api.v4/user.php?api_key=...

You can expect this API response:

{
    "status": true
}

Add a New Configuration Key

Adds a new configuration key to a member’s account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
config_key string Configuration key POST
config_value string Configuration value POST
is_hidden_value boolean If true, the value is hidden. POST
can_unhide_value boolean If true, the value can be visible. POST
<job id="New Account Configuration Key">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of creating a new account configuration key.
      
      url="https://route4me.com/api.v4/configuration-settings.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="add_new_account_config_value_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://route4me.com/api.v4/configuration-settings.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of creating a new account configuration key.

curl -o file1.txt -k -g -X POST -H "Content-Type: application/json;" -d "@add_new_account_config_value_data2.json" "%url%?api_key=%apikey%" 

timeout /t 30
@ECHO OFF
SET url=https://route4me.com/api.v4/configuration-settings.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of creating a new account configuration key.

curl -o file1.txt -k -g -X POST -H "Content-Type: application/json;" -d "@add_new_account_config_value_data2.json" "%url%?api_key=%apikey%" 

timeout /t 30
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Create New Configuration Key
        /// </summary>
        public void AddNewConfigurationKey()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberConfigurationParameters @params = new MemberConfigurationParameters
            {
                config_key = "destination_icon_uri",
                config_value = "value"
            };

            // Run the query
            string errorString = "";
            MemberConfigurationResponse result = route4Me.CreateNewConfigurationKey(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("AddNewConfigurationKey executed successfully");
                Console.WriteLine("Result: " + result.result);
                Console.WriteLine("Affected: " + result.affected);
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("AddNewConfigurationKey error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Create New Configuration Key
        ''' </summary>
        Public Sub AddNewConfigurationKey()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberConfigurationParameters = New MemberConfigurationParameters() With { _
                .config_key = "destination_icon_uri", _
                .config_value = "value" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberConfigurationResponse = route4Me.CreateNewConfigurationKey(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("AddNewConfigurationKey executed successfully")
                Console.WriteLine("Result: " & result.result)
                Console.WriteLine("Affected: " & result.affected)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("UserRegistration error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
    success, err := service.AddConfigEntry("config-test-key-go", "config-test-value-go")
    if err != nil {
        // request unsuccessful
        return
    }
    if !success {
        // couldn't add entry
        return
    }
    // everything went as expected
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

// The example demonstrates the process of creating a new account configuration key.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$params = Member::fromArray(array (
    "config_key"   => "destination_icon_uri",
    "config_value" => "value"
));

$member = new Member();

$response = $member->newMemberConfigKey($params);

Route4Me::simplePrint($response);
unit AddConfigValueUnit;

interface

uses SysUtils, BaseExampleUnit, EnumsUnit;

type
  TAddConfigValue = class(TBaseExample)
  public
    function Execute(Key, Value: String): boolean;
  end;

implementation
function TAddConfigValue.Execute(Key, Value: String): boolean;
var
  ErrorString: String;
begin
  Result := Route4MeManager.User.AddConfigValue(Key, Value, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    if Result then
      WriteLn('AddConfigValue executed successfully')
    else
      WriteLn('AddConfigValue error');
    WriteLn('');
  end
  else
    WriteLn(Format('AddConfigValue error: "%s"', [ErrorString]));
end;

end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("add_account_data.json");
    if(!inf.is_open())
    {
        cout << "Can't find data file" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    int ret = 0;

    Json::Value account;
    inf >> account;

    if(route.modify_config(account, CRoute4Me::REQ_POST) == 0)
    {
        cout << "Config added:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Failed to add config " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char file_name[] = "add_account_data.json";
    char* data = NULL;
    struct MapPoint point = {0,1};

    if (deserialize(file_name, &data))
    {
        printf("File add_account_data.json not found!\n");
        return -1;
    }

    init(key, 1);

    if (!modify_config(data, REQ_POST))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    if (data)
    {
        free(data);
    }

    cleanUp();
  return 0;
}


HTTP Request

POST
/api.v4/configuration-settings.php?api_key=...

You can expect this API response:

{
  "result":"OK",
  "affected":1
}

Add an Array of Configuration Keys

Adds an array of configuration keys to a member’s account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
payload string A JSON object containing an array of configuration keys. POST
<job id="Add Account Configuration Keys Array">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			
			WScript.Echo "Please, press OK and wait..."
			
			' Example refers to the process of adding array of the new account configuration keys to the user's account.
			
			url="https://route4me.com/api.v4/configuration-settings.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="add_array_of_account_config_values_data.json"
			
			Set r4m=New Route4Me
			r4m.outputFile="add_array_of_account_config_values_RESPONSE.json"
			
			r4m.HttpPostRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://route4me.com/api.v4/configuration-settings.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of adding an array of configuration keys to a member's account.

curl -o add_array_of_account_config_values_RESPONSE.json -k -g -X POST -H "Content-Type: application/json;" -d "@add_array_of_account_config_values_data.json" "%url%?api_key=%apikey%" 

timeout /t 30
#!/bin/bash

url=https://route4me.com/api.v4/configuration-settings.php
apikey=11111111111111111111111111111111

# The example demonstrates the process of adding an array of configuration keys to a member's account.

curl -o add_array_of_account_config_values_RESPONSE.json -k -g -X POST -H "Content-Type: application/json;" -d "@add_array_of_account_config_values_data.json" "$url?api_key=$apikey" 

echo "Finished..."

sleep 15
public void AddConfigurationKeyArrayTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	MemberConfigurationParameters[] parametersArray = new MemberConfigurationParameters[]
		{
			new MemberConfigurationParameters
			{
				config_key = "Test My Height",
				config_value = "185"
			},
			new MemberConfigurationParameters
			{
				config_key = "Test My Weight",
				config_value = "110"
			},
		};

	// Run the query
	var result = route4Me.CreateNewConfigurationKey(parametersArray, out string errorString);

	Assert.IsNotNull(result, "AddNewConfigurationKeyTest failed... " + errorString);

	lsConfigurationKeys.Add("Test My Height");
	lsConfigurationKeys.Add("Test My Weight");
}
Public Sub AddConfigurationKeyArrayTest()
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)

	Dim parametersArray As MemberConfigurationParameters() = New MemberConfigurationParameters() _
	{
		New MemberConfigurationParameters With {
		.config_key = "Test My Height",
		.config_value = "185"
	},
	New MemberConfigurationParameters With {
		.config_key = "Test My Weight",
		.config_value = "110"
	}}

	Dim errorString As String = Nothing
	Dim result = route4Me.CreateNewConfigurationKey(parametersArray, errorString)

	Assert.IsNotNull(result, "AddNewConfigurationKeyTest failed... " & errorString)

	lsConfigurationKeys.Add("Test My Height")
	lsConfigurationKeys.Add("Test My Weight")
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Example refers to the process of adding array of the new account configuration keys to the user's account.
// Set the api key in the Route4me class
Route4Me::setApiKey('11111111111111111111111111111111');

$params = [
    Member::fromArray([
        'config_key' => 'hide_sharing_in_route_parameters_dialog',
        'config_value' => 'false',
    ]),
    Member::fromArray([
        'config_key' => 'disable_telematics_popup_overlay',
        'config_value' => 'false',
    ])
 ];
 
$member = new Member();

$response = $member->newMemberConfigKey($params);

Route4Me::simplePrint($response);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/configuration-settings.php?api_key=...

You can expect this API response:

{
	"result": "OK",
	"affected": 2
}

Get All Configuration Data

Get all configuration data from a member’s account.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
<job id="Get All Configuration Data">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example refers to the process of getting all configuration data from an account.
      
      url="https://route4me.com/api.v4/configuration-settings.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://route4me.com/api.v4/configuration-settings.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of getting all configuration data from an account.

ECHO ON

curl -o file1.txt -g -X GET -k "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://route4me.com/api.v4/configuration-settings.php
apikey=11111111111111111111111111111111

# The example refers to the process of getting all configuration data from an account.

curl -o file1.txt -g -X GET -k "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get All Configuration Data
        /// </summary>
        public void GetAllConfigurationData()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberConfigurationParameters @params = new MemberConfigurationParameters();

            // Run the query
            string errorString = "";
            MemberConfigurationDataRersponse result = route4Me.GetConfigurationData(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("GetAllConfigurationData executed successfully");
                Console.WriteLine("Result: " + result.result);
                foreach (MemberConfigurationData mc_data in result.data)
                {
                    Console.WriteLine("member_id= " + mc_data.member_id);
                    Console.WriteLine("config_key= " + mc_data.config_key);
                    Console.WriteLine("config_value= " + mc_data.config_value);
                    Console.WriteLine("---------------------------");
                }
            }
            else
            {
                Console.WriteLine("GetAllConfigurationData error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get All Configuration Data
        ''' </summary>
        Public Sub GetAllConfigurationData()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberConfigurationParameters = New MemberConfigurationParameters()

            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberConfigurationDataRersponse = route4Me.GetConfigurationData(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("GetAllConfigurationData executed successfully")
                Console.WriteLine("Result: " & result.result)
                For Each mc_data As MemberConfigurationData In result.data
                    Console.WriteLine("member_id= " & mc_data.member_id)
                    Console.WriteLine("config_key= " & mc_data.config_key)
                    Console.WriteLine("config_value= " & mc_data.config_value)
                    Console.WriteLine("---------------------------")
                Next
            Else
                Console.WriteLine("GetAllConfigurationData error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
    values, err := service.GetConfigValues()
    if err != nil {
        // handle error
        return
    }
    // process values
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

// The example refers to the process of getting all configuration data from an account.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$params = Member::fromArray(array ( ));

$member = new Member();

$response = $member->getMemberConfigData($params);

foreach ($response as $key => $value) {
    if (is_array($value)) {
        foreach ($value as $v1) {
            Route4Me::simplePrint($v1);
            echo "<br>";
        }
    } else {
        echo "$key => $value <br>";
    }
    echo "<br>";
}
unit GetAllConfigValuesUnit;

interface

uses SysUtils, BaseExampleUnit, EnumsUnit;

type
  TGetAllConfigValues = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation
uses
  CommonTypesUnit;
procedure TGetAllConfigValues.Execute;
var
  ErrorString: String;
  Values: TListStringPair;
  i: Integer;
begin
  Values := Route4MeManager.User.GetAllConfigValues(ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn('GetAllConfigValues executed successfully.');

      for i := 0 to Values.Count - 1 do
        WriteLn(Format('Key="%s", Value="%s"', [Values[i].Key, Values[i].Value]));

      WriteLn('');
    end
    else
      WriteLn(Format('GetAllConfigValues error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Values);
  end;
end;

end.
#include <iostream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{    
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    int ret = 0;

    if(route.get_config() == 0)
    {
        cout << "Config data:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else
    {
        cout << "Failed to get config " << route.get_err_code() << ": " << route.get_err_msg() << endl;
        ret = -1;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/configuration-settings.php?api_key=...

You can expect this API response:

{
  "result": "OK",
  "data": [
    {
      "member_id": 1,
      "config_key": "destination_icon_width",
      "config_value": "32"
    },
    {
      "member_id": 1,
      "config_key": "destination_icon_uri",
      "config_value": "value"
    }
  ]
}

Get a Specific Configuration Key Value

Get a specific configuration key value from a member’s account.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
config_key string Configuration key GET
<job id="Get Specific Key Value">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of getting a specific single configuration key data.
      
      url="https://route4me.com/api.v4/configuration-settings.php"
      apikey="11111111111111111111111111111111"
      config_key="destination_icon_width"
      
      url=url&"?api_key="&apikey
      url=url&"&config_key="&config_key
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/configuration-settings.php
SET apikey=11111111111111111111111111111111
SET config_key=destination_icon_width

:: The example demonstrates the process of getting a specific single configuration key data.

ECHO ON

curl -o file1.txt -g -X GET -k "%url%?api_key=%apikey%&config_key=%config_key%"

timeout /t 30
#!/bin/bash

url=https://route4me.com/api.v4/configuration-settings.php
apikey=11111111111111111111111111111111
config_key=destination_icon_width

# The example demonstrates the process of getting a specific single configuration key data.

curl -o file1.txt -g -X GET -k "$url?api_key=$apikey&config_key=$config_key"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Specific Configuration Key Value (v4)
        /// </summary>
        public void GetSpecificConfigurationKeyData()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberConfigurationParameters @params = new MemberConfigurationParameters { config_key = "destination_icon_uri" };

            // Run the query
            string errorString = "";
            MemberConfigurationDataRersponse result = route4Me.GetConfigurationData(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("GetSpecificConfigurationKeyData executed successfully");
                Console.WriteLine("Result: " + result.result);
                foreach (MemberConfigurationData mc_data in result.data)
                {
                    Console.WriteLine("member_id= " + mc_data.member_id);
                    Console.WriteLine("config_key= " + mc_data.config_key);
                    Console.WriteLine("config_value= " + mc_data.config_value);
                    Console.WriteLine("---------------------------");
                }
            }
            else
            {
                Console.WriteLine("GetSpecificConfigurationKeyData error: {0}", errorString);
            }
        }
    }
}
Public Sub GetSpecificConfigurationKeyDataTest()
	Dim route4Me As New Route4MeManager(c_ApiKey)

	Dim params As New MemberConfigurationParameters() With { _
		.config_key = "destination_icon_uri" _
	}

	' Run the query
	Dim errorString As String = ""
	Dim result As MemberConfigurationDataRersponse = route4Me.GetConfigurationData(params, errorString)

	Assert.IsNotNull(result, Convert.ToString("GetSpecificConfigurationKeyDataTest failed... ") & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
    values, err := service.GetConfigValues()
    if err != nil {
        // handle error
        return
    }
    // process values
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the process of getting a specific single configuration key data.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$member = new Member();

// Get a random member config key
$randomParams = Member::fromArray(array ( ));

$response = $member->getMemberConfigData($randomParams);

assert(!is_null($response), "Can't retrieve all config data");
assert(sizeof($response)==2, "Can't retrieve all config data");
assert(isset($response['data']), "Can't retrieve all config data");

$randomKey = $response['data'][rand(0, sizeof($response['data']) - 1)]['config_key'];

// Get a specific single configuration key data
echo "randomKey -> $randomKey <br><br>";

$params = Member::fromArray(array (
    "config_key"  => $randomKey
));

$response = $member->getMemberConfigData($params);

foreach ($response as $key => $value) {
    if (is_array($value)) {
        Route4Me::simplePrint($value);
    } else {
        echo "$key => $value <br>";
    }
}
unit GetConfigValueUnit;

interface

uses SysUtils, BaseExampleUnit, EnumsUnit;

type
  TGetConfigValue = class(TBaseExample)
  public
    procedure Execute(Key: String);
  end;

implementation
uses
  CommonTypesUnit, NullableBasicTypesUnit;
procedure TGetConfigValue.Execute(Key: String);
var
  ErrorString: String;
  Value: NullableString;
begin
  Value := Route4MeManager.User.GetConfigValue(Key, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    if Value.IsNotNull then
      WriteLn(
        Format('GetConfigValue executed successfully. Key="%s", Value="%s"',
        [Key, Value.Value]))
    else
      WriteLn('GetConfigValue error');
    WriteLn('');
  end
  else
    WriteLn(Format('GetConfigValue error: "%s"', [ErrorString]));
end;

end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{

    init(key, 1);

    if (!get_config(""))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api.v4/configuration-settings.php?api_key=...&config_key=...

You can expect this API response:

{
  "result": "OK",
  "data": [{
    "member_id": 1,
    "config_key": "destination_icon_width",
    "config_value": "32"
  }]
}

Remove a Configuration Key

Removes a configuration key from a member’s account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
config_key string Configuration key POST
<job id="Remove Specific Configuration Key">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example demonstrates the process of removing a specific configuration key belonging to an account.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://route4me.com/api.v4/configuration-settings.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="delete_existing_config_key_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpDeleteRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://route4me.com/api.v4/configuration-settings.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of removing a specific configuration key belonging to an account.

curl -o file1.txt -k -g -X DELETE -H "Content-Type: application/json;" -d "@delete_existing_config_key_data.json" "%url%?api_key=%apikey%" 

timeout /t 30
#!/bin/bash

url=https://route4me.com/api.v4/configuration-settings.php
apikey=11111111111111111111111111111111

# The example demonstrates the process of removing a specific configuration key belonging to an account.

curl -o file1.txt -k -g -X DELETE -H "Content-Type: application/json;" -d "@delete_existing_config_key_data.json" "$url?api_key=$apikey" 

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Remove a Configuration Key
        /// </summary>
        public void RemoveConfigurationKey()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberConfigurationParameters @params = new MemberConfigurationParameters { config_key = "My height" };

            // Run the query
            string errorString = "";
            MemberConfigurationResponse result = route4Me.RemoveConfigurationKey(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("RemoveConfigurationKey executed successfully");
                Console.WriteLine("Result: " + result.result);
                Console.WriteLine("Affected: " + result.affected);
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("UserRegistration error: {0}", errorString);
            }

        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Remove a Configuration Key
        ''' </summary>
        Public Sub RemoveConfigurationKey()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberConfigurationParameters = New MemberConfigurationParameters() With { _
                .config_key = "My height" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberConfigurationResponse = route4Me.RemoveConfigurationKey(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("RemoveConfigurationKey executed successfully")
                Console.WriteLine("Result: " & result.result)
                Console.WriteLine("Affected: " & result.affected)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("UserRegistration error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
    success, err := service.DeleteConfigEntry("config-test-key-go")
    if err != nil {
        // request unsuccessful
        return
    }
    if !success {
        // couldn't delete entry
        return
    }
    // key deleted
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

// The example demonstrates the process of removing a specific configuration key belonging to an account.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$member = new Member();

// Create a config key
$createParams = Member::fromArray(array (
    "config_key"   => "My height",
    "config_value" => "182"
));

$response = $member->newMemberConfigKey($createParams);

// Delete a config key
$removeParams = Member::fromArray(array (
    "config_key" => "My height"
));

$response = $member->removeMemberConfigKey($removeParams);

Route4Me::simplePrint($response);
unit DeleteConfigValueUnit;

interface

uses SysUtils, BaseExampleUnit, EnumsUnit;

type
  TDeleteConfigValue = class(TBaseExample)
  public
    function Execute(Key: String): boolean;
  end;

implementation
function TDeleteConfigValue.Execute(Key: String): boolean;
var
  ErrorString: String;
begin
  Result := Route4MeManager.User.DeleteConfigValue(Key, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    if Result then
      WriteLn('DeleteConfigValue executed successfully')
    else
      WriteLn('DeleteConfigValue error');
    WriteLn('');
  end
  else
    WriteLn(Format('DeleteConfigValue error: "%s"', [ErrorString]));
end;

end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api.v4/configuration-settings.php?api_key=...

You can expect this API response:

{
  "result": "OK",
  "affected": 1
}

Update a Configuration Key Value

Updates a configuration key value in a member’s account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP method
api_key string API key of the user GET
config_key string Configuration key POST
config_value string Configuration value POST
is_hidden_value boolean If true the value is hidden POST
can_unhide_value boolean If true, the value can be visible POST
<job id="Update Specific Key Value">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      ' The example demonstrates the process of updating an existing configuration key value.
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://route4me.com/api.v4/configuration-settings.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
    
      jFile="update_existing_config_key_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://route4me.com/api.v4/configuration-settings.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of updating an existing configuration key value.

curl -o file1.txt -k -g -X PUT -H "Content-Type: application/json;" -d "@update_existing_config_key_data.json" "%url%?api_key=%apikey%" 

timeout /t 30

#!/bin/bash

url=https://route4me.com/api.v4/configuration-settings.php
apikey=11111111111111111111111111111111

# The example demonstrates the process of updating an existing configuration key value.

curl -o file1.txt -k -g -X PUT -H "Content-Type: application/json;" -d "@update_existing_config_key_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Update a Configuration Key Value
        /// </summary>
        public void UpdateConfigurationKey()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            MemberConfigurationParameters @params = new MemberConfigurationParameters
            {
                config_key = "destination_icon_uri",
                config_value = "444"
            };

            // Run the query
            string errorString = "";
            MemberConfigurationResponse result = route4Me.UpdateConfigurationKey(@params, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("UpdateConfigurationKey executed successfully");
                Console.WriteLine("Result: " + result.result);
                Console.WriteLine("Affected: " + result.affected);
                Console.WriteLine("---------------------------");
            }
            else
            {
                Console.WriteLine("UpdateConfigurationKey error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Update a Configuration Key Value
        ''' </summary>
        Public Sub UpdateConfigurationKey()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As MemberConfigurationParameters = New MemberConfigurationParameters() With { _
                .config_key = "destination_icon_uri", _
                .config_value = "444" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim result As MemberConfigurationResponse = route4Me.UpdateConfigurationKey(params, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("UpdateConfigurationKey executed successfully")
                Console.WriteLine("Result: " & result.result)
                Console.WriteLine("Affected: " & result.affected)
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("UpdateConfigurationKey error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/users"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &users.Service{Client: client}
    success, err := service.UpdateConfigEntry("config-test-key-go", "config-test-value-go")
    if err != nil {
        // request unsuccessful
        return
    }
    if !success {
        // couldn't edit entry
        return
    }
    // everything went as expected
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Member;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the process of updating an existing configuration key value.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$member = new Member();

// Get a random member config key
$randomParams = Member::fromArray(array ( ));

$response = $member->getMemberConfigData($randomParams);

assert(!is_null($response), "Can't retrieve all config data");
assert(sizeof($response)==2, "Can't retrieve all config data");
assert(isset($response['data']), "Can't retrieve all config data");

$randIndex = rand(0, sizeof($response['data']) - 1);

$randomKey = $response['data'][$randIndex]['config_key'];
$randomValue = $response['data'][$randIndex]['config_value'];
echo "Random key -> $randomKey,  random value -> $randomValue <br><br>";

// Update existing configuration key data
$params = Member::fromArray(array (
    "config_key"   => $randomKey,
    "config_value" => $randomValue." Updated"
));

$response = $member->updateMemberConfigKey($params);

assert(isset($response['affected']), "Can't update the config data");
assert(isset($response['affected'])=='1', "Can't update the config data");

Route4Me::simplePrint($response);
unit UpdateConfigValueUnit;

interface

uses SysUtils, BaseExampleUnit, EnumsUnit;

type
  TUpdateConfigValue = class(TBaseExample)
  public
    function Execute(Key, Value: String): boolean;
  end;

implementation
function TUpdateConfigValue.Execute(Key, Value: String): boolean;
var
  ErrorString: String;
begin
  Result := Route4MeManager.User.UpdateConfigValue(Key, Value, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    if Result then
      WriteLn('UpdateConfigValue executed successfully')
    else
      WriteLn('UpdateConfigValue error');
    WriteLn('');
  end
  else
    WriteLn(Format('UpdateConfigValue error: "%s"', [ErrorString]));
end;

end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/configuration-settings.php?api_key=...

You can expect this API response:

{
  "result": "OK",
  "affected": 1
}

Notes

A note refers to an assigned or additional text description or data added to a Route or Address object.

See the Note JSON Schema in our GitHub repository.

Note Properties

Attribute Type Description
note_id integer The ID of the note in the system.
route_id string Route ID
route_destination_id integer Route destination ID
upload_id string The unique ID of the file attachment.
ts_added integer The Unix timestamp.
lat number Latitude
lng number Longitude
activity_type string Activity Type
contents string Contents
upload_type string Upload Type
upload_url string The direct CDN URL of the uploaded attachment.
upload_extension string The extension of the attachment.
device_type string Device type

Add Route Notes

Adds a note to a route.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
address_id integer Address ID
dev_lat number Device latitude
dev_lng number Device longitude
device_type string Device type
input data POST data A valid JSON object string. See the Note JSON Schema as a guide.
<job id="AddNotesToRoute">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            ' For accurate testing and results, use your API key and insert real test data.
            
            WScript.Echo "Please, press OK and wait..."
            
            url="https://api.route4me.com/actions/addRouteNotes.php"
            apikey="11111111111111111111111111111111"
            routeid="vf55g4fg5dfgfdg1fdgd21g2f"
            addrid="787854545455"
            dev_lat="33.132675170898"
            dev_lng="-83.244743347168"
            dev_type="web"
            updatetype="dropoff"
            
            url=url&"?api_key="&apikey
            url=url&"&route_id="&routeid
            url=url&"&address_id="&addrid
            url=url&"&dev_lat="&dev_lat
            url=url&"&dev_lng="&dev_lng
            url=url&"&device_type="&dev_type
            url=url&"&update_type="&updatetype
            
            jFile="add_notes_to_route_data.json"
            
            Set r4m=New Route4Me
            
            r4m.HttpPostRequest url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void AddAddressNote(string routeId, int addressId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      NoteParameters noteParameters = new NoteParameters()
      {
        RouteId = routeId,
        AddressId = addressId,
        Latitude = 33.132675170898,
        Longitude = -83.244743347168,
        DeviceType = DeviceType.Web.Description(),
        ActivityType = StatusUpdateType.DropOff.Description()
      };

      // Run the query
      string errorString;
      string contents = "Test Note Contents " + DateTime.Now.ToString();
      AddressNote note = route4Me.AddAddressNote(noteParameters, contents, out errorString);

      Console.WriteLine("");

      if (note != null)
      {
        Console.WriteLine("AddAddressNote executed successfully");

        Console.WriteLine("Note ID: {0}", note.NoteId);
      }
      else
      {
        Console.WriteLine("AddAddressNote error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub AddAddressNote(routeId As String, addressId As Integer)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim noteParameters As New NoteParameters() With { _
                .RouteId = routeId, _
                .AddressId = addressId, _
                .Latitude = 33.132675170898, _
                .Longitude = -83.244743347168, _
                .DeviceType = EnumHelper.GetEnumDescription(DeviceType.Web), _
                .ActivityType = EnumHelper.GetEnumDescription(StatusUpdateType.DropOff) _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim contents As String = "Test Note Contents " + DateTime.Now.ToString()
            Dim note As AddressNote = route4Me.AddAddressNote(noteParameters, contents, errorString)

            Console.WriteLine("")

            If note IsNot Nothing Then
                Console.WriteLine("AddAddressNote executed successfully")

                Console.WriteLine("Note ID: {0}", note.NoteId)
            Else
                Console.WriteLine("AddAddressNote error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import (
    DEVICE_TYPE
)

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    route = route4me.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            route_id = response.route_id
            route_destination_id = response.addresses[0].route_destination_id
            lat = response.addresses[0].lat
            lng = response.addresses[0].lng
            note = 'Test Note Contents'
            response = route4me.address.add_address_notes(
                note,
                route_id=route_id,
                device_type=DEVICE_TYPE.WEB,
                activity_type='wrongdelivery',
                dev_lat=lat,
                dev_lng=lng,
                address_id=route_destination_id,
            )
            if hasattr(response, 'errors'):
                print '. '.join(response.errors)
            else:
                print 'Note ID: {}'.format(response.note_id)
                print 'Note contents: {}'.format(response.note.contents)
                print 'Route ID: {}'.format(response.note.route_id)
                print 'Route Destination ID: {}'.format(
                    response.note.route_destination_id)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.notes;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.notes.NoteRequest;
import com.route4me.sdk.services.notes.NotesManager;
import com.route4me.sdk.services.notes.StatusUpdateType;
import com.route4me.sdk.services.routing.*;

import java.util.List;

public class AddAddressNotes {

    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager routeManager = new RoutingManager(apiKey);
        List<Route> routes = routeManager.getRoutes(new RoutesRequest().setLimit(10));
        Route responseObject = routeManager.getRoute(new RoutesRequest().setId(routes.get(0).getId()));
        NotesManager notesManager = new NotesManager(apiKey);
        Address address = responseObject.getAddresses().get(0);
        long routeDestinationID = address.getRouteDestinationId();
        String noteContent = "Adding a note to an Address";
        NoteRequest request = new NoteRequest().setRouteId(routes.get(0).getId())
                .setAddressId(Long.toString(routeDestinationID))
                .setLatitude(address.getLatitude())
                .setLongitude(address.getLongitude())
                .setDeviceType(Constants.DeviceType.WEB);
        NotesManager.AddedNote note = notesManager.addAddressNotes(request, noteContent, StatusUpdateType.WRONG_DELIVERY);
        if (note.getStatus()) {
            System.out.println(note);
        }
    }
}
package AddAddressNote;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::QueryTypes::NoteParameters;
use Route4MeSDK::DataTypes::StatusUpdateType;

sub AddAddressNote {
    my ($self, $routeId, $addressId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $noteParameters = NoteParameters->new(
        route_id => $routeId,
        address_id => $addressId,
        dev_lat => 33.132675170898,
        dev_lng => -83.244743347168,
        device_type => DeviceType->Web,
        strUpdateType => StatusUpdateType->DropOff
    );

    my $errorString = "";

    my $contents = "Test Note Contents " . localtime();

    my $note = $route4Me->addAddressNote($noteParameters, $contents, $errorString);

    if ($note) {
        print "AddAddressNote executed successfully\n";

        printf "Note ID: %s\n\n", $note->{'note_id'};

    } else {
        printf "AddAddressNote error: %s\n", $errorString;
    }
}

1;
@ECHO OFF

SET url=https://api.route4me.com/actions/addRouteNotes.php

SET apikey=11111111111111111111111111111111
SET routeid=DD376C7148E7FEE36CFABE2BD9978BDD

:: The parameters of the address "2705 N River Rd, Stow, OH 44224"
SET addrid=183045812
SET dev_lat=41.145240783691
SET dev_lng=-81.410247802734

SET dev_type=web
SET updatetype=dropoff
SET content=Note example for Destination Audit Use Case

:: The example refers to the process of adding a note to a route by sending HTTP parameters.

ECHO ON

curl -o file1.txt -g -k -X POST -H "Content-Type: multipart/form-data;" -F "strNoteContents=%content%" -F "strUpdateType=%dropoff%" "%url%?api_key=%apikey%&route_id=%routeid%&address_id=%addrid%&dev_lat=%dev_lat%&dev_lng=%dev_lng%&device_type=%dev_type%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/addRouteNotes.php

apikey=11111111111111111111111111111111
routeid=DD376C7148E7FEE36CFABE2BD9978BDD

# The parameters of the address "2705 N River Rd, Stow, OH 44224"
addrid=183045812
dev_lat=41.145240783691
dev_lng=-81.410247802734

dev_type=web
updatetype=dropoff
content=Note example for Destination Audit Use Case

# The example refers to the process of adding a note to a route by sending HTTP parameters.

curl -o file1.txt -g -k -X POST -H "Content-Type: multipart/form-data;" -F "strNoteContents=$content" -F "strUpdateType=$dropoff" "$url?api_key=$apikey&route_id=$routeid&address_id=$addrid&dev_lat=$dev_lat&dev_lng=$dev_lng&device_type=$dev_type"

echo "Finished..."

sleep 15
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$route_id = $route->getRandomRouteId(0, 10);

assert(!is_null($route_id), "Can't retrieve random route_id");

// Get the random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($route_id);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

// Add an address note
$noteParameters = array(
    "route_id"        => $route_id,
    "address_id"      => $route_destination_id,
    "dev_lat"         => 33.132675170898,
    "dev_lng"         => -83.244743347168,
    "device_type"     => "web",
    "strUpdateType"   => "dropoff",
    "strNoteContents" => "Test"
);

$address = new Address();

echo "route_id = $route_id <br>";
echo "route_destination_id = $route_destination_id <br><br>";

$address1 = $address->AddAddressNote($noteParameters);

Route4Me::simplePrint((array)$address1, true);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    
    query := &NoteQuery{
        RouteID:      get.ID,
        AddressID:    get.Addresses[0].RouteDestinationID.String(),
        Latitude:     33.132675170898,
        Longitude:    -83.244743347168,
        ActivityType: DropOff,
    }
    addedNote, err = service.AddAddressNote(query, "Note Contents")
    if err != nil {
        //handle errors
        return
    }
}
unit AddAddressNoteUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TAddAddressNote = class(TBaseExample)
  public
    procedure Execute(RouteId: String; AddressId: integer);
  end;

implementation

uses NoteParametersUnit, AddressNoteUnit, EnumsUnit;

procedure TAddAddressNote.Execute(RouteId: String; AddressId: integer);

var
  ErrorString: String;
  Parameters: TNoteParameters;
  Contents: String;
  Note: TAddressNote;
begin
  Parameters := TNoteParameters.Create();
  try
    Parameters.RouteId := RouteId;
    Parameters.AddressId := AddressId;
    Parameters.Latitude := 33.132675170898;
    Parameters.Longitude := -83.244743347168;
    Parameters.DeviceType := TDeviceTypeDescription[TDeviceType.Web];
    Parameters.ActivityType := TStatusUpdateTypeDescription[TStatusUpdateType.DropOff];

    Contents := 'Test Note Contents ' + DateTimeToStr(Now);
    Note := Route4MeManager.AddressNote.Add(Parameters, Contents, ErrorString);
    try
      WriteLn('');

      if (Note <> nil) then
      begin
        WriteLn('AddAddressNote executed successfully');
        WriteLn(Format('Note ID: %d', [Note.NoteId.Value]));
      end
      else
        WriteLn(Format('AddAddressNote error: "%s"', [ErrorString]));
    finally
      FreeAndNil(Note);
    end;
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("add_address_to_route.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";
    const char *route_destination_id = "174405709A";

    int ret = route.add_route_notes(route_id, route_destination_id, "info");
    if (ret == 0)
      cout << "Note added" << endl;
    else
      cout << "Error adding note :" << route.get_err_code() << ": " << route.get_err_msg() << endl;

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
"use strict"

const path = require("path")
const debug = require("debug")("route4me-node:examples")

require("../init-examples-suite")
const helper  = require("./../../test/helper")

helper.describeIntegration(helper.toSuiteName(__filename), function T() {
    this.timeout(5000)
    this.slow(3000)
    it.skip(path.basename(__filename), (done) => {
        // const Route4Me = require("route4me-node")

        const apiKey   = "11111111111111111111111111111111"
        const route4me = new Route4Me(apiKey)
        const noteData = {
            addressId: 167899269,
            routeId: "241466F15515D67D3F951E2DA38DE76D",
            deviceLatitude: 55.6884868,
            deviceLongitude: 12.5366426,
            deviceType: "android_phone",
            note: "Just a test note",
            type: "web",
        }

        route4me.Notes.create(noteData, (err, noteResult) => {
            debug("error  ", err)
            debug("result ", noteResult)

            // Expectations about result
            expect(err).is.null

            expect(noteResult).has.property("optimization_problem_id", "07372F2CF3814EC6DFFAFE92E22771AA")

            // TODO: remove `done` call from examples
            done()
        })
    })
})
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char route_id[] = "CA902292134DBC134EAF8363426BD247";
    char route_destination_id[] = "174405709A";
    char file_name[] = "add_address_to_route.json";
    char* data = NULL;
    struct MapPoint point = {0,1};

    deserialize(file_name, &data);

    init(key, 1);

    if (!add_route_notes(route_id, route_destination_id,"notes", "laptop", &point, data))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    if (data)
    {
        free(data);
    }

    cleanUp();
    return 0;
}


HTTP Request

POST
/actions/addRouteNotes.php?api_key=...&route_id=...&address_id=...&dev_lat=...&dev_lng=...

You can expect this API response:

{
    "status": true,
    "note_id": "1015289",
    "upload_id": "",
    "note": {
        "note_id": 1015289,
        "route_id": "DD376C7148E7FEE36CFABE2BD9978BDD",
        "route_destination_id": 183045812,
        "ts_added": 1480511401,
        "activity_type": "",
        "upload_id": "",
        "upload_extension": null,
        "upload_url": null,
        "upload_type": null,
        "contents": "Note example for Destination Audit Use Case",
        "lat": 41.145241,
        "lng": -81.410248,
        "device_type": "web"
    }
}

Add a Note File

Adds a note to a route through file upload.

See the sample CSV file for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
address_id integer Address ID
dev_lat number Device latitude
dev_lng number Device longitude
device_type string Device type
strUpdateType string Update type
strFilename file A file containing data for the note. See this sample CSV file as a guide.
@ECHO OFF

SET url=https://api.route4me.com/actions/addRouteNotes.php

SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7

SET addrid=162916895
SET dev_lat=33.132675170898
SET dev_lng=-83.244743347168

SET dev_type=web
SET updatetype=dropoff
SET "filename=notes.csv"
SET "strNoteContents=This is the content of the file"

:: The example refers to the process of adding a note to a route through the use of file uploading.

ECHO ON

curl -o file1.txt -g -k -X POST -F "strFilename=@%filename%" "%url%?api_key=%apikey%&route_id=%routeid%&address_id=%addrid%&dev_lat=%dev_lat%&dev_lng=%dev_lng%&device_type=%dev_type%&strUpdateType=ANY_FILE"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/addRouteNotes.php

apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7

addrid=162916895
dev_lat=33.132675170898
dev_lng=-83.244743347168

dev_type=web
updatetype=dropoff
filename="notes.csv"

# The example refers to the process of adding a note to a route through the use of file uploading.


curl -o file1.txt -g -k -X POST -F "strFilename=@$filename" "$url?api_key=$apikey&route_id=$routeid&address_id=$addrid&dev_lat=$dev_lat&dev_lng=$dev_lng&device_type=$dev_type&strUpdateType=ANY_FILE"

echo "Finished..."

sleep 15
<job id="Add Notes To Route File Uploading">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            ' The example refers to the process of adding a note to a route through the use of file uploading.
            
            WScript.Echo "Please, press OK and wait..."
            
            url="https://api.route4me.com/actions/addRouteNotes.php"
            apikey="11111111111111111111111111111111"
            routeid="7CA872B9D3C0C22B54841090DD3F0C4B"
            addrid="167101717"
            dev_lat="33.132675170898"
            dev_lng="-83.244743347168"
            dev_type="web"
            updatetype="dropoff"
            filename="notes.csv"
            
            url=url&"?api_key="&apikey
            url=url&"&route_id="&routeid
            url=url&"&address_id="&addrid
            url=url&"&dev_lat="&dev_lat
            url=url&"&dev_lng="&dev_lng
            url=url&"&device_type="&dev_type
            url=url&"&strUpdateType="&updatetype
            
            Set r4m=New Route4Me
            
            r4m.Upload url, filename, "strFilename", "strFilename="&filename
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void AddAddressNoteWithFile(string routeId, int addressId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      NoteParameters noteParameters = new NoteParameters()
      {
        RouteId = routeId,
        AddressId = addressId,
        Latitude = 33.132675170898,
        Longitude = -83.244743347168,
        DeviceType = DeviceType.Web.Description(),
        ActivityType = StatusUpdateType.DropOff.Description()
      };

      string tempFilePath = null;
      using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Route4MeSDKTest.Resources.test.png"))
      {
        var tempFiles = new TempFileCollection();
        {
          tempFilePath = tempFiles.AddExtension("png");
          System.Console.WriteLine(tempFilePath);
          using (Stream fileStream = File.OpenWrite(tempFilePath))
          {
            stream.CopyTo(fileStream);
          }
        }
      }

      // Run the query
      string errorString;
      string contents = "Test Note Contents with Attachment " + DateTime.Now.ToString();
      AddressNote note = route4Me.AddAddressNote(noteParameters, contents, tempFilePath, out errorString);

      Console.WriteLine("");

      if (note != null)
      {
        Console.WriteLine("AddAddressNoteWithFile executed successfully");

        Console.WriteLine("Note ID: {0}", note.NoteId);
      }
      else
      {
        Console.WriteLine("AddAddressNoteWithFile error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Imports System.IO
Imports System.Reflection
Imports System.CodeDom.Compiler
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub AddAddressNoteWithFile(routeId As String, addressId As Integer)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim noteParameters As New NoteParameters() With { _
                .RouteId = routeId, _
                .AddressId = addressId, _
                .Latitude = 33.132675170898, _
                .Longitude = -83.244743347168, _
                .DeviceType = DataTypes.DeviceType.Web, _
                .ActivityType = StatusUpdateType.DropOff _
            }

            Dim tempFilePath As String = Nothing
            Using stream As Stream = File.Open("test.png", FileMode.Open)
                Dim tempFiles = New TempFileCollection()
                If True Then
                    tempFilePath = tempFiles.AddExtension("png")
                    System.Console.WriteLine(tempFilePath)
                    Using fileStream As Stream = File.OpenWrite(tempFilePath)
                        stream.CopyTo(fileStream)
                    End Using
                End If
            End Using

            ' Run the query
            Dim errorString As String = ""
            Dim contents As String = "Test Note Contents with Attachment " + DateTime.Now.ToString()
            Dim note As AddressNote = route4Me.AddAddressNote(noteParameters, contents, tempFilePath, errorString)

            Console.WriteLine("")

            If note IsNot Nothing Then
                Console.WriteLine("AddAddressNoteWithFile executed successfully")

                Console.WriteLine("Note ID: {0}", note.NoteId)
            Else
                Console.WriteLine("AddAddressNoteWithFile error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$route_id = $route->getRandomRouteId(0, 10);

assert(!is_null($route_id), "Can't retrieve random route_id");

// Get the random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($route_id);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

// Add a file note
$noteParameters = array(
    "strFilename"     => "notes.csv",
    "route_id"        => $route_id,
    "address_id"      => $route_destination_id,
    "dev_lat"         => 33.132675170898,
    "dev_lng"         => -83.244743347168,
    "device_type"     => "web",
    "strUpdateType"   => "ANY_FILE"
);

$address = new Address();

echo "route_id = $route_id <br>";
echo "route_destination_id = $route_destination_id <br><br>";

$address1 = $address->AddNoteFile($noteParameters);

Route4Me::simplePrint($address1);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/actions/addRouteNotes.php?api_key=...&route_id=...&address_id=...&dev_lat=...&dev_lng=...

You can expect this API response:

{
    "status": true,
    "note_id": "539264",
    "upload_id": "1a499113c63d68d1a5d26045a1763d16",
    "note": {
        "note_id": 539264,
        "route_id": "5C15E83A4BE005BCD1537955D28D51D7",
        "route_destination_id": 162916895,
        "ts_added": 1466515325,
        "activity_type": "",
        "upload_id": "1a499113c63d68d1a5d26045a1763d16",
        "upload_extension": "csv",
        "upload_url": "http:\/\/adb6def9928467589ebb-f540d5a8d53c2e76ad581b6e5c346ad6.r74.cf1.rackcdn.com\/1a499113c63d68d1a5d26045a1763d16.csv",
        "upload_type": "ANY_FILE",
        "contents": "",
        "lat": 33.132675,
        "lng": -83.244743,
        "device_type": "web"
    }
}

Get Notes

Get address notes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
route_destination_id integer Route destination ID
<job id="GetAddressNotes">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            
            WScript.Echo "Please, press OK and wait..."
            
            ' The example refers to the process of getting the notes attached to the address of a route.
            ' For accurate testing and results, use your API key and insert real test data.
            
            url="https://api.route4me.com/api.v4/address.php"
            apikey="11111111111111111111111111111111"
            routeid="kllk645lkl6kllk6l5k6l5k6l5k6"
            rdi="545464355"
            
            url=url&"?api_key="&apikey
            url=url&"&route_id="&routeid
            url=url&"&route_destination_id="&rdi
            
            Set r4m=New Route4Me
            
            r4m.HttpGetRequest url
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetAddressNotes(string routeId, int routeDestinationId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      NoteParameters noteParameters = new NoteParameters()
      {
        RouteId = routeId,
        AddressId = routeDestinationId
      };

      // Run the query
      string errorString;
      AddressNote[] notes = route4Me.GetAddressNotes(noteParameters, out errorString);

      Console.WriteLine("");

      if (notes != null)
      {
        Console.WriteLine("GetAddressNotes executed successfully, {0} notes returned", notes.Length);
        Console.WriteLine("");
      }
      else
      {
        Console.WriteLine("GetAddressNotes error: {0}", errorString);
        Console.WriteLine("");
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetAddressNotes(routeId As String, routeDestinationId As Integer)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim noteParameters As New NoteParameters() With { _
                .RouteId = routeId, _
                .AddressId = routeDestinationId _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim notes As AddressNote() = route4Me.GetAddressNotes(noteParameters, errorString)

            Console.WriteLine("")

            If notes IsNot Nothing Then
                Console.WriteLine("GetAddressNotes executed successfully, {0} notes returned", notes.Length)
                Console.WriteLine("")
            Else
                Console.WriteLine("GetAddressNotes error: {0}", errorString)
                Console.WriteLine("")
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    route = route4me.route
    response = route.get_routes(limit=10, Offset=5)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        response = route.get_route(route_id=response[0].route_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            route_id = response.route_id
            route_destination_id = response.addresses[0].route_destination_id
            response = route4me.address.get_address_notes(
                route_id=route_id,
                route_destination_id=route_destination_id,
            )
            if hasattr(response, 'errors'):
                print '. '.join(response.errors)
            else:
                print 'Address: {}'.format(response.address)
                print 'Notes'
                for i, note in response.notes:
                    print '\t{0} - {1}'.format(i + 1, note)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.notes;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.notes.Note;
import com.route4me.sdk.services.notes.NotesManager;
import com.route4me.sdk.services.routing.DataObject;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class GetAddressNotes {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        RoutingManager routingManager = new RoutingManager(apiKey);
        try {
            List<Route> routes = routingManager.getRoutes(new RoutesRequest().setLimit(2));
            for(Route route : routes) {
                DataObject dataObject = routingManager.getRoute(new RoutesRequest().setId(route.getId()));
                NotesManager notesManager = new NotesManager(apiKey);
                List<Note> notes = notesManager.getAddressNotes(route.getId(), Long.toString(dataObject.getAddresses().get(0).getRouteDestinationId()));
                for (Note note : notes) {
                    System.out.println(note);
                }
            }
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
package GetAddressNotes;
use strict;
use warnings FATAL => 'all';

sub GetAddressNotes {
    my ($self, $routeId, $addressId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $noteParameters = NoteParameters->new(
        route_id => $routeId,
        address_id => $addressId
    );

    my $errorString = "";
    my @notes = $route4Me->getAddressNotes($noteParameters, $errorString);

    print "\n";

    if (@notes) {
        printf "GetAddressNotes executed successfully, %s notes returned\n\n", scalar @notes;
    } else {
        printf "GetAddressNotes error: %s \n\n", $errorString;
    }
}
1;
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route from test routes
$route = new Route();

$route_id = $route->getRandomRouteId(0, 10);

assert(!is_null($route_id), "Can't retrieve random route_id");

// Get the random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($route_id);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

// Add an address note
$noteParameters = array(
    "route_id"        => $route_id,
    "address_id"      => $route_destination_id,
    "dev_lat"         => 33.132675170898,
    "dev_lng"         => -83.244743347168,
    "device_type"     => "web",
    "strUpdateType"   => "dropoff",
    "strNoteContents" => "Test ".time()
);

$address = new Address();

$address1 = $address->AddAddressNote($noteParameters);

assert(!is_null($address1), "Can't create an address note");

// Get address notes
$noteParameters = array(
    "route_id"              => $route_id,
    "route_destination_id"  => $route_destination_id
);

$address = new Address();

$notes = $address->GetAddressesNotes($noteParameters);

echo "Destination note count --> ".$notes['destination_note_count']."<br>";

foreach ($notes['notes'] as $note) {
    echo "========== Notes ==================<br>";
    echo "note_id --> ".$note['note_id']."<br>";
    $content = isset($note['contents']) ? $note['contents'] : "";
    if (strlen($content)>0) echo "contents --> $content"."<br>";
}
@ECHO OFF

SET url=https://api.route4me.com/api.v4/address.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET routedestinationid=545464355

:: The example refers to the process of getting the notes attached to the address of a route.
:: For accurate testing and results, use your API key and insert real test data.

ECHO ON
curl -o file1.txt -g -k -X GET "%url%?api_key=%apikey%&route_id=%routeid%&route_destination_id=%routedestinationid%&notes=1"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
routedestinationid=545464355

# The example refers to the process of getting the notes attached to the address of a route.
# For accurate testing and results, use your API key and insert real test data.

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&route_id=$routeid&route_destination_id=$routedestinationid&notes=1"

echo "Finished..."

sleep 15
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/routing"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &routing.Service{Client: client}
    
    query := &NoteQuery{
        RouteID:   "route_id",
        AddressID: "address_id",
    }
    notes, err := service.GetAddressNotes(query)
    if err != nil {
        //handle errors
        return
    }
    // do something with address notes
}
unit GetAddressNotesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAddressNotes = class(TBaseExample)
  public
    procedure Execute(RouteId: String; RouteDestinationId: integer);
  end;

implementation

uses NoteParametersUnit, AddressNoteUnit;

procedure TGetAddressNotes.Execute(RouteId: String; RouteDestinationId: integer);

var
  ErrorString: String;
  Parameters: TNoteParameters;
  Notes: TAddressNoteArray;
  i: integer;
begin
  Parameters := TNoteParameters.Create();
  try
    Parameters.RouteId := RouteId;
    Parameters.AddressId := RouteDestinationId;

    Notes := Route4MeManager.AddressNote.Get(Parameters, ErrorString);
    try
      WriteLn('');

      if (Notes <> nil) then
        WriteLn(Format('GetAddressNotes executed successfully, %d notes returned',
          [Length(Notes)]))
      else
        WriteLn(Format('GetAddressNotes error: "%s"', [ErrorString]));

      WriteLn('');
    finally
      for i := Length(Notes) - 1 downto 0 do
        FreeAndNil(Notes[i]);
    end;
  finally
    FreeAndNil(Parameters);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    ifstream inf("add_address_to_route.json");
    if(!inf.is_open())
    {
        cout << "Can't find a file with addresses" << endl;
        return -1;
    }
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";
    const char *route_destination_id = "174405709A";

    ret = route.get_route_notes(route_id, route_destination_id);
    if (ret == 0)
      cout << "Notes:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
      cout << "No notes: " << route.get_err_code() << ": " << route.get_err_msg() << endl;

    // global cleanup
    CRoute4Me::cleanup();

    return ret;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char route_id[] = "CA902292134DBC134EAF8363426BD247";
    char route_destination_id[] = "174405709A";
    char file_name[] = "add_address_to_route.json";
    char* data = NULL;
    struct MapPoint point = {0,1};

    deserialize(file_name, &data);

    init(key, 1);

    if (!add_route_notes(route_id, route_destination_id,"notes", "laptop", &point, data))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    if (data)
    {
        free(data);
    }

    cleanUp();
    return 0;
}


HTTP Request

GET
/api.v4/address.php?api_key=...&route_id=...&route_destination_id=...notes=1



See the sample JSON response of this method.


Add New Custom Note Type

Add a new custom note type to the user’s account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
type string The custom note type.
values array An array of string values.
<job id="AddNewCustomNoteType">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            ' The example refers to the process of adding a custom note type to the user's account by sending HTTP parameters.
            
            WScript.Echo "Please, press OK and wait..."
            
            url="https://api.route4me.com/api.v4/note_custom_types.php"
            apikey="11111111111111111111111111111111"
            
            url=url&"?api_key="&apikey
            
            jFile="add_new_note_custom_type_data.json"
            'msgbox(url)
            Set r4m=New Route4Me
            r4m.OutputFile="add_new_note_custom_type_RESPONSE.json"
            
            r4m.HttpPostRequest2 url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/note_custom_types.php

SET apikey=11111111111111111111111111111111

:: The example refers to the process of adding a custom note type to the user's account by sending HTTP parameters.

ECHO ON

curl -o add_new_note_custom_type_RESPONSE.json -g -k -X POST -d "@add_new_note_custom_type_data.json" "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/note_custom_types.php

apikey=11111111111111111111111111111111

# The example refers to the process of adding a custom note type to the user's account by sending HTTP parameters.

curl -o add_new_note_custom_type_RESPONSE.json -g -k -X POST -d "@add_new_note_custom_type_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
public void AddCustomNoteTypeTest()
{
	var response = addCustomNoteType("To Do", new string[] { "Pass a package", "Pickup package", "Do a service" });

	Assert.IsTrue(response.GetType() != typeof(String), response.ToString());

	Assert.IsTrue(Convert.ToInt32(response) >= 0, "Can not create new custom note type");
}

public Object addCustomNoteType(string customType, string[] customValues)
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	// Run the query
	string errorString;

	var response = route4Me.AddCustomNoteType(customType, customValues, out errorString);

	return response;
}
Public Sub AddCustomNoteTypeTest()
	Dim response = addCustomNoteType("To Do", New String() {"Pass a package", "Pickup package", "Do a service"})
	Assert.IsTrue(response.[GetType]() <> GetType(String), response.ToString())
	Assert.IsTrue(Convert.ToInt32(response) >= 0, "Can not create new custom note type")
End Sub

Public Function addCustomNoteType(ByVal customType As String, ByVal customValues As String()) As Object
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	Dim errorString As String
	Dim response = route4Me.AddCustomNoteType(customType, customValues, errorString)
	Return response
End Function
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Create a custom note type
$noteParameters=array(
    "type"   => 'To Do',
    "values" => array(
                  'Pass a package',
                  'Pickup package',
                  'Do a service'
                )
);

$address = new Address();

$response = $address->createCustomNoteType($noteParameters);

Route4Me::simplePrint($response);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/note_custom_types.php?api_key=...

You can expect this API response:

{
    "result": "OK",
    "affected": 1
}

Add Custom Note To Route

Adds a custom note to a route.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
address_id string Route destination ID
dev_lat double The device latitude
dev_lng double The device longitude
format string Response format
custom_note_type[n] string URL encoded key-value pairs.
n = custom note type ID
<job id="AddCustomNotesToRoute">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			' The example refers to the process of adding a note custom type to a user's account by sending HTTP parameters.
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://www.route4me.com/actions/addRouteNotes.php"
			apikey="11111111111111111111111111111111"
			routeid="D1DF6BAF991E3CDC00134C28D27AEC12"
			addrid="289863166"
			dev_lat="-37.8207115"
			dev_lng="144.9581931"
			format="json"
			custom_note_type11="slippery"
			custom_note_type10="Backdoor"
			strUpdateType="dropoff"
			strNoteContents="test1111"
			
			url=url&"?api_key="&apikey
			url=url&"&route_id="&routeid
			url=url&"&address_id="&addrid
			url=url&"&dev_lat="&dev_lat
			url=url&"&dev_lng="&dev_lng
			url=url&"&format="&format
			
			url=url&"&custom_note_type[11]="&custom_note_type11
			url=url&"&custom_note_type[10]="&custom_note_type10
			url=url&"&strUpdateType="&strUpdateType
			url=url&"&strNoteContents="&strNoteContents
			
			'msgbox(url)
			Set r4m=New Route4Me
			
			jFile="add_custom_note_to_route_data.json" 
			r4m.OutputFile="add_custom_note_to_route_data_RESPONSE.json"
			r4m.HttpPostRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/actions/addRouteNotes.php

SET apikey=11111111111111111111111111111111
SET routeID=D1DF6BAF991E3CDC00134C28D27AEC12
SET routeDestinationID=289863166
SET format=json
SET dev_lat=-37.8207115
SET dev_lng=144.9581931

:: The example refers to the process of adding a custom note type to a route destination by sending HTTP parameters.

ECHO ON

curl -o add_custom_note_to_route_data_RESPONSE.json -g -k -X POST -d "custom_note_type[11]=slippery&custom_note_type[10]=Backdoor&strUpdateType=dropoff&strNoteContents=test1111" "%url%?api_key=%apikey%&route_id=%routeID%&address_id=%routeDestinationID%&format=%format%&dev_lat=%dev_lat%&dev_lng=%dev_lng%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/addRouteNotes.php

apikey=11111111111111111111111111111111
routeid=D1DF6BAF991E3CDC00134C28D27AEC12
address_id=289863166
format=json
dev_lat=-37.8207115
dev_lng=144.9581931

# The example refers to the process of adding a custom note type to a route destination by sending HTTP parameters.

curl -o add_custom_note_to_route_data_RESPONSE.json -g -k -X POST -d  "custom_note_type[11]=slippery&custom_note_type[10]=Backdoor&strUpdateType=dropoff&strNoteContents=test1111" "$url?api_key=$apikey&route_id=$routeid&address_id=$address_id&dev_lat=$dev_lat&dev_lng=$dev_lng&format=$format"

echo "Finished..."

sleep 15
public void AddCustomNoteToRouteTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	string errorString;

	NoteParameters noteParameters = new NoteParameters()
	{
		RouteId = tdr.SDRT_route.RouteID,
		AddressId = tdr.SDRT_route.Addresses[1].RouteDestinationId != null ? (int)tdr.SDRT_route.Addresses[1].RouteDestinationId : 0,
		Format = "json",
		Latitude = tdr.SDRT_route.Addresses[1].Latitude,
		Longitude = tdr.SDRT_route.Addresses[1].Longitude
	};

	Dictionary<string, string> customNotes = new Dictionary<string, string>()
	{
		{"custom_note_type[11]", "slippery"},
		{"custom_note_type[10]", "Backdoor"},
		{"strUpdateType", "dropoff"},
		{"strNoteContents", "test1111"}
	};

	var response = route4Me.addCustomNoteToRoute(noteParameters, customNotes, out errorString);

	Assert.IsTrue(response.GetType() != typeof(String), errorString);

	Assert.IsTrue(response.GetType() == typeof(AddressNote));
}
Public Sub AddCustomNoteToRouteTest()
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	Dim errorString As String
	Dim noteParameters As NoteParameters = New NoteParameters() With {
		.RouteId = tdr.SDRT_route.RouteID,
		.AddressId = If(tdr.SDRT_route.Addresses(1).RouteDestinationId IsNot Nothing, CInt(tdr.SDRT_route.Addresses(1).RouteDestinationId), 0),
		.Format = "json",
		.Latitude = tdr.SDRT_route.Addresses(1).Latitude,
		.Longitude = tdr.SDRT_route.Addresses(1).Longitude
	}
	Dim customNotes As Dictionary(Of String, String) = New Dictionary(Of String, String)() From {
		{"custom_note_type[11]", "slippery"},
		{"custom_note_type[10]", "Backdoor"},
		{"strUpdateType", "dropoff"},
		{"strNoteContents", "test1111"}
	}
	Dim response = route4Me.addCustomNoteToRoute(noteParameters, customNotes, errorString)
	Assert.IsTrue(response.[GetType]() <> GetType(String), errorString)
	Assert.IsTrue(response.[GetType]() = GetType(AddressNote))
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route_id");

// Get the random address ID from the selected route above
$addressRand = (array)$route->GetRandomAddressFromRoute($routeId);
$route_destination_id = $addressRand['route_destination_id'];

assert(!is_null($route_destination_id), "Can't retrieve random address");

// Add a custom note to a route
$noteParameters = array(
    'route_id'             =>  $routeId,
    'address_id'           =>  $route_destination_id,
    'format'               =>  'json',
    'dev_lat'              =>  33.132675170898,
    'dev_lng'              =>  -83.244743347168,
    'custom_note_type[11]' => 'slippery',
    'custom_note_type[10]' => 'Backdoor',
    'strUpdateType'        => 'dropoff',
    'strNoteContents'      => 'test1111'
);

$address = new Address();

$response = $address->addCustomNoteToRoute($noteParameters);

Route4Me::simplePrint($response);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/actions/addRouteNotes.php?api_key=...&route_id=...&address_id=...&format=...

You can expect this API response:

{
    "status": true,
    "note_id": "3237302",
    "upload_id": "",
    "note": {
        "note_id": 3237302,
        "route_id": "D1DF6BAF991E3CDC00134C28D27AEC12",
        "route_destination_id": 289863166,
        "ts_added": 1517238859,
        "activity_type": "dropoff",
        "upload_id": "",
        "upload_extension": null,
        "upload_url": null,
        "upload_type": null,
        "contents": "test1111",
        "lat": -37.820712,
        "lng": 144.958193,
        "device_type": "web",
        "custom_types": [{
            "note_custom_entry_id": "ABCBA1228FA18968DBEECBFA2DA7899C850E15CA",
            "note_id": "3237302",
            "note_custom_type_id": "10",
            "note_custom_value": "Backdoor",
            "note_custom_type": "Dropoff Location"
        },
        {
            "note_custom_entry_id": "0E297CA5584557C9C9782D74AEF476D33B06ACF1",
            "note_id": "3237302",
            "note_custom_type_id": "11",
            "note_custom_value": "slippery",
            "note_custom_type": "Conditions at Site"
        }]
    }
}

Get All Custom Note Types

Get all the custom note types.


PARAMETERS

Parameter Type Description
api_key string API key of the user
<job id="GetAllCustomNoteTypes">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            
            WScript.Echo "Please, press OK and wait..."
            
            ' The example refers to the process of getting all the custom note types.
            
            url="https://api.route4me.com/api.v4/note_custom_types.php"
            apikey="11111111111111111111111111111111"
            
            url=url&"?api_key="&apikey
            
            Set r4m=New Route4Me
            r4m.OutputFile="get_all_custom_note_types_RESPONSE.json"
            
            r4m.HttpGetRequest url
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/note_custom_types.php
SET apikey=11111111111111111111111111111111


:: The example refers to the process of getting all the custom note types.

ECHO ON
curl -o get_all_custom_note_types_RESPONSE.json -g -k -X GET "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/note_custom_types.php

apikey=11111111111111111111111111111111

# The example refers to the process of getting all the custom note types.

curl -o get_all_custom_note_types_RESPONSE.json -g -k -X GET "$url?api_key=$apikey"

echo "Finished..."

sleep 15
public void GetAllCustomNoteTypesTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	string errorString;

	var response = route4Me.getAllCustomNoteTypes(out errorString);

	Assert.IsTrue(response.GetType() != typeof(String), errorString);

	Assert.IsTrue(response.GetType() == typeof(CustomNoteType[]));
}
Public Sub GetAllCustomNoteTypesTest()
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	Dim errorString As String
	Dim response = route4Me.getAllCustomNoteTypes(errorString)
	Assert.IsTrue(response.[GetType]() <> GetType(String), errorString)
	Assert.IsTrue(response.[GetType]() = GetType(CustomNoteType()))
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get all custom note types
$address = new Address();

$response = $address->getAllCustomNoteTypes();

Route4Me::simplePrint($response);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/note_custom_types.php?api_key=...

You can expect this API response:

[{
    "note_custom_type_id": 10,
    "note_custom_type": "Dropoff Location",
    "root_owner_member_id": 1,
    "note_custom_type_values": [
        "Front door",
        "Backdoor",
        "Roof"
    ]
},
{
    "note_custom_type_id": 11,
    "note_custom_type": "Conditions at Site",
    "root_owner_member_id": 1,
    "note_custom_type_values": [
        "safe",
        "mild",
        "dangerous",
        "slippery"
    ]
}]

Vehicles

Route4Me gives you the ability to add new vehicles and assign them to a route.

See the Vehicle JSON Schema in our GitHub repository.


Get Vehicles

Get the vehicles that belong to a Route4Me account.


PARAMETERS

Parameter Type Description
api_key string API key of the user
show string A scope to get. Avaiable scopes are: pending, deleted, all and active (default)
search_query string Query string
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/v5.0/vehicles
SET apikey=11111111111111111111111111111111
SET show=active
SET search_query=Medium

:: The example refers to the process of getting a list of the vehicles.

ECHO ON

curl -o get_vehicles_RESPONSE.json -g -X GET -k "%url%?api_key=%apikey%&show=%show%&search_query=%search_query%"

timeout /t 30
#!/bin/bash

url=https://wh.route4me.com/modules/api/v5.0/vehicles
apikey=11111111111111111111111111111111
show=active
search_query=Medium

# The example refers to the process of getting a list of the vehicles.

curl -o get_vehicles_RESPONSE.json -g -X GET -k "$url?api_key=$apikey&show=$show&search_query=$search_query"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
public sealed partial class Route4MeExamples
{
	/// <summary>
	/// The example refers to the process of getting a list of the vehicles by their state using the API 5 endpoint.
	/// </summary>
	public void GetVehiclesByStateV5()
	{
		var route4Me = new Route4MeManagerV5(ActualApiKey);

		var vehicles = route4Me.GetVehiclesByState(VehicleStates.ACTIVE, out ResultResponse resultResponse);

		PrintTestVehcilesV5(vehicles, resultResponse);

		RemoveTestVehiclesV5();
	}
}
Public Function getVehiclesList() As VehiclesPaginated
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	
	Dim vehicleParameters As VehicleParameters = New VehicleParameters With {
		.WithPagination = True,
		.Page = 1,
		.PerPage = 10
	}
	
	Dim errorString As String = ""
	Dim vehicles As VehiclesPaginated = route4Me.GetVehicles(vehicleParameters, errorString)
	
	Assert.IsInstanceOfType(vehicles, GetType(VehiclesPaginated), "getVehiclesList failed... " & errorString)
	
	Return vehicles
End Function
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

// Example refers to getting all vehicles.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

$vehicleParameters = array(
        "with_pagination" => true,
        "page"            => 2,
        "perPage"         => 10
    );
    
$response = $vehicle->getVehicles($vehicleParameters);

foreach ($response['data'] as $key => $vehicle) {
    Route4Me::simplePrint($vehicle);
    echo "<br>";
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/vehicles?api_key=...


See the sample JSON response of this method.


Get a Vehicle

Get a vehicle by supplying a value in the endpoint’s vehicle_id path parameter.


PARAMETERS

Parameter Type Description HTTP Method
api_key string API key of the user GET
vehicle_id string Vehicle ID
(This is a path parameter.)
GET
An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/v5.0/vehicles
SET apikey=11111111111111111111111111111111
SET vehicle_id=AE350EF3153448665300F2C8216698C6

:: The example refers to the process of getting a vehicle by ID.

ECHO ON

curl -o get_vehicle_by_id_RESPONSE.json -g -X GET -k "%url%/%vehicle_id%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://wh.route4me.com/modules/api/v5.0/vehicles
apikey=11111111111111111111111111111111
vehicle_id=AE350EF3153448665300F2C8216698C6

# The example refers to the process of getting a vehicle by vehicle_id.

curl -o get_vehicle_by_id_RESPONSE.json -g -X GET -k "$url/$vehicle_id?api_key=$apikey"

echo "Finished..."

sleep 15
/// <summary>
/// The example refers to the process of getting a vehicle by ID using the API 5 endpoint.
/// </summary>
public void GetVehicleByIdV5()
{
	var route4Me = new Route4MeManagerV5(ActualApiKey);

	var vehicleData = route4Me.GetVehicleById(
		"FFBBFE7960518F7B4A79C5767C9B10CF",
		out ResultResponse resultResponse
	);

	PrintTestVehiclesV5(vehicleData, resultResponse);
}
Public Sub getVehicleTest()
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)

	Dim vehicleParameters As VehicleParameters = New VehicleParameters With {
		.VehicleId = lsVehicleIDs(lsVehicleIDs.Count - 1)
	}

	Dim errorString As String = ""
	Dim vehicles As VehicleV4Response = route4Me.GetVehicle(vehicleParameters, errorString)

	Assert.IsInstanceOfType(vehicles, GetType(VehicleV4Response), "getVehicleTest failed... " & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Example refers to getting a vehicle.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

// Get a random vehicle ID
$randomVehicleID = $vehicle->getRandomVehicleId(1, 20);
assert(!is_null($randomVehicleID), "Can't retrieve a random vehicle ID");

// Get a vehicle by ID
$vehicle = $vehicle->getVehicleByID($randomVehicleID);

Route4Me::simplePrint($vehicle);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/vehicles/{vehicle_id}?api_key=...

You can expect this API response:

{
	"vehicle_id": "AE350EF3153448665300F2C8216698C6",
	"member_id": 1,
	"is_deleted": false,
	"vehicle_alias": "Commercial Vehicle Medium Duty 4",
	"vehicle_vin": "WBADE6322VBW53333",
	"vehicle_reg_state_id": 4,
	"vehicle_reg_country_id": 223,
	"vehicle_license_plate": "CRL8474",
	"vehicle_type_id": "pickup_truck",
	"timestamp_added": "2022-10-13T17:56:06+00:00",
	"vehicle_make": "Ford",
	"vehicle_model_year": null,
	"vehicle_model": null,
	"vehicle_year_acquired": 2017,
	"vehicle_cost_new": null,
	"purchased_new": null,
	"license_start_date": "2022-07-29",
	"license_end_date": "2025-08-19",
	"is_operational": true,
	"fuel_type": "unleaded 87",
	"external_telematics_vehicle_id": null,
	"timestamp_removed": null,
	"vehicle_profile_id": 7889,
	"fuel_consumption_city": null,
	"fuel_consumption_highway": null,
	"vehicle_capacity_profile_id": null,
	"fuel_consumption_city_unit": "mi/l",
	"fuel_consumption_highway_unit": "mi/l",
	"mpg_city": null,
	"mpg_highway": null,
	"fuel_consumption_city_uf_value": "",
	"fuel_consumption_highway_uf_value": ""
}

Update a Vehicle

Updates a vehicle using the value passed in the endpoint’s vehicle_id path parameter.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP Method
api_key string API key of the user GET
vehicle_id string Vehicle ID
(This is a path parameter.)
GET
input data POST data A valid JSON object string. See the Vehicle JSON Schema as a guide. Payload
An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/v5.0/vehicles
SET apikey=11111111111111111111111111111111
SET vehicle_id=AE350EF3153448665300F2C8216698C6

:: The example refers to the process of updating a vehicle.

ECHO ON

curl -o update_vehicle_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X PATCH -k -d "@update_vehicle_data.json" "%url%/%vehicle_id%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://wh.route4me.com/modules/api/v5.0/vehicles
apikey=11111111111111111111111111111111
vehicle_id=AE350EF3153448665300F2C8216698C6

# The example refers to the process of updating a vehicle.

curl -o update_vehicle_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X PATCH -k -d "@update_vehicle_data.json" "$url/$vehicle_id?api_key=$apikey"

echo "Finished..."

sleep 15
/// <summary>
/// The example refers to the process of updating a vehicle using the API 5 endpoint.
/// </summary>
public void UpdateVehicleV5()
{
	var route4Me = new Route4MeManagerV5(ActualApiKey);

	var vehicleParams = new Vehicle()
	{
		VehicleId = "68F3545D3DA82DBF007B20FA9A1875EB",
		VehicleModelYear = 2015,
		VehicleYearAcquired = 2019
	};

	var vehicle = route4Me.UpdateVehicle(vehicleParams, out ResultResponse resultResponse);

	PrintTestVehiclesV5(vehicle, resultResponse);
}
Public Sub updateVehicleTest()
	If lsVehicleIDs.Count < 1 Then
		Dim newVehicle As VehicleV4Parameters = New VehicleV4Parameters() With {
			.VehicleAlias = "Ford Transit Test 6"
		}
		Dim vehicle As VehicleV4Response = createVehicle(newVehicle)
		lsVehicleIDs.Add(vehicle.VehicleId)
	End If

	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	
	Dim vehicleParams As VehicleV4Parameters = New VehicleV4Parameters() With {
		.VehicleId = lsVehicleIDs(lsVehicleIDs.Count - 1),
		.VehicleAlias = "Ford Transit Test 4",
		.VehicleModelYear = 1995,
		.VehicleRegCountryId = 223,
		.VehicleMake = "Ford",
		.VehicleAxleCount = 2,
		.MpgCity = 8,
		.MpgHighway = 14,
		.FuelType = "unleaded 93",
		.HeightInches = 72,
		.WeightLb = 2000
	}

	Dim errorString As String = ""
	Dim vehicles As VehicleV4Response = route4Me.updateVehicle(vehicleParams, errorString)

	Assert.IsInstanceOfType(vehicles, GetType(VehicleV4Response), "updateVehicleTest failed... " & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example refers to the process of updating a vehicle.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

// Get a random vehicle ID
$randomVehicleID = $vehicle->getRandomVehicleId(1, 20);
assert(!is_null($randomVehicleID), "Can't retrieve a random vehicle ID");

// Update the vehicle
$vehicleParameters = Vehicle::fromArray(array (
    'vehicle_id'             => $randomVehicleID,
    'vehicle_model_year'     => 2013,
    'vehicle_year_acquired'  => 2016,
    'vehicle_reg_country_id' => '223',
    'vehicle_make'           => 'Ford',
    'vehicle_axle_count'     => 3,
    'mpg_city'               => 11,
    'mpg_highway'            => 17,
    'fuel_type'              => 'unleaded 93',
    'height_inches'          => 74,
    'weight_lb'              => 2098
));

$result = $vehicle->updateVehicle($vehicleParameters);

assert(!is_null($result), "Can't update the vehicle");

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PATCH
/api/vehicles/{vehicle_id}?api_key=...

You can expect this API response:

{
	"vehicle_id": "AE350EF3153448665300F2C8216698C6",
	"member_id": 1,
	"is_deleted": false,
	"vehicle_alias": "Commercial Vehicle Medium Duty 4",
	"vehicle_vin": "WBADE6322VBW53333",
	"vehicle_reg_state_id": 4,
	"vehicle_reg_country_id": 223,
	"vehicle_license_plate": "CRL8474",
	"vehicle_type_id": "pickup_truck",
	"timestamp_added": "2022-10-13T17:56:06+00:00",
	"vehicle_make": "Ford",
	"vehicle_model_year": 2018,
	"vehicle_model": null,
	"vehicle_year_acquired": 2017,
	"vehicle_cost_new": null,
	"purchased_new": null,
	"license_start_date": "2022-07-29",
	"license_end_date": "2025-08-19",
	"is_operational": true,
	"fuel_type": "unleaded 87",
	"external_telematics_vehicle_id": null,
	"timestamp_removed": null,
	"vehicle_profile_id": 7889,
	"fuel_consumption_city": null,
	"fuel_consumption_highway": null,
	"vehicle_capacity_profile_id": null,
	"fuel_consumption_city_unit": "mi/l",
	"fuel_consumption_highway_unit": "mi/l",
	"mpg_city": null,
	"mpg_highway": null,
	"fuel_consumption_city_uf_value": "",
	"fuel_consumption_highway_uf_value": ""
}

Create a Vehicle

Creates a vehicle using the sent JSON payload.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description HTTP Method
api_key string API key of the user GET
input data POST data A valid JSON object string. See the Vehicle JSON Schema as a guide. Payload
An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/v5.0/vehicles
SET apikey=11111111111111111111111111111111

:: The example refers to the process of creating a new vehicle.

ECHO ON

curl -o create_new_vehicle_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_new_vehicle_data.json" "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://wh.route4me.com/modules/api/v5.0/vehicles
apikey=11111111111111111111111111111111

# The example refers to the process of creating a new vehicle.

curl -o create_new_vehicle_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_new_vehicle_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
/// <summary>
/// The example refers to the process of creating a vehicle using the API 5 endpoint.
/// </summary>
public void CreateVehicleV5()
{
	var route4Me = new Route4MeManagerV5(ActualApiKey);

	var vehicleParams = new Vehicle()
	{
		VehicleAlias = "Peterbilt 579",
		VehicleVin = "1NP5DB9X93N507873",
		VehicleLicensePlate = "PPV7516",
		VehicleModel = "579",
		VehicleModelYear = 2015,
		VehicleYearAcquired = 2018,
		VehicleRegCountryId = 223,
		VehicleMake = "Peterbilt",
		VehicleTypeId = "tractor_trailer",
		FuelType = "diesel"
	};

	var vehicle = route4Me.CreateVehicle(vehicleParams, out ResultResponse resultResponse);

	if (vehicle != null && vehicle.GetType() == typeof(Vehicle))
	{
		vehiclesToRemove = new System.Collections.Generic.List<string>();
		vehiclesToRemove.Add(vehicle.VehicleId);
	}

	PrintTestVehiclesV5(vehicle, resultResponse);
}
Public Sub CreatetVehicleTest()
	Dim commonVehicleParams As VehicleV4Parameters = New VehicleV4Parameters() With {
		.VehicleAlias = "Ford Transit Test 6"
	}
	
	Dim commonVehicle As VehicleV4Response = createVehicle(commonVehicleParams)
End Sub

Public Function createVehicle(ByVal vehicleParams As VehicleV4Parameters) As VehicleV4Response
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)

	Dim errorString As String = ""
	Dim result As VehicleV4Response = route4Me.CreateVehicle(vehicleParams, errorString)

	Assert.IsNotNull(result, "CreatetVehicleTest failed... " & errorString)

	Return result
End Function
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example refers to the process of creating a new vehicle.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

$vehicleParameters = Vehicle::fromArray(array (
    'vehicle_alias'          => 'Ford Transit Test 4',
    'vehicle_vin'            => 'JS3TD62V1Y4107898',
    'vehicle_reg_country_id' => '223',
    'vehicle_make'           => 'Ford',
    'vehicle_model_year'     => 2013,
    'vehicle_axle_count'     => 3,
    'mpg_city'               => 8,
    'mpg_highway'            => 14,
    'fuel_type'              => 'unleaded 93',
    'height_inches'          => 72,
    'weight_lb'              => 2000
));

$result = $vehicle->createVehicle($vehicleParameters);

assert(!is_null($result), "Can't update the vehicle");

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api/vehicles?api_key=...

You can expect this API response:

{
	"vehicle_alias": "Commercial Vehicle Medium Duty 4",
	"vehicle_vin": "WBADE6322VBW51984",
	"vehicle_reg_state_id": 4,
	"vehicle_reg_country_id": 223,
	"vehicle_license_plate": "CRL8474",
	"vehicle_type_id": "pickup_truck",
	"vehicle_make": "Ford",
	"license_start_date": "2022-07-29",
	"license_end_date": "2025-08-19",
	"is_operational": true,
	"fuel_type": "unleaded 87",
	"vehicle_profile_id": 76472,
	"fuel_consumption_city_unit": "km/l",
	"fuel_consumption_highway_unit": "km/l"
}

Remove a Vehicle

Removes a vehicle using the value passed in the endpoint’s vehicle_id path parameter.


PARAMETERS

Parameter Type Description HTTP Method
api_key string API key of the user GET
vehicle_id string Vehicle ID
(This is a path parameter.)
GET
An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/v5.0/vehicles
SET apikey=11111111111111111111111111111111
SET vehicle_id=AE350EF3153448665300F2C8216698C6

:: The example refers to the process of deleting a vehicle.

ECHO ON

curl -o delete_vehicle_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X DELETE -k "%url%/%vehicle_id%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://wh.route4me.com/modules/api/v5.0/vehicles
apikey=11111111111111111111111111111111
vehicle_id=AE350EF3153448665300F2C8216698C6

# The example refers to the process of deleting a vehicle.

curl -o delete_vehicle_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X DELETE -k "$url/$vehicle_id?api_key=$apikey"

echo "Finished..."

sleep 15
/// <summary>
/// The example refers to the process of removing a vehicle using the API 5 endpoint.
/// </summary>
public void DeleteVehicleV5()
{
	var route4Me = new Route4MeManagerV5(ActualApiKey);

	var vehicleData = route4Me.DeleteVehicle(
		"FFBBFE7960518F7B4A79C5767C9B10CF",
		out ResultResponse resultResponse
	);

	PrintTestVehiclesV5(vehicleData, resultResponse);
}
Public Sub deleteVehicleTest()
	If lsVehicleIDs.Count < 1 Then
		Dim newVehicle As VehicleV4Parameters = New VehicleV4Parameters() With {
			.VehicleAlias = "Ford Transit Test 6"
		}
		Dim vehicle As VehicleV4Response = createVehicle(newVehicle)
		lsVehicleIDs.Add(vehicle.VehicleId)
	End If

	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	Dim vehicleParams As VehicleV4Parameters = New VehicleV4Parameters() With {
		.VehicleId = lsVehicleIDs(lsVehicleIDs.Count - 1)
	}

	Dim errorString As String = ""
	Dim vehicles As VehicleV4Response = route4Me.deleteVehicle(vehicleParams, errorString)

	Assert.IsInstanceOfType(vehicles, GetType(VehicleV4Response), "updateVehicleTest failed... " & errorString)
	lsVehicleIDs.RemoveAt(lsVehicleIDs.Count - 1)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Example refers to removing a vehicle.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

// Get a random vehicle ID
$randomVehicleID = $vehicle->getRandomVehicleId(1, 20);
assert(!is_null($randomVehicleID), "Can't retrieve a random vehicle ID");

// Remove the vehicle
$vehicleParameters = Vehicle::fromArray(array (
    'vehicle_id'  => $randomVehicleID
));

$result = $vehicle->removeVehicle($vehicleParameters);

assert(!is_null($result), "Can't update the vehicle");

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api/vehicles/{vehicle_id}?api_key=...

You can expect this API response:

{
    "vehicle_id": "A730BAC4B6FDA9E39AD5B86E97C2131D",
    "member_id": 1,
    "is_deleted": true,
    "vehicle_alias": "Commercial Vehicle Medium Duty 4",
    "vehicle_vin": "WBADE6322VBW51984",
    "vehicle_reg_state_id": 4,
    "vehicle_reg_country_id": 223,
    "vehicle_license_plate": "CRL8474",
    "vehicle_type_id": "pickup_truck",
    "timestamp_added": "2023-03-02T14:34:14+00:00",
    "vehicle_make": "Ford",
    "vehicle_model_year": null,
    "vehicle_model": null,
    "vehicle_year_acquired": null,
    "vehicle_cost_new": null,
    "purchased_new": null,
    "license_start_date": "2022-07-29",
    "license_end_date": "2025-08-19",
    "is_operational": true,
    "fuel_type": "unleaded 87",
    "external_telematics_vehicle_id": null,
    "timestamp_removed": "2023-03-02T15:18:08+00:00",
    "vehicle_profile_id": 76472,
    "fuel_consumption_city": null,
    "fuel_consumption_highway": null,
    "vehicle_capacity_profile_id": null,
    "fuel_consumption_city_unit": "mpg",
    "fuel_consumption_highway_unit": "mpg",
    "mpg_city": null,
    "mpg_highway": null,
    "fuel_consumption_city_uf_value": "",
    "fuel_consumption_highway_uf_value": ""
}

Commercial Routing

Using the Route4Me API, you can create trucks in your account and optimize routes for trucking operations for different industries.

Trucks vary greatly in size, power, and configuration; smaller varieties, on the other hand, have a conventional configuration.

Commercial trucks can be huge and may be configured to mount specialized equipment, such as in the case of utility and fire trucks and concrete mixers and suction excavators. There are some features, which are essential in the trucking services: truck size, the presence of hazardous materials, trailer type and parameters, and local transportation rules for trucking.

These are the essential parameters for trucks:

Parameter Type Description
vehicle_type_id string Vehicle type. The allowed values are: “sedan”, “suv”, “pickup_truck”, “van”, “18wheeler”, “cabin”, “hatchback”, “motorcyle”, “waste_disposal”, “tree_cutting”, “bigrig”, “cement_mixer”, “livestock_carrier”, “dairy”, or “tractor_trailer”.
vehicle_axle_count integer The vehicle’s number of axles.
height_inches number Truck height measured in inches
has_trailer boolean If true, the truck has a trailer.
heightInInches number Vehicle height measured in inches
lengthInInches number Vehicle length measured in inches
widthInInches number Vehicle width measured in inches
maxWeightPerAxleGroupInPounds number The maximum weight per axle group in pounds.
HazmatType string The type of hazardous material contained inside the truck. The allowed values are: “INVALID”, “NONE”, “GENERAL”, “EXPLOSIVE”, “INHALANT”, “RADIOACTIVE”, “CAUSTIC”, “FLAMMABLE”, or “HARMFUL_TO_WATER”.
LowEmissionZonePref string Low emission zone preference. The allowed values are: “AVOID”, “ALLOW”, or “WARN”.
Use53FootTrailerRouting string Use 53-foot trailer routing
UseNationalNetwork string Allow the use of the networked state highways and interstates for commercial truck drivers in the USA. The allowed values are “YES” or “NO”.
UseTruckRestrictions string Use truck restrictions. The allowed values are “YES” or “NO”.
AvoidFerries string Avoid routes that include ferries. The allowed values are “YES” or “NO”.
DividedHighwayAvoidPreference string Preference for avoiding divided highways. The allowed values are: “STRONG_AVOID”, “AVOID”, “NEUTRAL”, “FAVOR”, or “STRONG_FAVOR”.
FreewayAvoidPreference string Preference for avoiding freeways. The allowed values are “STRONG_AVOID”, “AVOID”, “NEUTRAL”, “FAVOR”, or “STRONG_FAVOR”.
TollRoadUsage string Preference for avoiding toll roads. The allowed values are: “ALWAYS_AVOID”, “IF_NECESSARY”, or “NO_RESTRICTION”.
hwy_only boolean If true, the vehicle uses highways only.
long_combination_vehicle boolean If true, the vehicle is a long combination vehicle.
truck_config string Truck configuration. The allowed values are: “NONE”, “PASSENGER”, “28_DOUBLETRAILER”, “48_STRAIGHT_TRUCK”, “48_SEMI_TRAILER”, “53_SEMI_TRAILER”, “FULLSIZEVAN”, or “26_STRAIGHT_TRUCK”.
height_metric number Truck height in metric unit
length_metric number Vehicle length in metric unit
width_metric number Vehicle width in metric unit
max_weight_per_axle_group_metric number Maximum weight per axle group in metric unit

The commercial truck classification is determined based on the vehicle’s gross vehicle weight rating (GVWR):

The following sections below provide an example for each classification. *******

Light Truck

Light truck or light-duty truck is a classification for trucks or truck-based vehicles with a gross vehicle weight of up to 8,500 lb (3,860 kg) and a payload capacity of up to 4,000 lb (1,815 kg). Some good examples are the Toyota Tacoma, Ford Excursion, and Ford F-350 models.

See the sample input JSON data for this method.

An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/vehicles
SET apikey=11111111111111111111111111111111

:: This example refers to the process of creating a light truck, class 2.

ECHO ON

curl -o create_light_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_light_truck_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://wh.route4me.com/modules/api/vehicles
apikey=11111111111111111111111111111111

 # This example refers to the process of creating a light truck, class 2.

curl -o create_light_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_light_truck_data.json" "$url$vehicleid?api_key=$apikey"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Example refers to creating a light class truck.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

$vehicleParameters = Vehicle::fromArray(array (
    'vehicle_alias'                    => 'GMC TopKick C5500 Light',
    'vehicle_vin'                      => 'SAJXA01A06FN08012',
    'vehicle_license_plate'            => 'CVH4561',
    'vehicle_model'                    => 'TopKick C5500',
    'vehicle_model_year'               => 1995,
    'vehicle_year_acquired'            => 2008,
    'vehicle_reg_country_id'           => '223',
    'vehicle_make'                     => 'GMC',
    'vehicle_type_id'                  => 'pickup_truck',
    'vehicle_axle_count'               => 2,
    'mpg_city'                         => 7,
    'mpg_highway'                      => 14,
    'fuel_type'                        => 'diesel',
    'height_inches'                    => 97,
    'height_metric'                    => 243,
    'weight_lb'                        => 19000,
    'maxWeightPerAxleGroupInPounds'    => 9500,
    'max_weight_per_axle_group_metric' => 4300,
    'widthInInches'                    => 96,
    'width_metric'                     => 240,
    'lengthInInches'                   => 244,
    'length_metric'                    => 610,
    'Use53FootTrailerRouting'          => 'NO',
    'UseTruckRestrictions'             => 'NO',
    'DividedHighwayAvoidPreference'    => 'NEUTRAL',
    'FreewayAvoidPreference'           => 'NEUTRAL',
    'truck_config'                     => 'FULLSIZEVAN',
));

$result = $vehicle->createVehicle($vehicleParameters);

assert(!is_null($result), "Can't update the vehicle");

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api/vehicles?api_key=...

You can expect this API response:

{
  "vehicle_alias": "Ford Excursion",
  "vehicle_vin": "1HGCG554XWA883434",
  "vehicle_license_plate": "FEX6245",
  "vehicle_model": "Ford Excursion",
  "vehicle_model_year": 2005,
  "vehicle_year_acquired": 2005,
  "vehicle_reg_country_id": "223",
  "vehicle_make": "Ford",
  "vehicle_type_id": "pickup_truck",
  "vehicle_axle_count": 2,
  "mpg_city": 6,
  "mpg_highway": 12,
  "fuel_type": "diesel",
  "height_inches": 77,
  "height_metric": 193,
  "weight_lb": 9200,
  "maxWeightPerAxleGroupInPounds": 4600,
  "max_weight_per_axle_group_metric": 4600,
  "widthInInches": 80,
  "width_metric": 200,
  "lengthInInches": 227,
  "length_metric": 567,
  "Use53FootTrailerRouting": "YES",
  "UseTruckRestrictions": "YES",
  "DividedHighwayAvoidPreference": "NEUTRAL",
  "FreewayAvoidPreference": "NEUTRAL",
  "truck_config": "FULLSIZEVAN",
  "member_id": 1,
  "vehicle_id": "64788FBD0C4BBA3B69D07EC3F947C190",
  "timestamp_added": "2018-10-18T15:38:31-04:00"
}

Medium Truck

Medium truck or medium-duty truck is a classification for trucks or truck-based vehicles with a gross vehicle weight in the range of 14,001–26,000 lb (6,351–11,793 kg). A medium truck can be a box truck, van, cutaway van chassis, platform truck, flatbed truck, stake bed truck, fire truck (may also be a heavy truck), or a recreational vehicle.

See the sample input JSON data for this method.

An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/vehicles
SET apikey=11111111111111111111111111111111

:: This example refers to the process of creating a medium truck, class 6.

ECHO ON

curl -o create_medium_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_medium_truck_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://wh.route4me.com/modules/api/vehicles
apikey=11111111111111111111111111111111

 # This example refers to the process of creating a medium truck, class 6.

curl -o create_medium_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_medium_truck_data.json" "$url$vehicleid?api_key=$apikey"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Example refers to creating a medium class truck.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

$vehicleParameters = Vehicle::fromArray(array (
    'vehicle_alias'                    => 'GMC TopKick C5500 Medium',
    'vehicle_vin'                      => 'SAJXA01A06FN08012',
    'vehicle_license_plate'            => 'CVH4561',
    'vehicle_model'                    => 'TopKick C5500',
    'vehicle_model_year'               => 1995,
    'vehicle_year_acquired'            => 2008,
    'vehicle_reg_country_id'           => '223',
    'vehicle_make'                     => 'GMC',
    'vehicle_type_id'                  => 'pickup_truck',
    'vehicle_axle_count'               => 2,
    'mpg_city'                         => 7,
    'mpg_highway'                      => 14,
    'fuel_type'                        => 'diesel',
    'height_inches'                    => 97,
    'height_metric'                    => 243,
    'weight_lb'                        => 19000,
    'maxWeightPerAxleGroupInPounds'    => 9500,
    'max_weight_per_axle_group_metric' => 4300,
    'widthInInches'                    => 96,
    'width_metric'                     => 240,
    'lengthInInches'                   => 244,
    'length_metric'                    => 610,
    'Use53FootTrailerRouting'          => 'YES',
    'UseTruckRestrictions'             => 'YES',
    'DividedHighwayAvoidPreference'    => 'NEUTRAL',
    'FreewayAvoidPreference'           => 'NEUTRAL',
    'truck_config'                     => 'FULLSIZEVAN',
));

$result = $vehicle->createVehicle($vehicleParameters);

assert(!is_null($result), "Can't update the vehicle");

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api/vehicles?api_key=...

You can expect this API response:

{
  "vehicle_alias": "GMC TopKick C5500",
  "vehicle_vin": "SAJXA01A06FN08012",
  "vehicle_license_plate": "CVH4561",
  "vehicle_model": "TopKick C5500",
  "vehicle_model_year": 1995,
  "vehicle_year_acquired": 2008,
  "vehicle_reg_country_id": "223",
  "vehicle_make": "GMC",
  "vehicle_type_id": "pickup_truck",
  "vehicle_axle_count": 2,
  "mpg_city": 7,
  "mpg_highway": 14,
  "fuel_type": "diesel",
  "height_inches": 97,
  "height_metric": 243,
  "weight_lb": 19000,
  "maxWeightPerAxleGroupInPounds": 9500,
  "max_weight_per_axle_group_metric": 4300,
  "widthInInches": 96,
  "width_metric": 240,
  "lengthInInches": 244,
  "length_metric": 610,
  "Use53FootTrailerRouting": "YES",
  "UseTruckRestrictions": "YES",
  "DividedHighwayAvoidPreference": "NEUTRAL",
  "FreewayAvoidPreference": "NEUTRAL",
  "truck_config": "FULLSIZEVAN",
  "member_id": 1,
  "vehicle_id": "2BB425F4D3300377FD74D58D6295B4DD",
  "timestamp_added": "2018-08-14T09:21:16-04:00"
}

Heavy Truck

The heavy truck or heavy-duty truck is a classification for trucks or truck-based vehicles with a gross vehicle weight of over 26,000 lb (11,793 kg). Heavy trucks are the most massive on-road trucks, and some good examples are semi-trailer trucks, mobile cranes, refrigerator trucks, log carriers, vocational applications such as heavy dump trucks, concrete pump trucks, and refuse hauling, as well as ubiquitous long-haul 4x2 and 6x4 tractor units.

See the sample input JSON data for this method.

An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/vehicles
SET apikey=11111111111111111111111111111111

:: This example refers to the process of creating a heavy truck, class 8.

ECHO ON

curl -o create_heavy_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_heavy_truck_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://wh.route4me.com/modules/api/vehicles
apikey=11111111111111111111111111111111

 # This example refers to the process of creating a heavy truck, class 8.

curl -o create_heavy_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_heavy_truck_data.json" "$url$vehicleid?api_key=$apikey"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Example refers to creating a heavy class truck.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

$vehicleParameters = Vehicle::fromArray(array (
    'vehicle_alias'                    => 'Peterbilt 579',
    'vehicle_vin'                      => '1NP5DB9X93N507873',
    'vehicle_license_plate'            => 'PPV7516',
    'license_start_date'               => '2017-06-05',
    'license_end_date'                 => '2021-08-14',
    'vehicle_model'                    => '579',
    'vehicle_model_year'               => 2015,
    'vehicle_year_acquired'            => 2018,
    'vehicle_reg_country_id'           => '223',
    'vehicle_make'                     => 'Peterbilt',
    'vehicle_type_id'                  => 'tractor_trailer',
    'has_trailer'                      => true,
    'vehicle_axle_count'               => 5,
    'mpg_city'                         => 6,
    'mpg_highway'                      => 12,
    'fuel_type'                        => 'diesel',
    'height_inches'                    => 114,
    'height_metric'                    => 290,
    'weight_lb'                        => 50350,
    'maxWeightPerAxleGroupInPounds'    => 40000,
    'max_weight_per_axle_group_metric' => 18000,
    'widthInInches'                    => 102,
    'width_metric'                     => 258,
    'lengthInInches'                   => 640,
    'length_metric'                    => 1625,
    'Use53FootTrailerRouting'          => 'YES',
    'UseTruckRestrictions'             => 'YES',
    'DividedHighwayAvoidPreference'    => 'STRONG_AVOID',
    'FreewayAvoidPreference'           => 'STRONG_AVOID',
    'truck_config'                     => '53_SEMI_TRAILER',
    'InternationalBordersOpen'         => 'YES',
    'purchased_new'                    => true
));

$result = $vehicle->createVehicle($vehicleParameters);

assert(!is_null($result), "Can't update the vehicle");

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api/vehicles?api_key=...

You can expect this API response:

{
  "vehicle_alias": "Peterbilt 579",
  "vehicle_vin": "1NP5DB9X93N507873",
  "vehicle_license_plate": "PPV7516",
  "license_start_date": "2017-06-05",
  "license_end_date": "2021-08-14",
  "vehicle_model": "579",
  "vehicle_model_year": 2015,
  "vehicle_year_acquired": 2018,
  "vehicle_reg_country_id": "223",
  "vehicle_make": "Peterbilt",
  "vehicle_type_id": "tractor_trailer",
  "has_trailer": true,
  "vehicle_axle_count": 5,
  "mpg_city": 6,
  "mpg_highway": 12,
  "fuel_type": "diesel",
  "height_inches": 114,
  "height_metric": 290,
  "weight_lb": 50350,
  "maxWeightPerAxleGroupInPounds": 40000,
  "max_weight_per_axle_group_metric": 18000,
  "widthInInches": 102,
  "width_metric": 258,
  "lengthInInches": 640,
  "length_metric": 1625,
  "Use53FootTrailerRouting": "YES",
  "UseTruckRestrictions": "YES",
  "DividedHighwayAvoidPreference": "STRONG_FAVOR",
  "FreewayAvoidPreference": "STRONG_AVOID",
  "truck_config": "53_SEMI_TRAILER",
  "TollRoadUsage": "ALWAYS_AVOID",
  "InternationalBordersOpen": "YES",
  "purchased_new": true,
  "member_id": 1,
  "vehicle_id": "DABA9B99B9EF691BF6064002B06B2533",
  "timestamp_added": "2018-10-19T03:49:07-04:00"
}

Super-heavy Truck

These are trucks that are considered heavy-duty and are too large for highway use without escorts and special permits. Examples are the ALMA transporter, ballast tractor, heavy hauler, and haul truck.

See the sample input JSON data for this method.

An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/vehicles
SET apikey=11111111111111111111111111111111

:: This example refers to the process of creating a super-heavy truck, class 9.

ECHO ON

curl -o create_super_heavy_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_super_heavy_truck_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://wh.route4me.com/modules/api/vehicles
apikey=11111111111111111111111111111111

 # This example refers to the process of creating a super-heavy truck, class 9.

curl -o create_super_heavy_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_super_heavy_truck_data.json" "$url$vehicleid?api_key=$apikey"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Example refers to creating a super-heavy class truck.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

$vehicleParameters = Vehicle::fromArray(array (
    'vehicle_alias'                    => 'Liebherr T 282B mining truck',
    'vehicle_vin'                      => '1NP5DB9X93N507873',
    'vehicle_license_plate'            => 'LMT8765',
    'license_start_date'               => '2008-04-12',
    'license_end_date'                 => '2020-08-16',
    'vehicle_model'                    => 'Liebherr T 282B',
    'vehicle_model_year'               => 2004,
    'vehicle_year_acquired'            => 2008,
    'vehicle_reg_country_id'           => '223',
    'vehicle_type_id'                  => 'bigrig',
    'has_trailer'                      => false,
    'vehicle_axle_count'               => 2,
    'mpg_city'                         => 2,
    'mpg_highway'                      => 4,
    'fuel_type'                        => 'diesel',
    'height_inches'                    => 596,
    'height_metric'                    => 1490,
    'weight_lb'                        => 1316000,
    'maxWeightPerAxleGroupInPounds'    => 658000,
    'max_weight_per_axle_group_metric' => 298450,
    'widthInInches'                    => 381,
    'width_metric'                     => 952,
    'lengthInInches'                   => 613,
    'length_metric'                    => 1532,
    'Use53FootTrailerRouting'          => 'YES',
    'UseTruckRestrictions'             => 'YES',
    'DividedHighwayAvoidPreference'    => 'STRONG_AVOID',
    'FreewayAvoidPreference'           => 'STRONG_AVOID',
    'truck_config'                     => '53_SEMI_TRAILER',
    'InternationalBordersOpen'         => 'YES',
    'purchased_new'                    => true
));

$result = $vehicle->createVehicle($vehicleParameters);

assert(!is_null($result), "Can't update the vehicle");

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api/vehicles?api_key=...

You can expect this API response:

{
  "vehicle_alias": "Liebherr T 282B mining truck",
  "vehicle_vin": "1NP5DB9X93N507873",
  "vehicle_license_plate": "LMT8765",
  "license_start_date": "2008-04-12",
  "license_end_date": "2020-08-16",
  "vehicle_model": "Liebherr T 282B",
  "vehicle_model_year": 2004,
  "vehicle_year_acquired": 2008,
  "vehicle_reg_country_id": "223",
  "vehicle_type_id": "bigrig",
  "has_trailer": false,
  "vehicle_axle_count": 2,
  "mpg_city": 220,
  "mpg_highway": 132,
  "fuel_type": "diesel",
  "height_inches": 596,
  "height_metric": 1490,
  "weight_lb": 1316000,
  "maxWeightPerAxleGroupInPounds": 658000,
  "max_weight_per_axle_group_metric": 298450,
  "widthInInches": 381,
  "width_metric": 596900,
  "lengthInInches": 613,
  "length_metric": 1532,
  "Use53FootTrailerRouting": "YES",
  "UseTruckRestrictions": "YES",
  "DividedHighwayAvoidPreference": "STRONG_AVOID",
  "FreewayAvoidPreference": "STRONG_AVOID",
  "truck_config": "53_SEMI_TRAILER",
  "TollRoadUsage": "ALWAYS_AVOID",
  "InternationalBordersOpen": "YES",
  "purchased_new": true,
  "member_id": 1,
  "vehicle_id": "4654F1D7083CF7F7F2207C7CC3E19FB5",
  "timestamp_added": "2018-10-19T08:07:00-04:00"
}

Hazmat Truck

A typical hazmat vehicle has a command and communications center. Often fitted with computers, televisions, two-way radios and other equipment. This command center is usually located in a portion of the vehicle that slides out or expands.

Also, hazmat vehicles often come with a portable lab that allows for the analysis of samples collected at the scene. Early on-site scientific analysis and monitoring speed up the detection process and provide the correct response for the particular incident.

See the sample input JSON data for this method.

An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://wh.route4me.com/modules/api/vehicles
SET apikey=11111111111111111111111111111111

:: This example refers to the process of creating a hazmat truck.

ECHO ON

curl -o create_hazmat_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_hazmat_truck_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://wh.route4me.com/modules/api/vehicles
apikey=11111111111111111111111111111111

 # This example refers to the process of creating a super-heavy truck, class 9.

curl -o create_super_heavy_truck_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -X POST -k -d "@create_super_heavy_truck_data.json" "$url$vehicleid?api_key=$apikey"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Vehicle;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Example refers to creating a hazmat class truck.

// Set the API key in the Route4Me class.
Route4Me::setApiKey('11111111111111111111111111111111');

$vehicle = new Vehicle();

$vehicleParameters = Vehicle::fromArray(array (
    'vehicle_alias'                    => 'ISUZU FTR',
    'vehicle_vin'                      => '1NP5DB9X93N507873',
    'vehicle_license_plate'            => 'IFT6253',
    'license_start_date'               => '2008-05-14',
    'license_end_date'                 => '2020-09-24',
    'vehicle_model'                    => 'FTR',
    'vehicle_model_year'               => 2008,
    'vehicle_year_acquired'            => 2008,
    'vehicle_reg_country_id'           => '223',
    'vehicle_type_id'                  => 'bigrig',
    'has_trailer'                      => false,
    'vehicle_axle_count'               => 2,
    'mpg_city'                         => 5,
    'mpg_highway'                      => 15,
    'fuel_type'                        => 'diesel',
    'height_inches'                    => 112,
    'height_metric'                    => 280,
    'weight_lb'                        => 25950,
    'maxWeightPerAxleGroupInPounds'    => 19000,
    'max_weight_per_axle_group_metric' => 8620,
    'widthInInches'                    => 94,
    'width_metric'                     => 235,
    'lengthInInches'                   => 384,
    'length_metric'                    => 960,
    'Use53FootTrailerRouting'          => 'NO',
    'UseTruckRestrictions'             => 'YES',
    'DividedHighwayAvoidPreference'    => 'NEUTRAL',
    'FreewayAvoidPreference'           => 'NEUTRAL',
    'TollRoadUsage'                    => 'ALWAYS_AVOID',
    'truck_config'                     => '26_STRAIGHT_TRUCK',
    'InternationalBordersOpen'         => 'YES',
    'purchased_new'                    => true,
    'HazmatType'                       => 'FLAMMABLE'
));

$result = $vehicle->createVehicle($vehicleParameters);

assert(!is_null($result), "Can't update the vehicle");

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api/vehicles?api_key=...

You can expect this API response:

{
  "vehicle_alias": "ISUZU FTR",
  "vehicle_vin": "1NP5DB9X93N507873",
  "vehicle_license_plate": "IFT6253",
  "license_start_date": "2008-05-14",
  "license_end_date": "2020-09-24",
  "vehicle_model": "FTR",
  "vehicle_model_year": 2008,
  "vehicle_year_acquired": 2008,
  "vehicle_reg_country_id": "223",
  "vehicle_type_id": "bigrig",
  "has_trailer": false,
  "vehicle_axle_count": 2,
  "mpg_city": 25,
  "mpg_highway": 15,
  "fuel_type": "diesel",
  "height_inches": 112,
  "height_metric": 280,
  "weight_lb": 25950,
  "maxWeightPerAxleGroupInPounds": 19000,
  "max_weight_per_axle_group_metric": 8620,
  "widthInInches": 94,
  "width_metric": 235,
  "lengthInInches": 384,
  "length_metric": 960,
  "Use53FootTrailerRouting": "YES",
  "UseTruckRestrictions": "YES",
  "DividedHighwayAvoidPreference": "NEUTRAL",
  "FreewayAvoidPreference": "NEUTRAL",
  "truck_config": "26_STRAIGHT_TRUCK",
  "TollRoadUsage": "ALWAYS_AVOID",
  "InternationalBordersOpen": "YES",
  "purchased_new": true,
  "HazmatType": "FLAMMABLE",
  "member_id": 1,
  "vehicle_id": "B7DB6E37E72BA8A3A9D631B2E44497FF",
  "timestamp_added": "2018-10-20T08:40:01-04:00"
}

Activity Feed

The activity feed displays all routing activities on your account, such as route modifications, note additions or driver progress.

For VBScript (WSH) examples, you should place the Route4Me.vbs file in its appropriate folder as referred to in the examples.

Activity Feed Properties

Attribute Type Description
route_id string Route ID
route_destination_id integer Route destination ID
member_id integer Member ID
note_id string Note ID
note_attachment_url string The URL of the uploaded note.
activity_type string Activity type
activity_id string Activity ID
activity_timestamp string The timestamp (in Epoch format) when the activity occurred.
activity_message string Activity message

Get All Activities

Get all recorded activities associated with a specific Route4Me account. Limit the search results using the limit and offset parameters.


PARAMETERS

Parameter Type Description
api_key string API key of the user
offset integer Search starting position
limit integer The number of records to return.
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET offset=0
SET limit=20

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&offset=%offset%&limit=%limit%"

timeout /t 30
<job id="Get Activities All">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      offset="0"
      limit="20"
      
      url=url&"?api_key="&apikey
      url=url&"&offset="&offset
      url=url&"&limit="&limit
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
offset=0
limit=20

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&offset=$offset&limit=$limit"

echo "Finished..."

sleep 15
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityParameters = ActivityParameters::fromArray(array(
    "limit"  => 10,
    "offset" => 0
));

$activities = new ActivityParameters();
$actresults = $activities->getActivities($activityParameters);
$results = $activities->getValue($actresults, "results");

foreach ($results as $result) {
    Route4Me::simplePrint($result);
    echo "<br>";
}
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetActivities(string routeId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      ActivityParameters activityParameters = new ActivityParameters()
      {
        RouteId = routeId,
        Limit = 10,
        Offset = 0
      };

      // Run the query
      string errorString;
      Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

      Console.WriteLine("");

      if (activities != null)
      {
        Console.WriteLine("GetActivities executed successfully, {0} activities returned", activities.Length);
        Console.WriteLine("");

        activities.ForEach(activity =>
        {
          Console.WriteLine("Activity ID: {0}", activity.ActivityId);
        });
        Console.WriteLine("");
      }
      else
      {
        Console.WriteLine("GetActivities error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetActivities(routeId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .RouteId = routeId, _
                .Limit = 10, _
                .Offset = 0 _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("GetActivities executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("GetActivities error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    response = activity_feed.get_activities_feed(limit=10, offset=0)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Total Found: {}'.format(response.total)
        for i, activity in enumerate(response.results):
            print 'Activity #{}'.format(i + 1)
            print '\tActivity ID: {}'.format(activity.activity_id)
            print '\tActivity Message: {}'.format(activity.activity_message)
            print '\tActivity Type: {}'.format(activity.activity_type)
            print '\tRoute ID: {}'.format(activity.route_id)
            print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.Activity;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.routing.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

public class GetActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        RoutingManager routeManager = new RoutingManager(apiKey);
        try {
            List<Route> routes = routeManager.getRoutes(new RoutesRequest().setLimit(10));
            String routeID = routes.get(2).getId();
            System.out.println("Getting Activities for Route ID: " + routeID);
            Activities responseObject = manager.getActivities(new ActivityRequest().setLimit(10).setRouteId(routeID));
            System.out.println("Total Activities: " + responseObject.getTotal());
            for (Activity activity : responseObject.getResults()) {
                System.out.println(activity);
            }
        } catch (APIException e) {
            // Handle error
            e.printStackTrace();
        }
    }
}
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{RouteID:"route-id"})
  if err != nil {
    t.Error(err)
  }
  // do something with activities, it's []Activity
}
package GetActivities;
use strict;
use warnings FATAL => 'all';
sub GetActivities {

    my ($self, $routeId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $activityParameters = ActivityParameters->new( {
            route_id => $routeId,
            limit => 10,
            offset => 0
        } );

    my $errorString = "";

    my $dataObject = $route4Me->getActivities( $activityParameters, \$errorString );

    print "\n";

    if ($dataObject) {
        printf "GetActivities executed successfully, %s activities returned\n\n", scalar @{$dataObject->results};

        foreach my $activity (@{$dataObject->results}) {
            printf "Activity ID: %s\n", $activity->activity_id;
        }

    } else {
        printf "GetActivities error: %s\n", $errorString;
    }
}
1;
unit GetAllActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAllActivities = class(TBaseExample)
  public
    procedure Execute(Limit, Offset: integer);
  end;

implementation

uses ActivityUnit;

procedure TGetAllActivities.Execute(Limit, Offset: integer);

var
  ErrorString: String;
  Activities: TActivityList;
  Activity: TActivity;
  Total: integer;
begin
  Activities := Route4MeManager.ActivityFeed.GetAllActivities(
    Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (Activities <> nil) and (Activities.Count > 0) then
    begin
      WriteLn(Format('GetActivities executed successfully, %d activities returned',
        [Activities.Count]));
      WriteLn('');

      for Activity in Activities do
        WriteLn(Format('Activity ID: %s', [Activity.Id.Value]));

      WriteLn('');
    end
    else
      WriteLn(Format('GetActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";

    int ret = route.get_all_activities();
    if (ret == 0)
        cout << "Activities: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "No activities: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 1);
    struct Limit limit = {5,10};

    if (!get_all_activities(&limit))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api/get_activities.php?api_key=...&offset=...&limit=...


See the sample JSON response of this method.


Get Team Activities on a Route

Get all recorded activities associated with a specific Route4Me account, including the activities of its team members.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
team string If set to “true”, team activities will be included.
<job id="Get Team Activities on a Route">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      route_id="06B655F27E0D6A74BD37F6F9758E4D2E"
      team="true"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&route_id
      url=url&"&team="&team
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET route_id=06B655F27E0D6A74BD37F6F9758E4D2E
SET team=true

:: The example demonstrates the process of getting team activities on a route.

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&route_id=%route_id%&team=%team%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
route_id=06B655F27E0D6A74BD37F6F9758E4D2E
team=true

# The example demonstrates the process of getting team activities on a route.

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&route_id=$route_id&team=$team&"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Team Activities on a Route
        /// </summary>
        public void GetRouteTeamActivities()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            string routeId = "06B655F27E0D6A74BD37F6F9758E4D2E";

            ActivityParameters activityParameters = new ActivityParameters
            {
                RouteId = routeId,
                Team = "true"
            };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("GetActivities executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("GetActivities error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetRouteTeamActivities()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim routeId As String = "06B655F27E0D6A74BD37F6F9758E4D2E"

            Dim activityParameters As New ActivityParameters() With { _
                .RouteId = routeId, _
                .team = "true" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("GetActivities executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("GetActivities error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
    activities, err := service.Get(&activity.Query{
        Team:    true,
        RouteID: "06B655F27E0D6A74BD37F6F9758E4D2E",
    })
    if err != nil {
        // handle error
    }
    // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$routeId = $route->getRandomRouteId(0, 10);

assert(!is_null($routeId), "Can't retrieve random route_id");

$activityParameters = ActivityParameters::fromArray(array(
    "route_id"   => $routeId,
    "team"       => "true"
));

$activities = new ActivityParameters();
$actresults = $activities->getActivities($activityParameters);
$results = $activities->getValue($actresults, "results");

foreach ($results as $result) {
  Route4Me::simplePrint($result);
    echo "<br>";
}
unit GetTeamActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetTeamActivities = class(TBaseExample)
  public
    procedure Execute(RouteId: String; Limit, Offset: integer);
  end;

implementation

uses ActivityUnit;

procedure TGetTeamActivities.Execute(RouteId: String; Limit, Offset: integer);

var
  ErrorString: String;
  Activities: TActivityList;
  Activity: TActivity;
  Total: integer;
begin
  Activities := Route4MeManager.ActivityFeed.GetTeamActivities(
    RouteId, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (Activities <> nil) and (Activities.Count > 0) then
    begin
      WriteLn(Format('GetActivities executed successfully, %d activities returned',
        [Activities.Count]));
      WriteLn('');

      for Activity in Activities do
        WriteLn(Format('Activity ID: %s', [Activity.Id.Value]));

      WriteLn('');
    end
    else
      WriteLn(Format('GetActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";

    int ret = route.get_team_activities(route_id);

    if (ret == 0)
        cout << "Activities by team: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "No activities by team: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    const char *route_id = "CA902292134DBC134EAF8363426BD247";
    init(key, 1);

    if (!get_team_activities(route_id, "sf"))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api/get_activities.php?api_key=...&route_id=...&team=true


See the sample JSON response of this method.


Get Last Activities

Get the last activities recorded after a specified date.


PARAMETERS

Parameter Type Description
api_key string API key of the user
offset integer Search starting position
limit integer The number of records to return.
start integer The time in Epoch format.
<job id="Get Activities All">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example demonstrates the process of getting all activities recorded after the specified time.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      offset="0"
      limit="20"
      start="1495238400"
      
      url=url&"?api_key="&apikey
      url=url&"&offset="&offset
      url=url&"&limit="&limit
      url=url&"&start="&start
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET offset=0
SET limit=20
SET start=1495238400

ECHO ON
curl -o file1.txt -g -k -X GET "%url%?api_key=%apikey%&offset=%offset%&limit=%limit%&start=%start%"

timeout /t 30
#!/bin/bash

# The example demonstrates the process of getting all activities recorded after the specified time.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
offset=0
limit=20
start=1495238400

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&offset=$offset&limit=$limit&start=$start"

echo "Finished..."

sleep 15
public void GetLastActivities()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	DateTime activitiesAfterTime = DateTime.Now - (new TimeSpan(7, 0, 0, 0));

	activitiesAfterTime = new DateTime(activitiesAfterTime.Year, activitiesAfterTime.Month, activitiesAfterTime.Day, 0, 0, 0);

	uint uiActivitiesAfterTime = (uint)Route4MeSDK.R4MeUtils.ConvertToUnixTimestamp(activitiesAfterTime);

	ActivityParameters activityParameters = new ActivityParameters()
	{
		Limit = 10,
		Offset = 0,
		Start = uiActivitiesAfterTime
	};

	// Run the query
	string errorString;
	Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

	foreach (Activity activity in activities)
	{
		uint activityTime = activity.ActivityTimestamp!=null ? (uint)activity.ActivityTimestamp : 0;
		Assert.IsTrue(activityTime >= uiActivitiesAfterTime, "GetLastActivities failed. "+ errorString);
	}

}
Public Sub GetLastActivitiesTest()
	Dim route4Me As New Route4MeManager(c_ApiKey)

	Dim activitiesAfterTime As DateTime = DateTime.Now - (New TimeSpan(7, 0, 0, 0))
	activitiesAfterTime = New DateTime(activitiesAfterTime.Year, activitiesAfterTime.Month, activitiesAfterTime.Day, 0, 0, 0)
	Dim uiActivitiesAfterTime As UInteger = CUInt(Route4MeSDKLibrary.Route4MeSDK.R4MeUtils.ConvertToUnixTimestamp(activitiesAfterTime))

	Dim activityParameters As New ActivityParameters() With { _
		.Limit = 10, _
		.Offset = 0, _
		.Start = 0 _
	}

	' Run the query
	Dim errorString As String = ""
	Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

	For Each activity As Activity In activities
		Dim activityTime As UInteger = If(activity.ActivityTimestamp IsNot Nothing, CUInt(activity.ActivityTimestamp), 0)
		Assert.IsTrue(activityTime >= uiActivitiesAfterTime, "GetLastActivities failed. " & errorString)
	Next

End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
  "github.com/route4me/route4me-go-sdk"
  "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
  client := route4me.NewClient("your-api-key")
  service := &activity.Service{Client: client}
  activities, err := service.Get(
    &activity.Query{
      RouteID:"route-id",
      Start: 1495238400, //Start is a timestamp
    }
  }
  if err != nil {
    t.Error(err)
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// The example demonstrates the process of getting all activities recorded after the specified time.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityParameters = ActivityParameters::fromArray(array(
    "limit"  => 10,
    "offset" => 0,
    "start"  => strtotime("-1 week")
));

$activities = new ActivityParameters();
$actresults = $activities->getActivities($activityParameters);
$results = $activities->getValue($actresults, "results");

foreach ($results as $result) {
    Route4Me::simplePrint($result);
    echo "<br>";
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&limit=...&start


See the sample JSON response of this method.


Log a Specific Message

Permanently store a specific message directly to the activity feed. A good use case for this method is to use it as part of a one or two-way chat solution.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type. In this case, it should be “user_message”.
activity_message string The message or text to log into the activity feed.
route_id string Route ID
@ECHO OFF

SET url=https://api.route4me.com/api.v4/activity_feed.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the logging of a specific message directly to the Activity Feed.

curl  -o file1.txt -g -k -X POST -H "Content-Type: application/json" -d"@send_user_message_data.json" "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/activity_feed.php
apikey=11111111111111111111111111111111

# The example demonstrates the logging of a specific message directly to the Activity Feed.

curl  -o file1.txt -g -k -X POST -H "Content-Type: application/json" -d"@send_user_message_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
<job id="Send User Message">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/activity_feed.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="send_user_message_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\AvtivityParameters;

// The example demonstrates the logging of a specific message directly to the Activity Feed.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get random route ID
$route = new Route();
$route_id = $route->getRandomRouteId(0, 10);

$postParameters = ActivityParameters::fromArray(array(
    "activity_type"     => "user_message",
    "activity_message"  => "Hello - php!",
    "route_id"          => $route_id
));

$activities = new ActivityParameters();

$results = $activities->sendUserMessage($postParameters);

$msg = isset($results["status"])!=null
  ? ($results["status"]==1 ? "The user message was sent to the route " : "The user message could not be sent to the route ")
   : "The user message could not be sent to the route ";

$msg .= " with route_id=".$route_id;

echo "<br> $msg <br>"; 
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Create User Activity
    /// </summary>
    /// <param name="message"> Activity message </param>
    /// <param name="routeId"> Route identifier </param>
    /// <returns> True/False </returns>
    public bool LogCustomActivity(string message, string routeId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      Activity activity = new Activity()
      {
        ActivityType = "user_message",
        ActivityMessage = message,
        RouteId = routeId
      };

      // Run the query
      string errorString;
      bool added = route4Me.LogCustomActivity(activity, out errorString);

      Console.WriteLine("");

      if (added)
      {
        Console.WriteLine("LogCustomActivity executed successfully");
        return added;
      }
      else
      {
        Console.WriteLine("LogCustomActivity error: {0}", errorString);
        return added;
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Log Specific Message
        ''' </summary>
        Public Sub LogSpecificMessage()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim params As ActivityParameters = New ActivityParameters() With { _
                .ActivityType = "user_message", _
                .ActivityMessage = "Hello vb.net !", _
                .RouteId = "2EA70721624592FC41522A708603876D" _
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As Boolean = route4Me.LogSpecificMessage(params, errorString)

            Console.WriteLine("")

            If result Then
                Console.WriteLine("LogSpecificMessage executed successfully")
                Console.WriteLine("---------------------------")
            Else
                Console.WriteLine("LogSpecificMessage error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    response = activity_feed.log_specific_message(activity_message='Hello from Python SDK',
      route_id='D2F447BCB1F8B8388E88B07188B3A256')
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Message Logged: {}'.format(response.status)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetSendUserMessageActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.USER_MESSAGE));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  err := service.Log("Message", "ROUTE_ID")
  if err != nil {
    // handle error
  }
  // success!
}
unit LogSpecificMessageUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TLogSpecificMessage = class(TBaseExample)
  public
    function Execute(Message, RouteId: String): boolean;
  end;

implementation

function TLogSpecificMessage.Execute(Message, RouteId: String): boolean;

var
  ErrorString: String;
begin
  Result := Route4MeManager.ActivityFeed.LogSpecificMessage(RouteId, Message, ErrorString);

  WriteLn('');

  if (Result) then
    WriteLn('LogSpecificMessage executed successfully')
  else
    WriteLn(Format('LogSpecificMessage error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    const char *route_id = "CA902292134DBC134EAF8363426BD247";

    int ret = route.log_custom_activity(route_id, "test", "test2");
    if (ret == 0)
        cout << "Writing log: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    else
        cout << "Error writing log: " << Json::FastWriter().write(route.get_json_resp()) << endl;

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    const char *route_id = "CA902292134DBC134EAF8363426BD247";
    init(key, 1);

    if (!log_custom_activity(route_id, "test", "test1"))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

POST
/api.v4/activity_feed.php?api_key=...

You can expect this API response:

{ 
  "status":true
}

Area added

Get “area added” activities.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Area Added Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="area-added"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=area-added

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=area-added

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Search Area Added
        /// </summary>
        public void SearchAreaAdded()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "area-added" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchAreaAdded executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchAreaAdded error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchAreaAdded()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "area-added" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchAreaAdded executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchAreaAdded error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['area-added']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTIVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetAreaAddedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.AREA_ADDED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `area-added`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "area-added",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.AreaAdded})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
unit GetAreaAddedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAreaAddedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetAreaAddedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atAreaAdded, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetAreaAddedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetAreaAddedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;
    types.push_back("area-added");

    std::vector<std::string> foundActivities, missingActivities;
  
    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Area removed

Get “area removed” activities.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Area Removed Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="area-removed"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=area-removed

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=area-removed

ECHO ON
curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Search Area Removed
        /// </summary>
        public void SearchAreaRemoved()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "area-removed" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchAreaRemoved executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchAreaRemoved error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchAreaRemoved()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "area-removed" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchAreaRemoved executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchAreaRemoved error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['area-removed']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetAreaRemovedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.AREA_REMOVED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.AreaRemoved})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `area-removed`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "area-removed",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetAreaRemovedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAreaRemovedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetAreaRemovedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atAreaRemoved, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('ActivityAreaRemoved executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('ActivityAreaRemoved error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("area-removed");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Area updated

Get “area updated” activities.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Area Updated Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="area-updated"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=area-updated

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=area-updated

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Search Area Updated
        /// </summary>
        public void SearchAreaUpdated()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "area-updated" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchAreaUpdated executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchAreaUpdated error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchAreaUpdated()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "area-updated" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchAreaUpdated executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchAreaUpdated error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['area-updated']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetAreaUpdatedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.AREA_UPDATED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.AreaUpdated})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `area-updated`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "area-updated",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetAreaUpdatedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAreaUpdatedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetAreaUpdatedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atAreaUpdated, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetAreaUpdatedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetAreaUpdatedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("area-updated");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...

You can expect this API response:

{
  "results": [{
    "activity_id": "9F862B79AF6F19757D440D8B328B5382",
    "activity_type": "area-updated",
    "activity_timestamp": "1463663397",
    "activity_message": "Region 'Test Territory' was updated",
    "route_id": "00000000000000000000000000000000",
    "route_name": null,
    "route_destination_id": null,
    "note_id": null,
    "note_type": null,
    "note_contents": null,
    "note_file": null,
    "member": {
      "member_id": "*",
      "member_first_name": "D*an",
      "member_last_name": "*",
      "member_email": "d*"
    }
  }],
  "total": 1
}

Destination deleted

Get “destination deleted” activities.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Delete Destination Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      act_type="area-updated"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET act_type=delete-destination

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&route_id=%routeid%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
act_type=delete-destination

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&route_id=$routeid&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Delete Destination
        /// </summary>
        public void SearchDeleteDestination()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "delete-destination" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchDeleteDestination executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchDeleteDestination error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDestinationDeleted()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "delete-destination", _
                .RouteId = "5C15E83A4BE005BCD1537955D28D51D7" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDestinationDeleted executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDestinationDeleted error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    response = activity_feed.get_activity_feed_deleted(route_id='C9F6F9F664169DFB4042110069EBE688')
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Total Found: {}'.format(response.total)
        for i, activity in enumerate(response.results):
            print 'Activity #{}'.format(i + 1)
            print '\tActivity ID: {}'.format(activity.activity_id)
            print '\tActivity Message: {}'.format(activity.activity_message)
            print '\tActivity Type: {}'.format(activity.activity_type)
            print '\tRoute ID: {}'.format(activity.route_id)
            print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDestinationDeletedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.DELETE_DESTINATION));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.DeleteDestination})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `delete-destination`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "delete-destination",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetDestinationDeletedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetDestinationDeletedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetDestinationDeletedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atDeleteDestination, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetDestinationDeletedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetDestinationDeletedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("delete-destination");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Destination out of sequence

Get “destination out of sequence” activities (events).


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Destination Out Of Sequence Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
      
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="destination-out-sequence"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=destination-out-sequence

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=destination-out-sequence

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Destination Out Sequence
        /// </summary>
        public void SearchDestinationOutSequence()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "destination-out-sequence" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchDestinationOutSequence executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchDestinationOutSequence error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDestinationOutSequence()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "destination-out-sequence" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDestinationOutSequence executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDestinationOutSequence error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['destination-out-sequence']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDestinationOutOfSequenceActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.DESTINATION_OUT_SEQUENCE));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.DestinationOutSequence})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `destination-out-sequence`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "destination-out-sequence",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetDestinationOutOfSequenceActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetDestinationOutOfSequenceActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetDestinationOutOfSequenceActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atDestinationOutSequence, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetDestinationOutOfSequenceActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetDestinationOutOfSequenceActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("destination-out-sequence");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Driver arrived early

Get “driver arrived early” activities (events).


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Driver Arrived Early Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="driver-arrived-early"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=driver-arrived-early

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=driver-arrived-early

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Driver Arrived Early
        /// </summary>
        public void SearchDriverArrivedEarly()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "driver-arrived-early" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchDriverArrivedEarly executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchDriverArrivedEarly error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDriverArrivedEarly()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "driver-arrived-early" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDriverArrivedEarly executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDriverArrivedEarly error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['driver-arrived-early']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDriverArrivedEarlyActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.DRIVER_ARRIVED_EARLY));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.DriverArrivedEarly})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `driver-arrived-early`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "driver-arrived-early",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetDriverArrivedEarlyActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetDriverArrivedEarlyActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetDriverArrivedEarlyActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atDriverArrivedEarly, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetDriverArrivedEarlyActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetDriverArrivedEarlyActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("driver-arrived-early");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Driver arrived late

Get “driver arrived late” activities (events).


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Driver Arrived Late Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="driver-arrived-late"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=driver-arrived-late

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=driver-arrived-late

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Driver Arrived Late
        /// </summary>
        public void SearchDriverArrivedLate()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "driver-arrived-late" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchDriverArrivedLate executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchDriverArrivedLate error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDriverArrivedLate()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "driver-arrived-late" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDriverArrivedLate executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDriverArrivedLate error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['driver-arrived-late']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDriverArrivedLateActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.DRIVER_ARRIVED_LATE));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.DriverArrivedLate})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `driver-arrived-late`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "driver-arrived-late",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetDriverArrivedLateActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetDriverArrivedLateActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetDriverArrivedLateActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atDriverArrivedLate, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetDriverArrivedLateActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetDriverArrivedLateActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("driver-arrived-late");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Driver arrived on time

Get “driver arrived on time” activities (events).


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Driver Arrived On Time Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="driver-arrived-on-time"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=driver-arrived-on-time

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=driver-arrived-on-time

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Driver Arrived On Time
        /// </summary>
        public void SearchDriverArrivedOnTime()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "driver-arrived-on-time" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchDriverArrivedOnTime executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchDriverArrivedOnTime error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDriverArrivedOnTime()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "driver-arrived-on-time" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDriverArrivedOnTime executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDriverArrivedOnTime error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['driver-arrived-on-time']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDriverArrivedOnTimeActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.DRIVER_ARRIVED_ON_TIME));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.DriverArrivedOnTime})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `driver-arrived-on-time`.


// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "driver-arrived-on-time",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetDriverArrivedOnTimeActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetDriverArrivedOnTimeActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetDriverArrivedOnTimeActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atDriverArrivedOnTime, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetDriverArrivedOnTimeActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetDriverArrivedOnTimeActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("driver-arrived-on-time");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...

You can expect this API response:

{
"results": [{
  "activity_id": "294FC46D14010EA7772AA1FFE4113379",
  "destination_name": "4280 Kellway Circle, Addison, Texas, 75001",
  "destination_alias": "Total Life Care",
  "activity_type": "driver-arrived-on-time",
  "activity_timestamp": "1454608230",
  "activity_message": "The driver marked as visited within the expected time window the address '4280 Kellway Circle, Addison, Texas, 75001'",
  "route_id": "E9C1BC7FCA59D934FFAC3703E287461C",
  "route_name": "with-cubic (Part 001)",
  "route_destination_id": "143359649",
  "note_id": null,
  "note_type": null,
  "note_contents": null,
  "note_file": null,
  "member": {
    "member_id": "1",
    "member_first_name": "Kevin",
    "member_last_name": "Bacon",
    "member_email": "[email protected]"
  }
}],
"total": 1
}

Geofence entered

Get “geofence entered” activities (events).


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Geofence Entered Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."

      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="geofence-entered"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=geofence-entered

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=geofence-entered

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Geofence Entered
        /// </summary>
        public void SearchGeofenceEntered()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "geofence-entered" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchGeofenceEntered executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchGeofenceEntered error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchGeofenceEntered()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "geofence-entered" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchGeofenceEntered executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchGeofenceEntered error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['geofence-entered']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetGeofenceEnteredActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.GEOFENCE_ENTERED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.GeofenceEntered})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `geofence-entered`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "geofence-entered",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetGeofenceEnteredActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetGeofenceEnteredActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetGeofenceEnteredActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atGeofenceEntered, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetGeofenceEnteredActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetGeofenceEnteredActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("geofence-entered");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Geofence left

Get “geofence left” activities (events).


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Geofence Left Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="geofence-left"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=geofence-left

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=geofence-left

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Geofence Left
        /// </summary>
        public void SearchGeofenceLeft()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "geofence-left" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchGeofenceLeft executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchGeofenceLeft error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchGeofenceLeft()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "geofence-left" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchGeofenceLeft executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchGeofenceLeft error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['geofence-left']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetGeofenceLeftActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.GEOFENCE_LEFT));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.GeofenceLeft})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `geofence-left`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "geofence-left",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetGeofenceLeftActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetGeofenceLeftActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetGeofenceLeftActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atGeofenceLeft, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetGeofenceLeftActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetGeofenceLeftActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("geofence-left");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Destination inserted

Get “destination inserted” activities (events) from a particular route.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
route_id string Route ID
<job id="Get Insert Destination Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      act_type="insert-destination"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET act_type=insert-destination

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&route_id=%routeid%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
act_type=insert-destination

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&route_id=$routeid&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Insert Destination
        /// </summary>
        public void SearchInsertDestination()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters()
      {
        ActivityType = "insert-destination",
        RouteId = "87B8873BAEA4E09942C68E2C92A9C4B7"
      };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchInsertDestination executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchInsertDestination error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDestinationInserted()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "insert-destination", _
                .RouteId = "87B8873BAEA4E09942C68E2C92A9C4B7" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDestinationInserted executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDestinationInserted error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    response = activity_feed.get_activity_feed_inserted(route_id='D2F447BCB1F8B8388E88B07188B3A256')
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Total Found: {}'.format(response.total)
        for i, activity in enumerate(response.results):
            print 'Activity #{}'.format(i + 1)
            print '\tActivity ID: {}'.format(activity.activity_id)
            print '\tActivity Message: {}'.format(activity.activity_message)
            print '\tActivity Type: {}'.format(activity.activity_type)
            print '\tRoute ID: {}'.format(activity.route_id)
            print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDestinationInsertedToCertainRouteActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.INSERT_DESTINATION).setRouteId("5C15E83A4BE005BCD1537955D28D51D7"));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.InsertDestination, RouteID: "5C15E83A4BE005BCD1537955D28D51D7"})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `insert-destination` on the specified route.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

// Get random route ID
$route = new Route();
$route_id = $route->getRandomRouteId(0, 10);

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "insert-destination",
  "limit"         => 2,
  "offset"        => 0,
  "route_id"      => $route_id
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetDestinationInsertedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetDestinationInsertedActivities = class(TBaseExample)
  public
    procedure Execute(RouteId: String);
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetDestinationInsertedActivities.Execute(RouteId: String);

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(RouteId,
    TActivityType.atInsertDestination, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetDestinationInsertedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetDestinationInsertedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("insert_destination");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...

You can expect this API response:

{
"results": [{
  "activity_id": "AED2D5EE219B6FE06FB41AC88B6B7052",
  "destination_name": "3557-3593 W Market St, Fairlawn, OH 44333, USA",
  "destination_alias": "",
  "activity_type": "insert-destination",
  "activity_timestamp": "1470407091",
  "activity_message": "Address '3557-3593 W Market St, Fairlawn, OH 44333, USA' was added into route 'Reveive_notifications_address_checkin_08-05-2016'",
  "route_id": "87B8873BAEA4E09942C68E2C92A9C4B7",
  "route_name": "Reveive_notifications_address_checkin_08-05-2016",
  "route_destination_id": "178204838",
  "note_id": null,
  "note_type": null,
  "note_contents": null,
  "note_file": null,
  "member": {
    "member_id": "1",
    "member_first_name": "Kevin",
    "member_last_name": "Bacon",
    "member_email": "[email protected]"
  }
}],
"total": 1
}

Destination inserted (all)

Get “destination inserted” activities (events) from all routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Insert Destination All Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="insert-destination"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=insert-destination

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=insert-destination

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Insert Destination All
        /// </summary>
        public void SearchInsertDestinationAll()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters()
      {
        ActivityType = "insert-destination"
      };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchInsertDestinationAll executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }
                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchInsertDestinationAll error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDestinationInsertedAll()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "insert-destination" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDestinationInsertedAll executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDestinationInsertedAll error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDestinationInsertedOfAllRoutesActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.INSERT_DESTINATION));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.InsertDestination})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `insert-destination`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "insert-destination",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetAllDestinationInsertedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAllDestinationInsertedActivities = class(TBaseExample)
  public
    procedure Execute();
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetAllDestinationInsertedActivities.Execute();

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atInsertDestination, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetAllDestinationInsertedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetAllDestinationInsertedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Destination marked as departed

Get “destination marked as departed” activities (events) from a particular route.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
activity_type string Activity type
<job id="Get Mark Destination Departed Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      act_type="mark-destination-departed"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET act_type=mark-destination-departed

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&route_id=%routeid%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
act_type=mark-destination-departed

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&route_id=$routeid&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Mark Destination As Departed
        /// </summary>
        public void SearchMarkDestinationDeparted()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters()
      { 
        ActivityType = "mark-destination-departed",
        RouteId = "03CEF546324F727239ABA69EFF3766E1"
      };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchMarkDestinationDeparted executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchMarkDestinationDeparted error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDestinationMarkedAsDeparted()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "mark-destination-departed", _
                .RouteId = "03CEF546324F727239ABA69EFF3766E1" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDestinationMarkedAsDeparted executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDestinationMarkedAsDeparted error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['mark-destination-departed']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDestinationMarkedAsDepartedFromCertainRouteActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.MARK_DESTINATION_DEPARTED).setRouteId("5C15E83A4BE005BCD1537955D28D51D7"));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.MarkDestinationDeparted, RouteID: "5C15E83A4BE005BCD1537955D28D51D7"})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `mark-destination-departed` on the specified route.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

// Get random route ID
$route = new Route();
$route_id = $route->getRandomRouteId(0, 10);

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "mark-destination-departed",
  "limit"         => 2,
  "offset"        => 0,
  "route_id"      => $route_id
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetDestinationMarkedAsDepartedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetDestinationMarkedAsDepartedActivities = class(TBaseExample)
  public
    procedure Execute(RouteId: String);
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetDestinationMarkedAsDepartedActivities.Execute(RouteId: String);

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(RouteId,
    TActivityType.atMarkDestinationDeparted, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetDestinationMarkedAsDepartedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetDestinationMarkedAsDepartedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("mark-destination-departed");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...&route_id=...

You can expect this API response:

{
"results": [{
  "activity_id": "17E82B5C4BFB3F5E0275D23D223A9C65",
  "destination_name": "2 Victoria Ct, Fredericksburg, VA 22407",
  "destination_alias": "",
  "activity_type": "mark-destination-departed",
  "activity_timestamp": "1450380541",
  "activity_message": "The address '2 Victoria Ct, Fredericksburg, VA 22407' was marked as departed from the web interface",
  "route_id": "03CEF546324F727239ABA69EFF3766E1",
  "route_name": "accenture-single-driver-1",
  "route_destination_id": "136592941",
  "note_id": null,
  "note_type": null,
  "note_contents": null,
  "note_file": null,
  "member": {
    "member_id": "1",
    "member_first_name": "Kevin",
    "member_last_name": "Bacon",
    "member_email": "[email protected]"
  }
},
{
  "activity_id": "DBCD55313DA1131646BFD83F9F7EF934",
  "destination_name": "10809 Stacy Run, Fredericksburg, VA 22408",
  "destination_alias": "",
  "activity_type": "mark-destination-departed",
  "activity_timestamp": "1450380340",
  "activity_message": "The address '10809 Stacy Run, Fredericksburg, VA 22408' was marked as departed from the web interface",
  "route_id": "03CEF546324F727239ABA69EFF3766E1",
  "route_name": "accenture-single-driver-1",
  "route_destination_id": "136592939",
  "note_id": null,
  "note_type": null,
  "note_contents": null,
  "note_file": null,
  "member": {
    "member_id": "1",
    "member_first_name": "Kevin",
    "member_last_name": "Bacon",
    "member_email": "[email protected]"
  }
}],
"total": 2
}

Destination marked as departed (all)

Get “destination marked as departed” activities (events) from all routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Mark Destination Departed All Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="mark-destination-departed"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=mark-destination-departed

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=mark-destination-departed

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Mark Destination As Departed All
        /// </summary>
        public void SearchMarkDestinationDepartedAll()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "mark-destination-departed" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchMarkDestinationDepartedAll executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchMarkDestinationDepartedAll error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchMarkDestinationDepartedAll()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "mark-destination-departed" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchMarkDestinationDepartedAll executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchMarkDestinationDepartedAll error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDestinationMarkedAsDepartedOfAllRoutesActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.MARK_DESTINATION_DEPARTED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.MarkDestinationDeparted})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `mark-destination-departed`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "mark-destination-departed",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetAllDestinationMarkedAsDepartedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAllDestinationMarkedAsDepartedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetAllDestinationMarkedAsDepartedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atMarkDestinationDeparted, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetAllDestinationMarkedAsDepartedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetAllDestinationMarkedAsDepartedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Destination marked as visited

Get “destination marked as visited” activities (events) from all routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Mark Destination Visited All Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="mark-destination-visited"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=mark-destination-visited

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=mark-destination-visited

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Mark Destination as Visited
        /// </summary>
        public void SearchMarkDestinationVisited()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "mark-destination-visited" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchMarkDestinationVisited executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchMarkDestinationVisited error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchMarkDestinationVisited()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "mark-destination-visited" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchMarkDestinationVisited executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchMarkDestinationVisited error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['mark-destination-visited']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDestinationMarkedAsVisitedOfAllRoutesActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.MARK_DESTINATION_VISITED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
    activities, err := service.Get(&activity.Query{Type: service.MarkDestinationVisited})
    if err != nil {
        // handle error
    }
    // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// Example refers to the process of getting activities of the_type mark-destination-visited.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "mark-destination-visited",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetAllDestinationMarkedAsVisitedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAllDestinationMarkedAsVisitedActivities = class(TBaseExample)
  public
    procedure Execute();
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetAllDestinationMarkedAsVisitedActivities.Execute();

var
  ErrorString: String;
  Activities: TActivityList;
  Limit, Offset, Total: integer;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atMarkDestinationVisited, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetAllDestinationMarkedAsVisitedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetAllDestinationMarkedAsVisitedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("mark-destination-visited");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...

You can expect this API response:

{
"results": [{
  "activity_id": "2E4573C2252D01AAA182929E693A7E43",
  "destination_name": "559 W Aurora Rd, Northfield, OH 44067",
  "destination_alias": "",
  "activity_type": "mark-destination-visited",
  "activity_timestamp": "1469712876",
  "activity_message": "The address '559 W Aurora Rd, Northfield, OH 44067' was marked as visited from the web interface",
  "route_id": "241466F15515D67D3F951E2DA38DE76D",
  "route_name": "Multiple Depot, Multiple Driver with 24 Stops, Time Window (Unrouted Destinations)",
  "route_destination_id": "167899269",
  "note_id": null,
  "note_type": null,
  "note_contents": null,
  "note_file": null,
  "member": {
    "member_id": "1",
    "member_first_name": "David",
    "member_last_name": "Progman",
    "member_email": "[email protected]"
  }
},
{
  "activity_id": "C6D2C6102EEF5BC00882BEE9D43BAAF8",
  "destination_name": "559 W Aurora Rd, Northfield, OH 44067",
  "destination_alias": "",
  "activity_type": "mark-destination-visited",
  "activity_timestamp": "1467820325",
  "activity_message": "The address '559 W Aurora Rd, Northfield, OH 44067' was marked as not visited from the web interface",
  "route_id": "241466F15515D67D3F951E2DA38DE76D",
  "route_name": "Multiple Depot, Multiple Driver with 24 Stops, Time Window (Unrouted Destinations)",
  "route_destination_id": "167899269",
  "note_id": null,
  "note_type": null,
  "note_contents": null,
  "note_file": null,
  "member": {
    "member_id": "1",
    "member_first_name": "David",
    "member_last_name": "Progman",
    "member_email": "[email protected]"
  }
}],
"total": 2
}

Member created

Get “member created” activities (events).


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Member Created Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="member-created"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=member-created

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=member-created

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Member Created
        /// </summary>
        public void SearchMemberCreated()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "member-created" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchMemberCreated executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchMemberCreated error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchMemberCreated()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "member-created" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchMemberCreated executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchMemberCreated error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['member-created']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetMemberCreatedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.MEMBER_CREATED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.MemberCreated})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `member-created`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "member-created",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetMemberCreatedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetMemberCreatedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetMemberCreatedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atMemberCreated, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetMemberCreatedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetMemberCreatedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("member-created");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...

You can expect this API response:

{
"results": [{
  "activity_id": "90C49E33DEF1492C3288C362219E996A",
  "destination_name": null,
  "destination_alias": null,
  "activity_type": "member-created",
  "activity_timestamp": "1463757375",
  "activity_message": "Team member \"bret x\" was created",
  "route_id": null,
  "route_name": null,
  "route_destination_id": null,
  "note_id": null,
  "note_type": null,
  "note_contents": null,
  "note_file": null,
  "member": {
    "member_id": "1",
    "member_first_name": "Kevin",
    "member_last_name": "Bacon",
    "member_email": "[email protected]"
  }
},
{
  "activity_id": "56F5772FD2EDA5DDC133B05EC7DA9065",
  "destination_name": null,
  "destination_alias": null,
  "activity_type": "member-created",
  "activity_timestamp": "1450472984",
  "activity_message": "Team member \"Analyst Analyst\" was created",
  "route_id": null,
  "route_name": null,
  "route_destination_id": null,
  "note_id": null,
  "note_type": null,
  "note_contents": null,
  "note_file": null,
  "member": {
    "member_id": "1",
    "member_first_name": "Kevin",
    "member_last_name": "Bacon",
    "member_email": "[email protected]"
  }
}],
"total": 2
}

Member deleted

Get “member deleted” activities (events).


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Member Deleted Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="member-deleted"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=member-deleted

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=member-deleted

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Member Deleted
        /// </summary>
        public void SearchMemberDeleted()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "member-deleted" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchMemberDeleted executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchMemberDeleted error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchMemberDeleted()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "member-deleted" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchMemberDeleted executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchMemberDeleted error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['member-deleted']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetMemberDeletedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.MEMBER_DELETED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.MemberDeleted})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `member-deleted`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "member-deleted",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetMemberDeletedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetMemberDeletedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetMemberDeletedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atMemberDeleted, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetMemberDeletedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetMemberDeletedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("member-deleted");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Member modified

Get “member modified” activities (events).


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Member Modified Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="member-modified"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=member-modified

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=member-modified

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Member Modified
        /// </summary>
        public void SearchMemberModified()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "member-modified" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchMemberModified executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchMemberModified error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchMemberModified()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "member-modified" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchMemberModified executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchMemberModified error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['member-modified']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetMemberUpdatedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.MEMBER_MODIFIED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.MemberModified})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `member-modified`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "member-modified",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>"
unit GetMemberModifiedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetMemberModifiedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetMemberModifiedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atMemberModified, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetMemberModifiedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetMemberModifiedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("member-modified");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Destination moved (all)

Get “destination moved to another route” activities (events) from all routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Move Destination Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="move-destination"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=move-destination

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=move-destination

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Move Destination
        /// </summary>
        public void SearchMoveDestination()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "move-destination" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchMoveDestination executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchMoveDestination error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDestinationMoved()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "move-destination" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDestinationMoved executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDestinationMoved error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['move-destination']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDestinationMovedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.MOVE_DESTINATION));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.MoveDestination})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `move-destination`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "move-destination",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetDestinationMovedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetDestinationMovedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetDestinationMovedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atMoveDestination, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetDestinationMovedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetDestinationMovedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("move-destination");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...

You can expect this API response:

{
  "results": [{
    "activity_id": "CB28C7FD9D4C7C8A3B641D30F7B16EDB",
    "activity_type": "move-destination",
    "activity_timestamp": "1463068860",
    "activity_message": "Address '230 Arbor Way Milledgeville GA 31061' was moved into route 'Single Driver Round Trip'",
    "route_id": "E9F85EA9BBBB0104D6D3493222557F11",
    "route_name": "Single Driver Route 10 Stops",
    "route_destination_id": "162437520",
    "note_id": null,
    "note_type": null,
    "note_contents": null,
    "note_file": null,
    "member": {
      "member_id": "*",
      "member_first_name": "*",
      "member_last_name": "*",
      "member_email": "*"
    }
  }],
  "total": 1
}

Note inserted

Get “note inserted” activities (events) from a particular route.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
activity_type string Activity type
<job id="Get Note Insert Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      act_type="note-insert"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET act_type=note-insert

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&route_id=%routeid%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
act_type=note-insert

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&route_id=$routeid&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Note Inserted
        /// </summary>
        public void SearchNoteInserted()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters()
      { 
        ActivityType = "note-insert",
        RouteId = "C3E7FD2F8775526674AE5FD83E25B88A"
      };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchNoteInserted executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchNoteInserted error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchNoteInserted()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "note-insert", _
                .RouteId = "C3E7FD2F8775526674AE5FD83E25B88A" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchNoteInserted executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchNoteInserted error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['note-insert']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetNoteInsertedFromCertainRouteActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.NOTE_INSERT).setRouteId("5C15E83A4BE005BCD1537955D28D51D7"));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.NoteInsert, RouteID: "5C15E83A4BE005BCD1537955D28D51D7"})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `note-insert` on the specified route.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

// Get random route ID
$route = new Route();
$route_id = $route->getRandomRouteId(0, 10);

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "note-insert",
  "limit"         => 2,
  "offset"        => 0,
  "route_id"      => $route_id
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetNoteInsertedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetNoteInsertedActivities = class(TBaseExample)
  public
    procedure Execute(RouteId: String);
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetNoteInsertedActivities.Execute(RouteId: String);

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(RouteId,
    TActivityType.atNoteInsert, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetNoteInsertedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetNoteInsertedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...&route_id=...

You can expect this API response:

{
"results": [{
  "activity_id": "72FEB9C96CA2204618217165BEF4816A",
  "destination_name": "2210 SW 22nd Terrace Cape Coral, FL 33991-3032",
  "destination_alias": "Hook Steve & Susan",
  "activity_type": "note-insert",
  "activity_timestamp": "1469648692",
  "activity_message": "A note was added to the address '2210 SW 22nd Terrace Cape Coral, FL 33991-3032 (Hook Steve & Susan)' from an iPhone",
  "route_id": "C3E7FD2F8775526674AE5FD83E25B88A",
  "route_name": "Aarons",
  "route_destination_id": "176449171",
  "note_id": "629817",
  "note_type": "",
  "note_contents": "",
  "note_file": "http:\/\/adb6def9928467589ebb-f540d5a8d53c2e76ad581b6e5c346ad6.r74.cf1.rackcdn.com\/4dc137d74102ee8b10f8fd5f34281809.jpg",
  "member": {
    "member_id": "1",
    "member_first_name": "Kevin",
    "member_last_name": "Bacon",
    "member_email": "[email protected]"
  }
},
{
  "activity_id": "2480861D51882FA3B2341398417A2411",
  "destination_name": "2210 SW 22nd Terrace Cape Coral, FL 33991-3032",
  "destination_alias": "Hook Steve & Susan",
  "activity_type": "note-insert",
  "activity_timestamp": "1469648562",
  "activity_message": "A note was added to the address '2210 SW 22nd Terrace Cape Coral, FL 33991-3032 (Hook Steve & Susan)' from an iPhone",
  "route_id": "C3E7FD2F8775526674AE5FD83E25B88A",
  "route_name": "Aarons",
  "route_destination_id": "176449171",
  "note_id": "629809",
  "note_type": "",
  "note_contents": "",
  "note_file": "http:\/\/adb6def9928467589ebb-f540d5a8d53c2e76ad581b6e5c346ad6.r74.cf1.rackcdn.com\/e36d66504c78b8f98dff232003c22c32.jpg",
  "member": {
    "member_id": "1",
    "member_first_name": "Kevin",
    "member_last_name": "Bacon",
    "member_email": "[email protected]"
  }
}],
"total": 2
}

Note inserted (all)

Get “note inserted” activities (events) from all routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Note Insert All Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
    
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="note-insert"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=note-insert

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=note-insert

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Note Inserted All
        /// </summary>
        public void SearchNoteInsertedAll()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters()
      { 
        ActivityType = "note-insert"
      };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchNoteInsertedAll executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchNoteInsertedAll error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchNoteInsertedAll()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "note-insert" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchNoteInsertedAll executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchNoteInsertedAll error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetNoteInsertedOfAllRoutesActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.NOTE_INSERT));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.NoteInsert})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `note-insert`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "note-insert",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetAllNoteInsertedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAllNoteInsertedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetAllNoteInsertedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atNoteInsert, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetAllNoteInsertedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetAllNoteInsertedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("note-insert");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Route deleted

Get “route deleted” activities (events) from all routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Route Delete Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
      
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="route-delete"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=route-delete

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=route-delete

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Route Deleted
        /// </summary>
        public void SearchRouteDeleted()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "route-delete" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchRouteDeleted executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchRouteDeleted error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchRouteDeleted()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "route-delete" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchRouteDeleted executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchRouteDeleted error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['route-delete']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetRouteDeletedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.ROUTE_DELETE));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.RouteDelete})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `route-delete`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "route-delete",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetRouteDeletedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetRouteDeletedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetRouteDeletedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atRouteDelete, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetRouteDeletedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetRouteDeletedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("route-delete");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Route optimized (all)

Get “route optimized” activities (events) from all routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Route Optimized Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
      
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="route-optimized"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=route-optimized

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=route-optimized

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Route Optimized
        /// </summary>
        public void SearchRouteOptimized()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "route-optimized" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchRouteOptimized executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchRouteOptimized error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchRouteOptimized()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "route-optimized" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchRouteOptimized executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchRouteOptimized error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['route-optimized']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetRouteOptimizedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.ROUTE_OPTIMIZED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.RouteOptimized})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `route-optimized`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "route-optimized",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetRouteOptimizedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetRouteOptimizedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetRouteOptimizedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atRouteOptimized, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetRouteOptimizedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetRouteOptimizedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("route-optimized");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Route owner changed

Get “route owner changed” activities (events) from all routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
activity_type string Activity type
<job id="Get Route Owner Changed Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.

      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      act_type="route-owner-changed"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET routeid=5C15E83A4BE005BCD1537955D28D51D7
SET act_type=route-owner-changed

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&route_id=%routeid%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
act_type=route-owner-changed

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&route_id=$routeid&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Route Owner Changed
        /// </summary>
        public void SearchRouteOwnerChanged()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "route-owner-changed" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchRouteOwnerChanged executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchRouteOwnerChanged error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchRouteOwnerChanged()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "route-owner-changed", _
                .RouteId = "5C15E83A4BE005BCD1537955D28D51D7" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchRouteOwnerChanged executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchRouteOwnerChanged error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    response = activity_feed.get_activity_feed_deleted(route_id='5C15E83A4BE005BCD1537955D28D51D7')
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Total Found: {}'.format(response.total)
        for i, activity in enumerate(response.results):
            print 'Activity #{}'.format(i + 1)
            print '\tActivity ID: {}'.format(activity.activity_id)
            print '\tActivity Message: {}'.format(activity.activity_message)
            print '\tActivity Type: {}'.format(activity.activity_type)
            print '\tRoute ID: {}'.format(activity.route_id)
            print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetRouteOwnerChangedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.ROUTE_OWNER_CHANGED));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.RouteOptimized, RouteID: "5C15E83A4BE005BCD1537955D28D51D7"})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `route-owner-changed` on the specified route.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

// Get random route ID
$route = new Route();
$route_id = $route->getRandomRouteId(0, 10);

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "route-owner-changed",
  "limit"         => 2,
  "offset"        => 0,
  "route_id"      => $route_id
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetRouteOwnerChangedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetRouteOwnerChangedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetRouteOwnerChangedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atRouteOwnerChanged, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetRouteOwnerChangedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetRouteOwnerChangedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("route-owner-changed");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...&route_id=...

You can expect this API response:

{
  "results": [{
    "activity_id": "8F9A3FF69C04E538DAB79812E1AA5C28",
    "activity_type": "route-owner-changed",
    "activity_timestamp": "1462372498",
    "activity_message": "The owner of the route 'updated 040516' was changed from '***@novapulsar.com' to '***@lmsvc.com'",
    "route_id": "5C15E83A4BE005BCD1537955D28D51D7",
    "route_name": "updated 040516",
    "route_destination_id": null,
    "note_id": null,
    "note_type": null,
    "note_contents": null,
    "note_file": null,
    "member": {
      "member_id": "177496",
      "member_first_name": "Joshua",
      "member_last_name": "Holkup",
      "member_email": "[email protected]"
    }
  }],
  "total": 1
}

Destination updated (all)

Get “destination updated” activities (events) from all routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
activity_type string Activity type
<job id="Get Update Destinations Activities">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' For accurate testing and results, use your API key and insert real test data.
      
      url="https://api.route4me.com/api/get_activities.php"
      apikey="11111111111111111111111111111111"
      act_type="update-destinations"
      
      url=url&"?api_key="&apikey
      url=url&"&activity_type="&act_type
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

:: For accurate testing and results, use your API key and insert real test data.

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET act_type=update-destinations

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&activity_type=%act_type%"

timeout /t 30
#!/bin/bash

# For accurate testing and results, use your API key and insert real test data.

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
act_type=update-destinations

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&activity_type=$act_type"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Activities Destination Updated
        /// </summary>
        public void SearchDestinationUpdated()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            ActivityParameters activityParameters = new ActivityParameters { ActivityType = "update-destinations" };

            // Run the query
            string errorString = "";
            Activity[] activities = route4Me.GetActivityFeed(activityParameters, out errorString);

            Console.WriteLine("");

            if (activities != null)
            {
                Console.WriteLine("SearchDestinationUpdated executed successfully, {0} activities returned", activities.Length);
                Console.WriteLine("");

                foreach (Activity Activity in activities)
                {
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId);
                }

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchDestinationUpdated error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchDestinationUpdated()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim activityParameters As New ActivityParameters() With { _
                .ActivityType = "update-destinations" _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim activities As Activity() = route4Me.GetActivityFeed(activityParameters, errorString)

            Console.WriteLine("")

            If activities IsNot Nothing Then
                Console.WriteLine("SearchDestinationUpdated executed successfully, {0} activities returned", activities.Length)
                Console.WriteLine("")

                For Each Activity As Activity In activities
                    Console.WriteLine("Activity ID: {0}", Activity.ActivityId)
                Next

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchDestinationUpdated error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

ACTYVITY_TYPE = ['update-destinations']

def main():
    route4me = Route4Me(KEY)
    activity_feed = route4me.activity_feed
    for activity_type in ACTYVITY_TYPE:
        response = activity_feed.get_activities_feed_by_type(activity_type=activity_type, limit=1, offset=0)
        print ' '.join(activity_type.split('-')).upper()
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Total Found: {}'.format(response.total)
            for i, activity in enumerate(response.results):
                print 'Activity #{}'.format(i + 1)
                print '\tActivity ID: {}'.format(activity.activity_id)
                print '\tActivity Message: {}'.format(activity.activity_message)
                print '\tActivity Type: {}'.format(activity.activity_type)
                print '\tRoute ID: {}'.format(activity.route_id)
                print '\tRoute Name: {}'.format(activity.route_name)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.activities;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.activities.Activities;
import com.route4me.sdk.services.activities.ActivityManager;
import com.route4me.sdk.services.activities.ActivityRequest;
import com.route4me.sdk.services.activities.ActivityType;

public class GetDestinationUpdatedActivities {
    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        ActivityManager manager = new ActivityManager(apiKey);
        try {
            Activities activities = manager.getActivities(new ActivityRequest().setType(ActivityType.UPDATE_DESTINATIONS));
            System.out.println(activities.getResults());
        }catch(APIException e) {
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/activity"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &activity.Service{Client: client}
  
  activities, err := service.Get(&activity.Query{Type: service.UpdateDestinations})
  if err != nil {
    // handle error
  }
  // do something with activities, it's []Activity
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;
use Route4Me\Enum\ActivityTypes;

// The example demonstrates how to get the activities of the type `update-destinations`.

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$activityTypes = new ActivityTypes();

$activityParameters = ActivityParameters::fromArray(array(
  "activity_type" => "update-destinations",
  "limit"         => 2,
  "offset"        => 0
));

$activities = new ActivityParameters();
$results = $activities->searchActivities($activityParameters);

foreach ($results as $key => $activity) {
  Route4Me::simplePrint($activity);
  echo "<br>";
}

echo "------------------- <br><br>";
unit GetDestinationUpdatedActivitiesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetDestinationUpdatedActivities = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses ActivityUnit, EnumsUnit;

procedure TGetDestinationUpdatedActivities.Execute;

var
  ErrorString: String;
  Limit, Offset, Total: integer;
  Activities: TActivityList;
begin
  Limit := 10;
  Offset := 0;
  Activities := Route4MeManager.ActivityFeed.GetActivities(
    TActivityType.atUpdateDestinations, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (ErrorString = EmptyStr) then
    begin
      WriteLn(Format('GetDestinationUpdatedActivities executed successfully, ' +
        '%d activities returned, %d total', [Activities.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetDestinationUpdatedActivities error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Activities);
  end;
end;
end.
#include <iostream>
#include <vector>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

static void feedback(const std::vector<std::string>& data, const char* message)
{
    std::cout << message << std::endl;
    for (int i = 0; i < data.size(); ++i)
    {
        std::cout << data[i] << std::endl;
    }
}

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    std::vector<std::string> types;

    types.push_back("update-destinations");

    std::vector<std::string> foundActivities, missingActivities;

    for (int i = 0; i < types.size(); ++i) {
        const char* type = types[i].c_str();
        if (route.get_activities_by_type(type) == 0)
            foundActivities.push_back(type);
        else
            missingActivities.push_back(type);
    }

    feedback(foundActivities, "Activities found for types:");
    feedback(missingActivities, "Activities missing for types:");

    CRoute4Me::cleanup();
    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 1);

    if (!get_activity_by_type("update-destinations"))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api/get_activities.php?api_key=...&activity_type=...


See the sample JSON response of this method.


Get Activities By User

Get the activities related to a specified user.


PARAMETERS

Parameter Type Description
api_key string API key of the user
member_id integer Member ID
<job id="Get Activities BY A Member">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			
			WScript.Echo "Please, press OK and wait..."
			
			' You should insert real test data and your API key for accurate testing
			
			' Example refers to the process of getting all activities by a member

			url="https://api.route4me.com/api/get_activities.php"
			apikey="11111111111111111111111111111111"
			member_id="888888"
			
			url=url&"?api_key="&apikey
			url=url&"&member_id="&member_id
			
			Set r4m=New Route4Me
			r4m.OutputFile="get_activities_by_member_RESPONSE.json"
			
			r4m.HttpGetRequest(url)
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

:: You should insert real test data and your API key for accurate testing

:: Example refers to the process of getting all activities by a member

SET url=https://api.route4me.com/api/get_activities.php
SET apikey=11111111111111111111111111111111
SET member_id=888888

ECHO ON
curl -o get_activities_by_member_RESPONSE.json -g -k -X GET "%URL%?api_key=%apikey%&member_id=%member_id%"

timeout /t 30
 #!/bin/bash

 # You should insert real test data and your API key for accurate testing

 # Example refers to the process of getting all activities by a member

url=https://api.route4me.com/api/get_activities.php
apikey=11111111111111111111111111111111
member_id=888888

curl -o get_activities_by_member_RESPONSE.json -g -k -X GET "$url?api_key=$apikey&member_id=$member_id"

echo "Finished..."

sleep 15
public void GetActivitiesByMemberTest()
{
	if (c_ApiKey == ApiKeys.demoApiKey) return;

	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	GenericParameters parameters = new GenericParameters()
	{
	};

	string userErrorString;
	var response = route4Me.GetUsers(parameters, out userErrorString);

	Assert.IsInstanceOfType(response.results, typeof(MemberResponseV4[]), "GetActivitiesByMemberTest failed - cannot get users");
	Assert.IsTrue(response.results.Length > 1, "Cannot retrieve more than 1 users");

	ActivityParameters activityParameters = new ActivityParameters()
	{
		MemberId = response.results[1].member_id!=null ? Convert.ToInt32(response.results[1].member_id) : -1,
		Offset = 0,
		Limit = 10
	};

	// Run the query
	string errorString;
	Activity[] activities = route4Me.GetActiviies(activityParameters, out errorString);

	Assert.IsInstanceOfType(activities, typeof(Activity[]), "GetActivitiesByMemberTest failed... " + errorString);
}
Public Sub GetActivitiesByMemberTest()
	If c_ApiKey = ApiKeys.demoApiKey Then Return

	Dim route4Me As New Route4MeManager(c_ApiKey)

	Dim parameters As New GenericParameters()

	Dim userErrorString As String
	Dim response = route4Me.GetUsers(parameters, userErrorString)

	Assert.IsInstanceOfType(response.results, GetType(MemberResponseV4()), "GetActivitiesByMemberTest failed - cannot get users")
	Assert.IsTrue(response.results.Length > 1, "Cannot retrieve more than 1 users")

	Dim activityParameters As New ActivityParameters() With {
		.MemberId = If(response.results(1).member_id IsNot Nothing, Convert.ToInt32(response.results(1).member_id), -1),
		.Limit = 10,
		.Offset = 0
	}

	' Run the query
	Dim errorString As String = ""
	Dim activities As Activity() = route4Me.GetActivities(activityParameters, errorString)

	Assert.IsInstanceOfType(activities, GetType(Activity()), Convert.ToString("GetActivitiesTest failed... ") & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$MamberParames =Member::fromArray([ ]);
$member = new Member();

$response = $member->getUsers($MamberParames);

assert(isset($response['results']), 'Cannot retrieve the users! <br>');
assert(sizeof($response['results'])>1, 'Cannot retrieve more than 1 users');

$memberId = $response['results'][1]["member_id"];

$activityParameters = ActivityParameters::fromArray([
    'member_id' => $memberId,
    'limit' => 10,
    'offset' => 0,
]);

$activities = new ActivityParameters();

$actResults = $activities->getActivities($activityParameters);

$results = $activities->getValue($actResults, 'results');

foreach ($results as $result) {
    Route4Me::simplePrint($result);
    echo '<br>';
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api.v4/order.php?api_key=...

You can expect this API response:

{"status":true}

Address Book

An address book refers to a user’s locations repository.

See the Address Book JSON Schema in our GitHub repository.

Address Book Properties

Attribute Type Description
api_key string API key of the user
address_1 string The route Address Line 1
address_2 string The route Address Line 2
address_alias string Address alias
address_group string Address group
first_name string First name
last_name string Last name
address_email string Address email
address_phone_number string Address phone number
cached_lat number Cached latitude
cached_lng number Cached longitude
address_city string Address city
address_state_id string Address state ID
address_country_id string Address country ID
address_zip string Address ZIP Code
address_custom_data array Address custom data (this is a String array).

Create a Location

Adds a location to a user’s address book.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data POST data A valid JSON object string. See the Address Book JSON Schema as a guide.
For implementation details refer to:
https://github.com/route4me/route4me-vbscript-sdk/blob/master/Addressbook/Addressbook_add_contact.wsf
 
<job id="Addressbook Add Location">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address_book.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="new_address_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public AddressBookContact AddAddressBookContact()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      AddressBookContact contact = new AddressBookContact()
      {
        FirstName = "Test FirstName " + (new Random()).Next().ToString(),
        Address1 = "Test Address1 " + (new Random()).Next().ToString(),
        CachedLat = 38.024654,
        CachedLng = -77.338814
      };

      // Run the query
      string errorString;
      AddressBookContact resultContact = route4Me.AddAddressBookContact(contact, out errorString);

      Console.WriteLine("");

      if (resultContact != null)
      {
        Console.WriteLine("AddAddressBookContact executed successfully");

        Console.WriteLine("AddressId: {0}", resultContact.AddressId);

        return resultContact;
      }
      else
      {
        Console.WriteLine("AddAddressBookContact error: {0}", errorString);

        return null;
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Function AddAddressBookContact() As AddressBookContact
            ' Create the manager with the API key
            Dim route4Me As New Route4MeSDKLibrary.Route4MeSDK.Route4MeManager(c_ApiKey)

            Dim contact As New AddressBookContact() With { _
                 .FirstName = "Test FirstName " + (New Random()).[Next]().ToString(), _
                 .Address1 = "Test Address1 " + (New Random()).[Next]().ToString(), _
                 .CachedLat = 38.024654, _
                 .CachedLng = -77.338814 _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim resultContact As AddressBookContact = route4Me.AddAddressBookContact(contact, errorString)

            Console.WriteLine("")

            If resultContact IsNot Nothing Then
                Console.WriteLine("AddAddressBookContact executed successfully")

                Console.WriteLine("AddressId: {0}", resultContact.AddressId)

                Return resultContact
            Else
                Console.WriteLine("AddAddressBookContact error: {0}", errorString)

                Return Nothing
            End If
        End Function
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    address_book = route4me.address_book
    response = address_book.create_contact(
        first_name="Juan",
        last_name="Pimentel",
        address_1="17205 RICHMOND TNPK, MILFORD, VA, 22514",
        cached_lat=38.024654,
        cached_lng=-77.338814,
    )
    print 'Address ID: {0}'.format(response.address_id)
    print 'First Name: {0}'.format(response.first_name)
    print 'Last Name: {0}'.format(response.last_name)
    print 'Address: {0}'.format(response.address_1)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.addressbook;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.addressbook.AddressBookManager;
import com.route4me.sdk.services.addressbook.Contact;

public class CreateAddressBookContact {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        AddressBookManager addressBookManager = new AddressBookManager(apiKey);
        Contact contact = new Contact();
        contact.setFirstName("Juan");
        contact.setLastName("Pimentel");
        contact.setAddress1("17205 RICHMOND TNPK, MILFORD, VA, 22514");
        contact.setCachedLat(38.024654);
        contact.setCachedLng(-77.338814);
        try {
            Contact responseObject = addressBookManager.createContact(contact);
            System.out.println(responseObject.toString());
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$AdressBookLocationParameters = AddressBookLocation::fromArray(array(
    "first_name"  => "Test FirstName ".strval(rand(10000, 99999)),
    "address_1"   => "Test Address1 ".strval(rand(10000, 99999)),
    "cached_lat"  => 38.024654,
    "cached_lng"  => -77.338814
));

$abContacts = new AddressBookLocation();

$abcResults = $abContacts->addAdressBookLocation($AdressBookLocationParameters);

echo "address_id = ".strval($abcResults["address_id"])."<br>";

Route4Me::simplePrint($abcResults);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/addressbook"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &addressbook.Service{Client: client}
  
  // To add a contact, you must first create an instance of it.
  contact := &addressbook.Contact{
    FirstName:   "John",
    Alias:       "johny",
    Address1:    "Some address",
    CachedLat:   38.024654,
    CachedLng:   -77.338814,
    Email:       "[email protected]",
    PhoneNumber: "000-000-000",
    StateID:     "5",
    CountryID:   "3",
    City:        "City",
    ZIP:         "00-000",
  }
  newContact, err := service.Add(contact)
  if err != nil {
    // Handle errors
  }
}
package AddAddressBookContact;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::DataTypes::AddressBookContact;

sub AddAddressBookContact {

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $contact = AddressBookContact->new(
        first_name => "Test FirstName " . int(rand(100000)),
        address_1 => "Test Address1 " . int(rand(100000)),
        cached_lat => 38.024654,
        cached_lng => -77.338814
    );

    my $errorString = "";

    my $resultContact = $route4Me->addAddressBookContact($contact, $errorString);

    print "\n";

    if ($resultContact) {
        print "AddAddressBookContact executed successfully\n";

        printf "AddressId: %s\n\n", $resultContact->address_id;

    } else {
        printf "AddAddressBookContact error: %s\n", $errorString;
    }
    return $resultContact;
}
1;
@ECHO OFF
SET url=https://api.route4me.com/api.v4/address_book.php
SET apikey=11111111111111111111111111111111

ECHO ON

curl -o file1.txt -g -k -X POST -H "Content-Type: application/json" -d "@new_address_data.json" "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash
# Add Addressbook Contact

url=https://api.route4me.com/api.v4/address_book.php
apikey=11111111111111111111111111111111

curl -o file1.txt -g -k -X POST -H "Content-Type: application/json" -d "@new_address_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 30
unit CreateLocationUnit;

interface

uses SysUtils, BaseExampleUnit, AddressBookContactUnit;

type
  TCreateLocation = class(TBaseExample)
  public
    function Execute(FirstName, Address: String): TAddressBookContact;
  end;

implementation

function TCreateLocation.Execute(FirstName, Address: String): TAddressBookContact;

var
  ErrorString: String;
  Contact: TAddressBookContact;
begin
  Contact := TAddressBookContact.Create();
  try
    Contact.FirstName := FirstName;
    Contact.Address := Address;
    Contact.Latitude := 38.024654;
    Contact.Longitude := -77.338814;

    Result := Route4MeManager.AddressBookContact.Add(Contact, ErrorString);

    WriteLn('');

    if (Result <> nil) then
    begin
      WriteLn('CreateLocation executed successfully');
      WriteLn(Format('AddressId: %d', [Result.Id.Value]));
    end
    else
      WriteLn(Format('CreateLocation error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Contact);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    Json::Value props(Json::objectValue);
    props["first_name"] = "John";
    props["last_name"] = "Smith";
    props["address_1"] = "Wall Street";
    props["cached_lat"] = 100500;
    props["cached_lng"] = 23450;

    if (route.add_address_book_contacts(props) == 0) {
      cout << "Address book:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
      cout << "Address book not added " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/address_book.php?api_key=...

You can expect this API response:

{
  "created_timestamp": 1464269324,
  "address_id": 7254355,
  "address_group": "",
  "address_alias": "301 MARKET SHELL",
  "address_1": "17205 RICHMOND TNPK, MILFORD, VA, 22514",
  "address_2": "",
  "member_id": 1,
  "first_name": "Gela",
  "last_name": "Gorason",
  "address_email": "[email protected]",
  "address_phone_number": "8046335852",
  "address_city": "Tbilisi",
  "address_state_id": "0",
  "address_country_id": "0",
  "address_zip": "00167",
  "cached_lat": 38.024654,
  "cached_lng": -77.338814,
  "curbside_lat": 38.024654,
  "curbside_lng": -77.338814,
  "address_custom_data": {
    "sales rep id": "545",
    "sales rep name": "Kellye Foster",
    "retailer id": "173907"
  },
  "in_route_count": 0,
  "last_visited_timestamp": 0,
  "last_routed_timestamp": 0,
  "local_time_window_start": null,
  "local_time_window_end": null,
  "local_time_window_start_2": null,
  "local_time_window_end_2": null,
  "service_time": 0,
  "local_timezone_string": "",
  "color": "",
  "address_icon": null,
  "address_stop_type": "DELIVERY",
  "address_cube": null,
  "address_pieces": null,
  "address_reference_no": null,
  "address_revenue": null,
  "address_weight": null,
  "address_priority": null,
  "address_customer_po": null
}

Create a Scheduled Location

The scheduled address book locations are used in the Hybrid Optimization process. Route4Me’s Hybrid Route Editor allows you to plan routes by merging recurrent customer visits from the scheduled address book contacts.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data POST data A valid JSON object string. See the Address Book JSON Schema as a guide.
An example for this language will be added in the future. For now, please see the other languages available for reference.
@ECHO OFF

SET url=https://api.route4me.com/api.v4/address_book.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of creating a new scheduled location in a Route4Me address book.

ECHO ON

:: Add a location, scheduled daily.
curl -o add_scheduled_location1_RESPONSE.json -g -X POST -H "Content-Type: application/json" -d "@add_scheduled_location_data_1.json" "%url%?api_key=%apikey%"

:: Add a location, scheduled weekly.
START /WAIT  curl -o add_scheduled_location2_RESPONSE.json -g -X POST -H "Content-Type: application/json" -d "@add_scheduled_location_data_2.json" "%url%?api_key=%apikey%"

:: Add a location, scheduled monthly (dates mode).
START /WAIT  curl -o add_scheduled_location3_RESPONSE.json -g -X POST -H "Content-Type: application/json" -d "@add_scheduled_location_data_3.json" "%url%?api_key=%apikey%"

:: Add a location, scheduled monthly (nth mode).
START /WAIT  curl -o add_scheduled_location4_RESPONSE.json -g -X POST -H "Content-Type: application/json" -d "@add_scheduled_location_data_4.json" "%url%?api_key=%apikey%"

:: Add a location with daily scheduling and blacklisting.
START /WAIT  curl -o add_scheduled_location6_RESPONSE.json -g -X POST -H "Content-Type: application/json" -d "@add_scheduled_location_data_6.json" "%url%?api_key=%apikey%"

timeout /t 30
An example for this language will be added in the future. For now, please see the other languages available for reference.
public void AddScheduledAddressBookContacts()
{
  Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

  #region // Add a location, scheduled daily.
  Schedule sched1 = new Schedule("daily", false) 
  { 
    enabled = true,
    mode = "daily",
    daily = new schedule_daily(1)
  };

  scheduledContact1 = new AddressBookContact()
  {
    address_1 = "1604 PARKRIDGE PKWY, Louisville, KY, 40214",
    address_alias = "1604 PARKRIDGE PKWY 40214",
    address_group = "Scheduled daily",
    first_name = "Peter",
    last_name = "Newman",
    address_email = "[email protected]",
    address_phone_number = "65432178",
    cached_lat = 38.141598,
    cached_lng = -85.793846,
    address_city = "Louisville",
    address_custom_data = new Dictionary<string, string>() { { "scheduled", "yes" }, { "service type", "publishing" } },
    schedule = new List<Schedule>(){ sched1}
  };

  string errorString;
  scheduledContact1Response = route4Me.AddAddressBookContact(scheduledContact1, out errorString);

  int location1 = scheduledContact1Response.address_id != null ? Convert.ToInt32(scheduledContact1Response.address_id) : -1;
  
  Console.WriteLine("AddressId: {0}", location1);
  #endregion

  #region // Add a location, scheduled weekly.
  Schedule sched2 = new Schedule("weekly", false)
  {
    enabled = true,
    weekly = new schedule_weekly(1, new int[]{1,2,3,4,5})
  };

  scheduledContact2 = new AddressBookContact()
  {
    address_1 = "1407 MCCOY, Louisville, KY, 40215",
    address_alias = "1407 MCCOY 40215",
    address_group = "Scheduled weekly",
    first_name = "Bart",
    last_name = "Douglas",
    address_email = "[email protected]",
    address_phone_number = "95487454",
    cached_lat = 38.202496,
    cached_lng = -85.786514,
    address_city = "Louisville",
    service_time = 600,
    schedule = new List<Schedule>() { sched2 }
  };

  scheduledContact2Response = route4Me.AddAddressBookContact(scheduledContact2, out errorString);

  int location2 = scheduledContact2Response.address_id != null ? Convert.ToInt32(scheduledContact2Response.address_id) : -1;
  
  Console.WriteLine("AddressId: {0}", location2);
  #endregion

  #region // Add a location, scheduled monthly (dates mode).
  Schedule sched3 = new Schedule("monthly", false)
  {
    enabled = true,
    monthly = new schedule_monthly(_every: 1, _mode: "dates", _dates: new int[] { 20, 22, 23, 24, 25 })
  };

  scheduledContact3 = new AddressBookContact()
  {
    address_1 = "4805 BELLEVUE AVE, Louisville, KY, 40215",
    address_2 = "4806 BELLEVUE AVE, Louisville, KY, 40215",
    address_alias = "4805 BELLEVUE AVE 40215",
    address_group = "Scheduled monthly",
    first_name = "Bart",
    last_name = "Douglas",
    address_email = "[email protected]",
    address_phone_number = "95487454",
    cached_lat = 38.178844,
    cached_lng = -85.774864,
    address_country_id = "US",
    address_state_id = "KY",
    address_zip = "40215",
    address_city = "Louisville",
    service_time = 750,
    schedule = new List<Schedule>() { sched3 },
    color = "red"
  };

  scheduledContact3Response = route4Me.AddAddressBookContact(scheduledContact3, out errorString);

  int location3 = scheduledContact3Response.address_id != null ? Convert.ToInt32(scheduledContact3Response.address_id) : -1;
  
  Console.WriteLine("AddressId: {0}", location3);
  #endregion

  #region // Add a location, scheduled monthly (nth mode).
  Schedule sched4 = new Schedule("monthly", false)
  {
    enabled = true,
    monthly = new schedule_monthly(_every: 1, _mode: "nth", _nth: new Dictionary<int,int>() {{1,4}})
  };

  scheduledContact4 = new AddressBookContact()
  {
    address_1 = "730 CECIL AVENUE, Louisville, KY, 40211",
    address_alias = "730 CECIL AVENUE 40211",
    address_group = "Scheduled monthly",
    first_name = "David",
    last_name = "Silvester",
    address_email = "[email protected]",
    address_phone_number = "36985214",
    cached_lat = 38.248684,
    cached_lng = -85.821121,
    address_city = "Louisville",
    service_time = 450,
    address_custom_data = new Dictionary<string, string>() { { "scheduled", "yes" }, { "service type", "library" } },
    schedule = new List<Schedule>() { sched4 },
    address_icon = "emoji/emoji-bus"
  };

  scheduledContact4Response = route4Me.AddAddressBookContact(scheduledContact4, out errorString);

  int location4 = scheduledContact4Response.address_id != null ? Convert.ToInt32(scheduledContact4Response.address_id) : -1;
  
  Console.WriteLine("AddressId: {0}", location4);
  #endregion

  #region // Add a location with daily scheduling and blacklisting.
  Schedule sched5 = new Schedule("daily", false)
  {
    enabled = true,
    mode = "daily",
    daily = new schedule_daily(1)
  };


  scheduledContact5 = new AddressBookContact()
  {
    address_1 = "4629 HILLSIDE DRIVE, Louisville, KY, 40216",
    address_alias = "4629 HILLSIDE DRIVE 40216",
    address_group = "Scheduled daily",
    first_name = "Kim",
    last_name = "Shandor",
    address_email = "[email protected]",
    address_phone_number = "9874152",
    cached_lat = 38.176067,
    cached_lng = -85.824638,
    address_city = "Louisville",
    address_custom_data = new Dictionary<string, string>() { { "scheduled", "yes" }, { "service type", "appliance" } },
    schedule = new List<Schedule>() { sched5 },
    schedule_blacklist = new string[] { "2017-12-22", "2017-12-23" },
    service_time = 300
  };

  scheduledContact5Response = route4Me.AddAddressBookContact(scheduledContact5, out errorString);

  int location5 = scheduledContact5Response.address_id != null ? Convert.ToInt32(scheduledContact5Response.address_id) : -1;
  
  Console.WriteLine("AddressId: {0}", location5);
  #endregion
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

#region // Add a location, scheduled daily with custom data.
$AdressBookLocationParameters = AddressBookLocation::fromArray(array(
    "address_1"            => "1604 PARKRIDGE PKWY, Louisville, KY, 40214",
    "address_alias"        => "1604 PARKRIDGE PKWY 40214",
    "address_group"        => "Scheduled daily",
    "first_name"           => "Peter",
    "last_name"            => "Newman",
    "address_email"        => "[email protected]",
    "address_phone_number" => "65432178",
    "cached_lat"           => 38.141598,
    "cached_lng"           => -85.793846,
    "address_city"         => "Louisville",
    "address_custom_data"  => array("scheduled"   => "yes", 
                                    "service type" => "publishing"),
    "schedule" => array(array(
        "enabled" => true,
        "mode"    => "daily",
        "daily"   => array("every" => 1)
    )),
    "service_time" => 900
));

$abContacts1 = new AddressBookLocation();

$abcResults1 = $abContacts1->addAdressBookLocation($AdressBookLocationParameters);

echo "address_id = ".strval($abcResults1["address_id"])."<br>";

Route4Me::simplePrint($abcResults1);
echo "<br>";
#endregion

#region // Add a location, scheduled weekly.
$AdressBookLocationParameters = AddressBookLocation::fromArray(array(
    "address_1"            => "1407 MCCOY, Louisville, KY, 40215",
    "address_alias"        => "1407 MCCOY 40215",
    "address_group"        => "Scheduled weekly",
    "first_name"           => "Bart",
    "last_name"            => "Douglas",
    "address_email"        => "[email protected]",
    "address_phone_number" => "95487454",
    "cached_lat"           => 38.202496,
    "cached_lng"           => -85.786514,
    "curbside_lat"         => 38.202496,
    "curbside_lng"         => -85.786514,
    "address_city"         => "Louisville",
    "schedule" => array(array(
        "enabled" => true,
        "mode"    => "weekly",
        "weekly"  => array(
            "every"    => 1,
            "weekdays" => array(1, 2, 3, 4, 5)
        )
    )),
    "service_time" => 600
));

$abContacts2 = new AddressBookLocation();

$abcResults2 = $abContacts2->addAdressBookLocation($AdressBookLocationParameters);

echo "address_id = ".strval($abcResults2["address_id"])."<br>";

Route4Me::simplePrint($abcResults2);
echo "<br>";
#endregion

#region // Add a location, scheduled monthly (dates mode).
$AdressBookLocationParameters = AddressBookLocation::fromArray(array(
    "address_1"            => "4805 BELLEVUE AVE, Louisville, KY, 40215",
    "address_2"            => "4806 BELLEVUE AVE, Louisville, KY, 40215",
    "address_alias"        => "4805 BELLEVUE AVE 40215",
    "address_group"        => "Scheduled monthly",
    "first_name"           => "Bart",
    "last_name"            => "Douglas",
    "address_email"        => "[email protected]",
    "address_phone_number" => "95487454",
    "cached_lat"           => 38.178844,
    "cached_lng"           => -85.774864,
    "curbside_lat"         => 38.178844,
    "curbside_lng"         => -85.774864,
    "address_city"         => "Louisville",
    "address_country_id"   => "US",
    "address_state_id"     => "KY",
    "address_zip"          => "40215",
    "schedule" => array(array(
        "enabled" => true,
        "mode"    => "monthly",
        "monthly" => array(
            "every" => 1,
            "mode"  => "dates",
            "dates" => array(20, 22, 23, 24, 25)
        )
    )),
    "service_time" => 750,
    "color" => "red"
));

$abContacts3 = new AddressBookLocation();

$abcResults3 = $abContacts3->addAdressBookLocation($AdressBookLocationParameters);

echo "address_id = ".strval($abcResults3["address_id"])."<br>";

Route4Me::simplePrint($abcResults3);
echo "<br>";
#endregion

#region // Add a location, scheduled monthly (nth mode).
$AdressBookLocationParameters = AddressBookLocation::fromArray(array(
    "address_1"            => "730 CECIL AVENUE, Louisville, KY, 40211",
    "address_alias"        => "730 CECIL AVENUE 40211",
    "address_group"        => "Scheduled monthly",
    "first_name"           => "David",
    "last_name"            => "Silvester",
    "address_email"        => "[email protected]",
    "address_phone_number" => "36985214",
    "cached_lat"           => 38.248684,
    "cached_lng"           => -85.821121,
    "curbside_lat"         => 38.248684,
    "curbside_lng"         => -85.821121,
    "address_city"         => "Louisville",
    "address_custom_data" => array(
        "scheduled"    => "yes",
        "service type" => "library"
    ),
    "schedule" => array(array(
        "enabled" => true,
        "mode"    => "monthly",
        "monthly" => array(
            "every" => 1,
            "mode"  => "nth",
            "nth"   => array(
                "n"    => 1,
                "what" => 4
            )
        )
    )),
    "service_time" => 450,
    "address_icon" => "emoji/emoji-bus"
));

$abContacts4 = new AddressBookLocation();

$abcResults4 = $abContacts4->addAdressBookLocation($AdressBookLocationParameters);

echo "address_id = ".strval($abcResults4["address_id"])."<br>";

Route4Me::simplePrint($abcResults4);
echo "<br>";
#endregion

#region // Add a location with daily scheduling and blacklisting.
$AdressBookLocationParameters = AddressBookLocation::fromArray(array(
    "address_1"            => "4629 HILLSIDE DRIVE, Louisville, KY, 40216",
    "address_alias"        => "4629 HILLSIDE DRIVE 40216",
    "address_group"        => "Scheduled daily",
    "first_name"           => "Kim",
    "last_name"            => "Shandor",
    "address_email"        => "[email protected]",
    "address_phone_number" => "9874152",
    "cached_lat"           => 38.176067,
    "cached_lng"           => -85.824638,
    "curbside_lat"         => 38.176067,
    "curbside_lng"         => -85.824638,
    "address_city"         => "Louisville",
    "address_custom_data"  => array(
        "scheduled"   => "yes",
        "service type" => "appliance"
    ),
    "schedule" => array(
        "enabled" => true,
        "mode"    => "daily",
        "daily"   => array("every" => 1)
    ),
    "schedule_blacklist" => array("2017-02-24", "2017-02-25"),
    "service_time"       => 300
));

$abContacts5 = new AddressBookLocation();

$abcResults5 = $abContacts5->addAdressBookLocation($AdressBookLocationParameters);

echo "address_id = ".strval($abcResults5["address_id"])."<br>";

Route4Me::simplePrint($abcResults5);
#endregion
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/address_book.php?api_key=...

You can expect this API response:

{
  "created_timestamp": 1509889058,
  "address_id": 23142492,
  "address_group": "Scheduled daily",
  "address_alias": "1604 PARKRIDGE PKWY 40214",
  "address_1": "1604 PARKRIDGE PKWY, Louisville, KY, 40214",
  "address_2": "",
  "member_id": 1,
  "first_name": "Peter",
  "last_name": "Newman",
  "address_email": "[email protected]",
  "address_phone_number": "65432178",
  "address_city": "Louisville",
  "address_state_id": null,
  "address_country_id": "0",
  "address_zip": "",
  "cached_lat": 38.141598,
  "cached_lng": -85.793846,
  "curbside_lat": 38.141598,
  "curbside_lng": -85.793846,
  "address_custom_data": {
    "scheduled": "yes",
    "service type": "publishing"
  },
  "schedule": [{
    "enabled": true,
    "mode": "daily",
    "daily": {
      "every": 1
    }
  }],
  "schedule_blacklist": null,
  "in_route_count": 0,
  "last_visited_timestamp": 0,
  "last_routed_timestamp": 0,
  "local_time_window_start": null,
  "local_time_window_end": null,
  "local_time_window_start_2": null,
  "local_time_window_end_2": null,
  "service_time": 900,
  "local_timezone_string": null,
  "color": null,
  "address_icon": null,
  "address_stop_type": "DELIVERY",
  "address_cube": null,
  "address_pieces": null,
  "address_reference_no": null,
  "address_revenue": null,
  "address_weight": null,
  "address_priority": null,
  "address_customer_po": null
}

Remove Locations

Removes some locations from an address book.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
address_ids array An array of location IDs
<job id="AddressbookDeleteContact">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address_book.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="address_data_for_delete.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpDeleteRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void RemoveAddressBookContacts(string[] addressIds)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Run the query
      string errorString;
      bool removed = route4Me.RemoveAddressBookContacts(addressIds, out errorString);

      Console.WriteLine("");

      if (removed)
      {
        Console.WriteLine("RemoveAddressBookContacts executed successfully, {0} contacts deleted", addressIds.Length);
      }
      else
      {
        Console.WriteLine("RemoveAddressBookContacts error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub RemoveAddressBookContacts(addressIds As String())
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim removed As Boolean = route4Me.RemoveAddressBookContacts(addressIds, errorString)

            Console.WriteLine("")

            If removed Then
                Console.WriteLine("RemoveAddressBookContacts executed successfully, {0} contacts deleted", addressIds.Length)
            Else
                Console.WriteLine("RemoveAddressBookContacts error: {0}", errorString)
            End If

        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    address_book = route4me.address_book
    response = address_book.create_contact(
        first_name="Juan",
        last_name="Pimentel",
        address_1="17205 RICHMOND TNPK, MILFORD, VA, 22514",
        cached_lat=38.024654,
        cached_lng=-77.338814,
    )
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Address ID: {0}'.format(response.address_id)
        print 'First Name: {0}'.format(response.first_name)
        print 'Last Name: {0}'.format(response.last_name)
        print 'Address: {0}'.format(response.address_1)
        print 'Deleting this Contact'
        address_ids = [response.address_id, ]
        response = address_book.delete_addressbook_contact(
            address_ids=address_ids)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Deleted: {}'.format(response.status)


if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.addressbook;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.addressbook.AddressBookManager;
import com.route4me.sdk.services.addressbook.Contact;

import java.util.ArrayList;
import java.util.List;

public class DeleteAddressBookContact {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        AddressBookManager addressBookManager = new AddressBookManager(apiKey);
        Contact contact = new Contact();
        contact.setFirstName("Juan");
        contact.setLastName("Pimentel");
        contact.setAddress1("17205 RICHMOND TNPK, MILFORD, VA, 22514");
        contact.setCachedLat(38.024654);
        contact.setCachedLng(-77.338814);
        try {
            Contact responseObject = addressBookManager.createContact(contact);
            Number addressID = responseObject.getAddressId();
            List<Number> addressIDs = new ArrayList<>();
            addressIDs.add(addressID);
            System.out.println("Deleting Address ID: " + addressID);
            boolean response = addressBookManager.deleteContact(addressIDs);
            System.out.println(response);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$AdressBookLocationParameters = AddressBookLocation::fromArray(array(
    "first_name"  => "Test FirstName ".strval(rand(10000, 99999)),
    "address_1"   => "Test Address1 ".strval(rand(10000, 99999)),
    "cached_lat"  => 38.024654,
    "cached_lng"  => -77.338814
));

$abContacts = new AddressBookLocation();

$createdContact = $abContacts->addAdressBookLocation($AdressBookLocationParameters);

$address_id = -1;

if (isset($createdContact['address_id'])) {
    $address_id = $createdContact["address_id"];
}

assert($address_id!=-1, "Creating of Address Book Location has failed. Try again!<br>");

echo "Address Book Location with address_id = ".strval($address_id)." was successfully added.<br>";

$addressBookLocations = array($address_id);

$abLocations = new AddressBookLocation();

$deleteResult = $abLocations->deleteAdressBookLocation($addressBookLocations);

assert(isset($deleteResult['status']), "Address Book Location delete operation failed!<br>");
assert($deleteResult['status'], "Address Book Location delete operation failed!<br>");

echo "Address Book Location with address_id = ".strval($address_id)." was successfully deleted.<br>";
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/addressbook"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &addressbook.Service{Client: client}
  
  removed, err := service.Delete([]string{"contact-id"})// It's likely your contact ID is in uint64. You will need to convert it to a string by calling strconv.FormatUint(contact-id, 10)
  if err != nil {
    // handle errors
    return
  }
}
package RemoveAddressBookContacts;
use strict;
use warnings FATAL => 'all';

sub RemoveAddressBookContacts {
    my ($self, $addressIds) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $errorString;
    my $removed = $route4Me->removeAddressBookContacts($addressIds, $errorString);

    print "\n";

    if ($removed)
    {
        printf "RemoveAddressBookContacts executed successfully, %s contacts deleted\n", scalar @$addressIds;
    }
    else
    {
        printf "RemoveAddressBookContacts error: %s\n", $errorString;
    }
}
1;
@ECHO OFF
SET url=https://api.route4me.com/api.v4/address_book.php
SET apikey=11111111111111111111111111111111

ECHO ON

curl -o file1.txt -g -k -X DELETE -H "Content-Type: application/json" -d "@address_data_for_delete.json" "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address_book.php
apikey=11111111111111111111111111111111

curl -o file1.txt -g -k -X DELETE -H "Content-Type: application/json" -d "@address_data_for_delete.json" "$url?api_key=$apikey"

sleep 20
unit RemoveLocationsUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TRemoveLocations = class(TBaseExample)
  public
    procedure Execute(AddressIds: TArray<integer>);
  end;

implementation

procedure TRemoveLocations.Execute(AddressIds: TArray<integer>);

var
  ErrorString: String;
  Removed: boolean;
begin
  Removed := Route4MeManager.AddressBookContact.Remove(AddressIds, ErrorString);

  WriteLn('');

  if (Removed) then
    WriteLn(Format('RemoveLocations executed successfully, %d contacts deleted',
      [Length(AddressIds)]))
  else
    WriteLn(Format('RemoveLocations error: "%s"', [ErrorString]));
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api.v4/address_book.php?api_key=...

You can expect this API response:

{"status":true}

Get a Location

Get an address book location using the value of the query parameter. Records with fields that match or contain the search value are the ones returned.


PARAMETERS

Parameter Type Description
api_key string API key of the user
query string Search value
offset integer Search starting position
limit integer The number of records to return.
<job id="Addressbook Get Locations By Any Fields Specified Text">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address_book.php"
      apikey="11111111111111111111111111111111"
      
      ' The example demonstrates the searching for one or more locations using a search value provided in the `query` parameter.

      search_text="technology"
      offset="0"
      limit="20"
      
      url=url&"?api_key="&apikey
      url=url&"&query="&search_text
      url=url&"&offset="&offset
      url=url&"&limit="&limit
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
ECHO OFF
SET url=https://api.route4me.com/api.v4/address_book.php
SET apikey=11111111111111111111111111111111

:: The example demonstrates the searching for one or more locations using a search value provided in the `query` parameter.

SET search_text="technology"

ECHO ON

curl -o file1.txt -k -X GET "%url%?api_key=%apikey%&query=%search_text%&offset=0&limit=20"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address_book.php
apikey=11111111111111111111111111111111

# The example demonstrates the searching for one or more locations using a search value provided in the `query` parameter.

search_text="technology"
offset=0
limit=20

curl -o file1.txt -k -X GET "$url?api_key=$apikey&query=$search_text&offset=$offset&limit=$limit"

echo "Finished..."

sleep 15
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$abLocation = new AddressBookLocation();

// Get random address book location
$AdressBookLocationParameters = array(
        "limit"   => 30,
        "offset"  => 0
);

$randomLocation = $abLocation->getRandomAddressBookLocation($AdressBookLocationParameters);

if (assert($randomLocation!=null, "Can't get a random address book location"));

// Get the address book location using the address_id
$addressID = $randomLocation["address_id"];
$abcResult = $abLocation->getAddressBookLocation($addressID);

$results = $abLocation->getValue($abcResult, "results");

Route4Me::simplePrint($results);
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Address Book Location
        /// </summary>
        public void GetAddressbookLocation()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AddressBookParameters addressBookParameters = new AddressBookParameters
            {
                Query = "david",
                Offset = 0,
                Limit = 20
            };

            // Run the query
            uint total = 0;
            string errorString = "";
            AddressBookContact[] contacts = route4Me.GetAddressBookLocation(addressBookParameters, out total, out errorString);

            Console.WriteLine("");

            if (contacts != null)
            {
                Console.WriteLine("GetAddressbookLocation executed successfully, {0} contacts returned, total = {1}", contacts.Length, total);

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("GetAddressbookLocation error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetAddressbookLocation()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim addressBookParameters As New AddressBookParameters() With { _
                .Query = "david", _
                .Offset = 0, _
                .Limit = 20 _
            }

            ' Run the query
            Dim total As UInteger
            Dim errorString As String = ""
            Dim contacts As AddressBookContact() = route4Me.GetAddressBookLocation(addressBookParameters, total, errorString)

            Console.WriteLine("")

            If contacts IsNot Nothing Then
                Console.WriteLine("GetAddressbookLocation executed successfully, {0} contacts returned, total = {1}", contacts.Length, total)

                Console.WriteLine("")
            Else
                Console.WriteLine("GetAddressbookLocation error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    address_book = route4me.address_book
    response = address_book.get_addressbook_contacts(limit=10, Offset=5)
    if 'errors' in response.keys():
        print '. '.join(response['errors'])
    else:
        address_id = "'{}'".format(response['results'][0]['address_id'])
        response = address_book.get_addressbook_contact(address_id=address_id)
        if 'errors' in response.keys():
            print '. '.join(response['errors'])
        else:
            contacts = response['results']
            for i, contact in enumerate(contacts):
                print 'Address: {0} -  ID: {1}'.format(i+1, contact['address_id'])
                print '\tFirst Name: {0}'.format(contact['first_name'])
                print '\tLast Name: {0}'.format(contact['last_name'])
                print '\tAddress: {0}'.format(contact['address_1'])

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.addressbook;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.addressbook.AddressBookManager;
import com.route4me.sdk.services.addressbook.Contact;
import com.route4me.sdk.services.addressbook.ContactsRequest;

import java.util.List;

public class GetAddressBookContact {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        AddressBookManager addressBookManager = new AddressBookManager(apiKey);
        try {
            List<Contact> contacts = addressBookManager.getContacts(new ContactsRequest().setLimit(10));
            Number addressID = contacts.get(0).getAddressId();
            System.out.println(addressID);
            Contact contact = addressBookManager.getContact(addressID);
            System.out.println(contact.toString());
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/addressbook"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &addressbook.Service{Client: client}
  
  query := &addressbook.Query{
        Query:  "technology",
        Offset: 0,
        Limit:  20,
    }
    locations, total, err := service.Get(query)
    if err != nil {
        // handle errors
        return
    }
    // do something with locations
}
unit GetLocationUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetLocation = class(TBaseExample)
  public
    procedure Execute(Query: String);
  end;

implementation

uses AddressBookContactUnit;

procedure TGetLocation.Execute(Query: String);

var
  ErrorString: String;
  Total: integer;
  Contacts: TAddressBookContactList;
  Limit, Offset: integer;
begin
  Limit := 10;
  Offset := 0;

  Contacts := Route4MeManager.AddressBookContact.Find(
    Query, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (Contacts.Count > 0) then
    begin
      WriteLn(Format('GetLocation executed successfully, ' +
        '%d contacts returned, total = %d', [Contacts.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetLocation error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Contacts);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    if (route.get_address_book_contacts_by_text("Wall") == 0) {
      cout << "Found address:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
      cout << "Address not found: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    
    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/address_book.php?api_key=...&query=...&offset=...&limit=...


See the sample JSON response of this method.


Get Locations by IDs

Get locations from an address book using a specified list of location IDs.


PARAMETERS

Parameter Type Description
api_key string API key of the user
address_id string A comma-separated list of address IDs.
<job id="Addressbook Get Locations By IDs">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address_book.php"
      apikey="11111111111111111111111111111111"
      
      ' Get contacts by listed IDs
      addr_id="4623361,6281217"
      
      url=url&"?api_key="&apikey
      url=url&"&address_id="&addr_id
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
#!/usr/bin/python

from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    address_book = route4me.address_book
    response = address_book.get_addressbook_contacts(limit=10, Offset=5)
    if 'errors' in response.keys():
        print '. '.join(response['errors'])
    else:
        address_id = "'{}'".format(response['results'][0]['address_id'])
        response = address_book.get_addressbook_contact(address_id=address_id)
        if 'errors' in response.keys():
            print '. '.join(response['errors'])
        else:
            contacts = response['results']
            for i, contact in enumerate(contacts):
                print 'Address: {0} -  ID: {1}'.format(i+1, contact['address_id'])
                print '\tFirst Name: {0}'.format(contact['first_name'])
                print '\tLast Name: {0}'.format(contact['last_name'])
                print '\tAddress: {0}'.format(contact['address_1'])

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.addressbook;

import com.route4me.sdk.Route4Me;
import com.route4me.sdk.managers.AddressBookManager;
import com.route4me.sdk.model.Contact;

public class GetAddressBookContact {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        Route4Me route4me = new Route4Me(apiKey);
        AddressBookManager addressBookManager = route4me.getAddressBookManager();
        Contact responseObject = addressBookManager.getContacts(10, 5);
        Number addressID = responseObject.getResults().get(0).getAddress_id();
        System.out.println(addressID);
        responseObject = addressBookManager.getContact(addressID);
        for (Contact contact : responseObject.getResults()) {
            System.out.println("Address ID: " + contact.getAddress_id());
            System.out.println("First Name: " + contact.getFirst_name());
            System.out.println("Last Name: " + contact.getLast_name());
            System.out.println("Address 1: " + contact.getAddress_1());
            System.out.println("Address 2: " + contact.getAddress_2());
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Get two random location IDs

$adressBookLocationParameters = array(
    "limit"   => 30,
    "offset"  => 0
); 

$abContacts = new AddressBookLocation();

$abcResults = $abContacts->getAddressBookLocations($adressBookLocationParameters);

$results = $abContacts->getValue($abcResults, "results");

$contactsNumber = sizeof($results);
$id1 = $results[rand(1, $contactsNumber) - 1]['address_id'];
$id2 = $results[rand(1, $contactsNumber) - 1]['address_id'];

$ids = array();
$ids['address_id'] = $id1.",".$id2;

// Retrieve address book locations by address_ids
$ablocation = new AddressBookLocation();

$abcResult = $ablocation->getAddressBookLocations($ids);

$results = $ablocation->getValue($abcResult, "results");

foreach ($results as $result) {
    Route4Me::simplePrint($result);
    echo "<br>";
}
ECHO OFF
SET url=https://api.route4me.com/api.v4/address_book.php
SET apikey=11111111111111111111111111111111

:: Get contacts by listed IDs
SET addr_id=4623361,6281217

ECHO ON

curl -o file1.txt -k -X GET "%url%?api_key=%apikey%&address_id=%addr_id%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address_book.php
apikey=11111111111111111111111111111111

# Get locations by listed IDs

addr_id=4623361,6281217

curl -o file1.txt -k -X GET "$url?api_key=$apikey&address_id=$addr_id"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Search Locations By IDs
        /// </summary>
        public void SearchLocationsByIDs()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AddressBookParameters addressBookParameters = new AddressBookParameters { AddressId = "2640129,4621569" };

            // Run the query
            uint total = 0;
            string errorString = "";
            AddressBookContact[] contacts = route4Me.GetAddressBookLocation(addressBookParameters, out total, out errorString);

            Console.WriteLine("");

            if (contacts != null)
            {
                Console.WriteLine("SearchLocationsByIDs executed successfully, {0} contacts returned, total = {1}", contacts.Length, total);

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchLocationsByIDs error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchLocationsByIDs()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim addressBookParameters As New AddressBookParameters() With { _
                .AddressId = "2640129,4621569" _
            }

            ' Run the query
            Dim total As UInteger
            Dim errorString As String = ""
            Dim contacts As AddressBookContact() = route4Me.GetAddressBookLocation(addressBookParameters, total, errorString)

            Console.WriteLine("")

            If contacts IsNot Nothing Then
                Console.WriteLine("SearchLocationsByIDs executed successfully, {0} contacts returned, total = {1}", contacts.Length, total)

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchLocationsByIDs error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/addressbook"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &addressbook.Service{Client: client}
  
  query := &addressbook.Query{
        AddressID: "4623361,6281217" //comma separated
    }
    locations, total, err := service.Get(query) 
    if err != nil {
        //handle errors
        return
    }
    // do something with locations
}
unit GetLocationsByIdsUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetLocationsByIds = class(TBaseExample)
  public
    procedure Execute(AddressesIds: TArray<integer>);
  end;

implementation

uses AddressBookContactUnit;

procedure TGetLocationsByIds.Execute(AddressesIds: TArray<integer>);

var
  ErrorString: String;
  Contacts: TAddressBookContactList;
begin
  Contacts := Route4MeManager.AddressBookContact.Get(AddressesIds, ErrorString);
  try
    WriteLn('');

    if (Contacts.Count > 0) then
    begin
      WriteLn(Format('GetLocationsByIds executed successfully, ' +
        '%d contacts returned', [Contacts.Count]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetLocationsByIds error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Contacts);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    if (route.get_address_book_contacts("4621569") == 0) {
      cout << "Found address:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
      cout << "Address book not found: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    
    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/address_book.php?api_key=...&address_id=...

You can expect this API response:

{
  "results": [{
    "created_timestamp": 1449084359,
    "address_id": 4623361,
    "address_group": "",
    "address_alias": "",
    "address_1": "102 Salina Lane, Goose Creek, SC, 29445",
    "address_2": "",
    "member_id": 177496,
    "first_name": "Juan Updated Updated Upda",
    "last_name": "Washington",
    "address_email": "[email protected]",
    "address_phone_number": "843-797-7874",
    "address_city": "",
    "address_state_id": null,
    "address_country_id": null,
    "address_zip": "",
    "cached_lat": 32.96225,
    "cached_lng": -80.020271,
    "curbside_lat": 32.96225,
    "curbside_lng": -80.020271,
    "address_custom_data": {
      "staff number": "105123", "fsc": "Gulzinski, Melissa",
      "sr merch": "Yes", "lms technology": "Yes", "both": "Yes",
      "jas only": "", "bhn only": "", "visits l3m": "202",
      "pay l3m": "2533.36", "bonuses lm3": "30.75", "weight": 0,
      "cost": 0, "revenue": 0, "cube": 0, "pieces": 0
    },
    "in_route_count": 0,
    "last_visited_timestamp": 0,
    "last_routed_timestamp": 0,
    "local_time_window_start": null,
    "local_time_window_end": null,
    "local_time_window_start_2": null,
    "local_time_window_end_2": null,
    "service_time": null,
    "local_timezone_string": null,
    "color": null,
    "address_icon": null,
    "address_stop_type": "DELIVERY",
    "address_cube": null,
    "address_pieces": null,
    "address_reference_no": null,
    "address_revenue": null,
    "address_weight": null,
    "address_priority": null,
    "address_customer_po": null
  }],
  "total": 1
}

Get Locations

Get all locations from a user’s address book.


PARAMETERS

Parameter Type Description
api_key string API key of the user
offset integer Search starting position
limit integer The number of records to return.
<job id="Addressbook Get Locations">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address_book.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void GetAddressBookContacts()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      AddressBookParameters addressBookParameters = new AddressBookParameters()
      {
        Limit = 10,
        Offset = 0
      };

      // Run the query
      uint total;
      string errorString;
      AddressBookContact[] contacts = route4Me.GetAddressBookContacts(addressBookParameters, out total, out errorString);

      Console.WriteLine("");

      if (contacts != null)
      {
        Console.WriteLine("GetAddressBookContacts executed successfully, {0} contacts returned, total = {1}", contacts.Length, total);
        Console.WriteLine("");
      }
      else
      {
        Console.WriteLine("GetAddressBookContacts error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetAddressBookContacts()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim addressBookParameters As New AddressBookParameters() With {.Limit = 10, .Offset = 0}

            ' Run the query
            Dim total As UInteger
            Dim errorString As String = ""
            Dim contacts As AddressBookContact() = route4Me.GetAddressBookContacts(addressBookParameters, total, errorString)

            Console.WriteLine("")

            If contacts IsNot Nothing Then
                Console.WriteLine("GetAddressBookContacts executed successfully, {0} contacts returned, total = {1}", contacts.Length, total)

                Console.WriteLine("")
            Else
                Console.WriteLine("GetAddressBookContacts error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    address_book = route4me.address_book
    response = address_book.get_addressbook_contacts(limit=10, Offset=5)
    if 'errors' in response.keys():
        print '. '.join(response['errors'])
    else:
        contacts = response['results']
        for i, contact in enumerate(contacts):
            print 'Address: {0} -  ID: {1}'.format(i+1, contact['address_id'])
            print '\tFirst Name: {0}'.format(contact['first_name'])
            print '\tLast Name: {0}'.format(contact['last_name'])
            print '\tAddress: {0}'.format(contact['address_1'])

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.addressbook;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.addressbook.AddressBookManager;
import com.route4me.sdk.services.addressbook.Contact;
import com.route4me.sdk.services.addressbook.ContactsRequest;

import java.util.List;

public class GetAddressBookContacts {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        AddressBookManager addressBookManager = new AddressBookManager(apiKey);
        try {
            List<Contact> contacts = addressBookManager.getContacts(new ContactsRequest().setLimit(10));
            for (Contact c : contacts) {
                System.out.println(c);
            }
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Route;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example refers to getting all address book locations.

$AdressBookLocationParameters = array(
    "limit"   => 30,
    "offset"  => 0
);

$abContacts = new AddressBookLocation();

$abcResults = $abContacts->getAddressBookLocations($AdressBookLocationParameters);

$results = $abContacts->getValue($abcResults, "results");

foreach ($results as $result) {
  Route4Me::simplePrint($result);
    echo "<br>";
}
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/addressbook"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &addressbook.Service{Client: client}
  
  query := &addressbook.Query{
    Limit:  10, // How many contacts to return
    Offset: 0, // The offset (how many records to skip) of contacts.
  }
  contacts, total, err := service.Get(query)
  if err != nil {
    // handle errors
    return
  }
  // do something with contacts, it's []Contact
  // variable `total` represents the total number of contacts in your addressbook
}
package GetAddressBookContacts;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::DataTypes::AddressBookParameters;

sub GetAddressBookContacts {
    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $addressBookParameters = AddressBookParameters->new (
        limit  => 10,
        offset => 0
    );
    my $errorString;
    my $total;
    my @contacts = $route4Me->getAddressBookContacts( $addressBookParameters, \$total, \$errorString );

    print "\n";

    if (@contacts)
    {
        printf "GetAddressBookContacts executed successfully, %s contacts returned, total = %s\n", scalar @contacts, $total;
        print "\n";
    }
    else
    {
        printf "GetAddressBookContacts error: {0}", $errorString;
    }
}
1;
ECHO OFF
SET url=https://api.route4me.com/api.v4/address_book.php
SET apikey=11111111111111111111111111111111

ECHO ON

curl -o file1.txt -k -X GET "%url%?api_key=%apikey%&offset=0&limit=10"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address_book.php
apikey=11111111111111111111111111111111

curl -o file1.txt -k -X GET "$url?api_key=$apikey&offset=0&limit=10"

echo "Finished..."

sleep 15
unit GetLocationsUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetLocations = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses AddressBookContactUnit;

procedure TGetLocations.Execute;

var
  ErrorString: String;
  Total: integer;
  Contacts: TAddressBookContactList;
  Limit, Offset: integer;
begin
  Limit := 10;
  Offset := 0;

  Contacts := Route4MeManager.AddressBookContact.Get(Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (Contacts.Count > 0) then
    begin
      WriteLn(Format('GetLocations executed successfully, ' +
        '%d contacts returned, total = %d', [Contacts.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('GetLocations error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Contacts);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    if (route.get_address_book_contacts("") == 0) {
      cout << "All contacts:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
      cout << "No contacts " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    // global cleanup
    CRoute4Me::cleanup();

    return 0;
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/address_book.php?api_key=...&offset=...&limit=...


See the sample JSON response of this method.


a) Get or search for some locations using the provided parameters.

Use the query parameter to retrieve records with fields that match your search value.

On the other hand, use the offset and limit parameters to specify the search position and limit the number of records returned, respectively. Lastly, use the fields parameter if you want to specify a limited number of fields for each record returned.


PARAMETERS

Parameter Type Description
api_key string API key of the user
query string Search value
fields string A comma-separated list of field names.
offset integer Search starting position
limit integer The number of records to return.
<job id="Addressbook Get Contacts By Fields text">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address_book.php"
      apikey="11111111111111111111111111111111"
      
      ' The example demonstrates how to search/retrieve for Addressbook contacts using some parameters that limit or customize the result.
      
      jFile=""
      
      search_text="david"
      fields="first_name,address_email"
      offset="0"
      limit="20"
      
      url=url&"?api_key="&apikey
      url=url&"&query="&search_text
      url=url&"&fields="&fields
      url=url&"&offset="&offset
      url=url&"&limit="&limit
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest2 url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
ECHO OFF
SET url=https://api.route4me.com/api.v4/address_book.php
SET apikey=11111111111111111111111111111111

:: The example demonstrates how to search/retrieve for Addressbook contacts using some parameters that limit or customize the result.

SET search_text="peter"
SET fields="first_name,address_email"
SET offset=0
SET limit=20

ECHO ON

curl -o file1.txt -k -X GET "%url%?api_key=%apikey%&query=%search_text%&fields=%fields%&offset=%offset%&limit=%limit%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address_book.php
apikey=11111111111111111111111111111111

# The example demonstrates how to search/retrieve for Addressbook contacts using some parameters that limit or customize the result.

search_text="david"
fields="first_name,address_email"
offset=0
limit=20

curl -o file1.txt -k -X GET "$url?api_key=$apikey&query=$search_text&fields=$fields&offset=$offset&limit=$limit"

echo "Finished..."

sleep 15
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$ablocation = new AddressBookLocation();

// The example refers to the process of searching for a specific text and specifying only a few fields to include in the result.

$params = array(
    'query'   => 'David',
    'fields'  => 'first_name,address_email',
    'offset'  => 0,
    'limit'   => 5
);

$abcResult = $ablocation->searchAddressBookLocations($params);

assert(isset($abcResult['results']) && isset($abcResult['total']), "Can't search for the locations");

Route4Me::simplePrint($abcResult, true);
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Search for Specified Text, Show Specified Fields
        /// </summary>
        public void GetSpecifiedFieldsSearchText()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AddressBookParameters addressBookParameters = new AddressBookParameters
            {
                Query = "david",
                Fields = "first_name,address_email",
                Offset = 0,
                Limit = 20
            };

            // Run the query
            uint total = 0;
            string errorString = "";
            List<string[]> contacts = route4Me.SearchAddressBookLocation(addressBookParameters, out total, out errorString);

            Console.WriteLine("");

            if (contacts != null)
            {
                Console.WriteLine("GetSpecifiedFieldsSearchText executed successfully, {0} contacts returned, total = {1}", contacts.Count, total);

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("GetSpecifiedFieldsSearchText error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub GetSpecifiedFieldsSearchText()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim addressBookParameters As New AddressBookParameters() With { _
                .Query = "david", _
                .Fields = "first_name,address_email", _
                .Offset = 0, _
                .Limit = 20 _
            }

            ' Run the query
            Dim total As UInteger
            Dim errorString As String = ""
            Dim contacts As List(Of String()) = route4Me.SearchAddressBookLocation(addressBookParameters, total, errorString)

            Console.WriteLine("")

            If contacts IsNot Nothing Then
                Console.WriteLine("GetSpecifiedFieldsSearchText executed successfully, {0} contacts returned, total = {1}", contacts.Count, total)

                Console.WriteLine("")
            Else
                Console.WriteLine("GetSpecifiedFieldsSearchText error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/addressbook"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &addressbook.Service{Client: client}
  
  query := &addressbook.Query{
        Query:  "technology",
        Offset: 0,
        Limit:  20,
    }
    locations, total, err := service.Get(query)
    if err != nil {
        // handle errors
        return
    }
    // do something with locations
}
unit LocationSearchUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TLocationSearch = class(TBaseExample)
  public
    procedure Execute(Query: String; Fields: TArray<String>);
  end;

implementation

uses AddressBookContactUnit, CommonTypesUnit;

procedure TLocationSearch.Execute(Query: String; Fields: TArray<String>);

var
  ErrorString: String;
  Total: integer;
  FindedResults: T2DimensionalStringArray;
  Limit, Offset: integer;
begin
  Limit := 10;
  Offset := 0;

  FindedResults := Route4MeManager.AddressBookContact.Find(
    Query, Fields, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (Length(FindedResults) > 0) then
    begin
      WriteLn(Format('LocationSearch executed successfully, ' +
        '%d contacts returned, total = %d', [Length(FindedResults), Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('LocationSearch error: "%s"', [ErrorString]));
  finally
    Finalize(FindedResults);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/address_book.php?api_key=...&query=...&offset=...&limit=...


See the sample JSON response of this method.


b) Display the locations included in the routes.


PARAMETERS

Parameter Type Description
api_key string API key of the user
display string If set to ‘routed’, get the locations included in the routes.
<job id="Addressbook Get Routed Locations">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address_book.php"
      apikey="11111111111111111111111111111111"
      
      ' Get routed locations. The `display` parameter can have any of these 3 possible values: [all, routed, unrouted].
      display="routed"
      
      url=url&"?api_key="&apikey
      url=url&"&display="&display
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
ECHO OFF
SET url=https://api.route4me.com/api.v4/address_book.php
SET apikey=11111111111111111111111111111111

:: Get routed locations. The `display` parameter can have any of these 3 possible values: [all, routed, unrouted].
SET display="routed"

ECHO ON

curl -o file1.txt -k -X GET "%url%?api_key=%apikey%&display=%display%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address_book.php
apikey=11111111111111111111111111111111

# Get routed locations. The `display` parameter can have any of these 3 possible values: [all, routed, unrouted].

display="routed"

curl -o file1.txt -k -X GET "$url?api_key=$apikey&display=$display"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
using System.Collections.Generic;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Search Routed Locations
        /// </summary>
        public void SearchRoutedLocations()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AddressBookParameters addressBookParameters = new AddressBookParameters
            {
                Display = "routed",
                Offset = 0,
                Limit = 20
            };

            // Run the query
            uint total = 0;
            string errorString = "";
            AddressBookContact[] contacts = route4Me.GetAddressBookLocation(addressBookParameters, out total, out errorString);

            Console.WriteLine("");

            if (contacts != null)
            {
                Console.WriteLine("SearchRoutedLocations executed successfully, {0} contacts returned, total = {1}", contacts.Length, total);

                Console.WriteLine("");
            }
            else
            {
                Console.WriteLine("SearchRoutedLocations error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub SearchRoutedLocations()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim addressBookParameters As New AddressBookParameters() With { _
                .Display = "routed", _
                .Offset = 0, _
                .Limit = 20 _
            }

            ' Run the query
            Dim total As UInteger
            Dim errorString As String = ""
            Dim contacts As AddressBookContact() = route4Me.GetAddressBookLocation(addressBookParameters, total, errorString)

            Console.WriteLine("")

            If contacts IsNot Nothing Then
                Console.WriteLine("SearchRoutedLocations executed successfully, {0} contacts returned, total = {1}", contacts.Length, total)

                Console.WriteLine("")
            Else
                Console.WriteLine("SearchRoutedLocations error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.

import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/addressbook"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &addressbook.Service{Client: client}
    query := &addressbook.Query{
        Limit:  10, // How many contacts to return
        Offset: 0,  // The offset (how many records to skip) of contacts.
        Display: "routed", // include locations in routes
    }
    contacts, total, err := service.Get(query)
    if err != nil {
        //handle errors
        return
    }
    // do something with contacts, it's []Contact
    // variable `total` represents the total number of contacts in your addressbook
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$ablocation = new AddressBookLocation();

// The example refers to the process of searching the routed locations.

$params = array(
    'offset'  => 0,
    'limit'   => 5,
    'display' => 'routed'
);

$abcResult = $ablocation->searchAddressBookLocations($params);

assert(isset($abcResult['results']) && isset($abcResult['total']), "Can't search for the locations");

echo "Found ".$abcResult['total']." routed locations";
unit DisplayRoutedUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TDisplayRouted = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses AddressBookContactUnit, EnumsUnit;

procedure TDisplayRouted.Execute;

var
  ErrorString: String;
  Total: integer;
  Contacts: TAddressBookContactList;
  Limit, Offset: integer;
begin
  Limit := 10;
  Offset := 0;

  Contacts := Route4MeManager.AddressBookContact.Find(
    TDisplayLocations.dlRouted, Limit, Offset, Total, ErrorString);
  try
    WriteLn('');

    if (Contacts.Count > 0) then
    begin
      WriteLn(Format('DisplayRouted executed successfully, ' +
        '%d contacts returned, total = %d', [Contacts.Count, Total]));
      WriteLn('');
    end
    else
      WriteLn(Format('DisplayRouted error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Contacts);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/address_book.php?api_key=...&display=...


See the sample JSON response of this method.


Update a Location

Updates an existing address book location.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data POST data A valid JSON object string. See the Address Book JSON Schema as a guide.
<job id="Addressbook Update Location">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/address_book.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="address_data_for_update.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    public void UpdateAddressBookContact(AddressBookContact contact)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      // Run the query
      string errorString;
      AddressBookContact updatedContact = route4Me.UpdateAddressBookContact(contact, out errorString);

      Console.WriteLine("");

      if (updatedContact != null)
      {
        Console.WriteLine("UpdateAddressBookContact executed successfully");
      }
      else
      {
        Console.WriteLine("UpdateAddressBookContact error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Sub UpdateAddressBookContact(contact As AddressBookContact)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            ' Run the query
            Dim errorString As String = ""
            Dim updatedContact As AddressBookContact = route4Me.UpdateAddressBookContact(contact, errorString)

            Console.WriteLine("")

            If updatedContact IsNot Nothing Then
                Console.WriteLine("UpdateAddressBookContact executed successfully")
            Else
                Console.WriteLine("UpdateAddressBookContact error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
#!/usr/bin/python

from route4me import Route4Me
from route4me.constants import *

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    address_book = route4me.address_book
    response = address_book.get_addressbook_contacts(limit=10, Offset=5)
    if 'errors' in response.keys():
        print '. '.join(response['errors'])
    else:
        address_id = "'{}'".format(response['results'][0]['address_id'])
        response = address_book.get_addressbook_contact(address_id=address_id)
        if 'errors' in response.keys():
            print '. '.join(response['errors'])
        else:
            contact = response['results'][0]
            contact['first_name'] = '{} Updated'.format(contact['first_name'])
            response = address_book.update_contact(**contact)
            if 'errors' in response.keys():
                print '. '.join(response['errors'])
            else:
                print 'Address ID: {0}'.format(response['address_id'])
                print 'First Name: {0}'.format(response['first_name'])
                print 'Last Name: {0}'.format(response['last_name'])
                print 'Address: {0}'.format(response['address_1'])

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.addressbook;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.addressbook.AddressBookManager;
import com.route4me.sdk.services.addressbook.Contact;
import com.route4me.sdk.services.addressbook.ContactsRequest;

import java.util.List;

public class UpdateAddressBookContact {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        AddressBookManager addressBookManager = new AddressBookManager(apiKey);
        try {
            List<Contact> contacts = addressBookManager.getContacts(new ContactsRequest().setLimit(10));
            contacts.get(0).setFirstName("Johny");
            Contact contact = addressBookManager.updateContact(contacts.get(0));
            System.out.println(contact);
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$AdressBookLocationParameters = AddressBookLocation::fromArray(array(
    "first_name"  => "Test FirstName ".strval(rand(10000, 99999)),
    "address_1"   => "Test Address1 ".strval(rand(10000, 99999)),
    "cached_lat"  => 38.024654,
    "cached_lng"  => -77.338814
));

$abLocation = new AddressBookLocation();

$abcResult = $abLocation->addAdressBookLocation($AdressBookLocationParameters);

$address_id = -1;

assert(isset($abcResult['address_id']), "Can't create an address book location<br><br>");

if (isset($abcResult["address_id"])) {
    $address_id = $abcResult["address_id"];
}

assert($address_id!=-1, "Can't create an address book location<br><br>");

echo "Address Book Location with <b>address_id = ".strval($address_id)."</b> and <b>first_name = ".$abcResult['first_name']."</b> was successfully added.<br>";
 
$abcResult["first_name"] = "Test Firstname Updated";

$abcResult = $abLocation->updateAdressBookLocation(AddressBookLocation::fromArray($abcResult));

assert(isset($abcResult['first_name']), "Can't update the address book location<br><br>");

assert($abcResult['first_name']=='Test Firstname Updated', "Can't update the address book location<br><br>");

echo "The field <b>first_name</b> in the address book location <b>".$address_id."</b> was successfully updated to <b>Test Firstname Updated</b>.<br>"; 
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/addressbook"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &addressbook.Service{Client: client}
  
  contact, err := service.Update(&contact)
  if err != nil {
    // handle errors
    return
  }
}
package UpdateAddressBookContact;
use strict;
use warnings FATAL => 'all';

sub UpdateAddressBookContact {
    my ($self, $contact) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $errorString;
    my $updatedContact = $route4Me->updateAddressBookContact($contact, $errorString);

    print "\n";

    if ($updatedContact)
    {
        print "UpdateAddressBookContact executed successfully\n";
    }
    else
    {
        printf "UpdateAddressBookContact error: %s\n", $errorString;
    }
}
1;
@ECHO OFF
SET url=https://api.route4me.com/api.v4/address_book.php
SET apikey=11111111111111111111111111111111

ECHO ON

curl -o file1.txt -k -g -X PUT -H "Content-Type: application/json" -d "@address_data_for_update.json" "%url%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/address_book.php
apikey=11111111111111111111111111111111


curl -o file1.txt -k -g -X PUT -H "Content-Type: application/json" -d "@address_data_for_update.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
unit UpdateLocationUnit;

interface

uses SysUtils, BaseExampleUnit, AddressBookContactUnit;

type
  TUpdateLocation = class(TBaseExample)
  public
    procedure Execute(Contact: TAddressBookContact);
  end;

implementation

procedure TUpdateLocation.Execute(Contact: TAddressBookContact);

var
  ErrorString: String;
  UpdatedContact: TAddressBookContact;
begin
  UpdatedContact := Route4MeManager.AddressBookContact.Update(Contact, ErrorString);
  try
    WriteLn('');

    if (UpdatedContact <> nil) then
      WriteLn('UpdateLocation executed successfully')
    else
      WriteLn(Format('UpdateLocation error: "%s"', [ErrorString]));
  finally
    FreeAndNil(UpdatedContact);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/address_book.php?api_key=...

You can expect this API response:

{
  "created_timestamp": 1462362515,
  "address_id": 6879135,
  "address_group": "",
  "address_alias": "301 MARKET SHELL",
  "address_1": "17205 RICHMOND TNPK, MILFORD, VA, 22514",
  "address_2": "",
  "member_id": 1,
  "first_name": "Modified",
  "last_name": "Gorason",
  "address_email": "[email protected]",
  "address_phone_number": "8046335852",
  "address_city": "Tbilisi",
  "address_state_id": "0",
  "address_country_id": "0",
  "address_zip": "00167",
  "cached_lat": 38.024654,
  "cached_lng": -77.338814,
  "curbside_lat": 38.024654,
  "curbside_lng": -77.338814,
  "address_custom_data": [],
  "in_route_count": 0,
  "last_visited_timestamp": 0,
  "last_routed_timestamp": 0,
  "local_time_window_start": null,
  "local_time_window_end": null,
  "local_time_window_start_2": null,
  "local_time_window_end_2": null,
  "service_time": 0,
  "local_timezone_string": "",
  "color": "",
  "address_icon": null,
  "address_stop_type": "DELIVERY",
  "address_cube": null,
  "address_pieces": null,
  "address_reference_no": null,
  "address_revenue": null,
  "address_weight": null,
  "address_priority": null,
  "address_customer_po": null
}

Address Book Group

An address book group refers to the searching and grouping process of the address book contacts.

See the Address Book Group JSON Schema in our GitHub repository.

Address Book Properties

Attribute Type Description
api_key string API key of the user
group_id string Unique address book group ID
group_name string Address book group name
group_color string Address book group name color
group_icon string Address book group icon
member_id integer The member ID of the address book contacts repository
filter JSON object The JSON object for filtering of the address book contacts

Create a Group

Adds an address book group to the user account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data payload data A valid JSON object string. See the Address Book Group JSON Schema as a guide.
<job id="Create Address Book Group">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/address_book_group.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="create_addressbook_group_data.json"
			
			Set r4m=New Route4Me
			
			r4m.OutputFile = "create_addressbook_group_RESPONSE.json"
			
			r4m.HttpPostRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
ECHO OFF

SET url=https://api.route4me.com/api.v4/address_book_group.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of creating address book group.

ECHO ON

curl -o create_addressbook_group_RESPONSE.json -k -d "@create_addressbook_group_data.json" -X POST -H "Content-Type: application/json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

 # The example refers to the process of creating address book group.

url=https://api.route4me.com/api.v4/address_book_group.php
apikey=11111111111111111111111111111111

curl -o create_addressbook_group_RESPONSE.json -g -k -X POST -H "Content-Type: application/json" -d "@create_addressbook_group_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 30
private static AddressBookGroup CreateAddreessBookGroup(out string errorString)
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	AddressBookGroupRule addressBookGroupRule = new AddressBookGroupRule()
	{
		ID = "address_1",
		Field = "address_1",
		Operator = "not_equal",
		Value = "qwerty123456"
	};

	AddressBookGroupFilter addressBookGroupFilter = new AddressBookGroupFilter()
	{
		Condition = "AND",
		Rules = new AddressBookGroupRule[] { addressBookGroupRule }
	};

	AddressBookGroup addressBookGroupParameters = new AddressBookGroup()
	{
		groupName = "All Group",
		groupColor = "92e1c0",
		Filter = addressBookGroupFilter
	};

	// Run the query
	//string errorString;
	AddressBookGroup addressBookGroup = route4Me.AddAddressBookGroup(addressBookGroupParameters, out errorString);

	return addressBookGroup;
}
Private Shared Function CreateAddreessBookGroup(ByRef errorString As String) As AddressBookGroup
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)

	Dim addressBookGroupRule As AddressBookGroupRule = New AddressBookGroupRule() With {
		.ID = "address_1",
		.Field = "address_1",
		.[Operator] = "not_equal",
		.Value = "qwerty123456"
	}

	Dim addressBookGroupFilter As AddressBookGroupFilter = New AddressBookGroupFilter() With {
		.Condition = "AND",
		.Rules = New AddressBookGroupRule() {addressBookGroupRule}
	}

	Dim addressBookGroupParameters As AddressBookGroup = New AddressBookGroup() With {
		.groupName = "All Group",
		.groupColor = "92e1c0",
		.Filter = addressBookGroupFilter
	}

	Dim addressBookGroup As AddressBookGroup = route4Me.AddAddressBookGroup(addressBookGroupParameters, errorString)

	Return addressBookGroup
End Function
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$abGroup = new AddressBookGroup();

// The example refers to the process of creating address book group.
// Note: you can find the allowed colors for the address book group at this link:
// https://github.com/route4me/route4me-json-schemas/blob/master/ColorSamples/AddressBookGroupAvailableColors.png

$createParameters= [
    'group_name'   => 'Louisville Group Temp',
    'group_color'  => '92e1c0',
    'filter' => [
        'condition' => 'AND',
        'rules' => [[
            'id'       => 'address_1',
            'field'    => 'address_1',
            'operator' => 'contains',
            'value'    => 'Luisville'
        ]]
    ]
];

$createdAddressBookGroup = $abGroup->createAddressBookGroup($createParameters);

Route4Me::simplePrint($createdAddressBookGroup);
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.


HTTP Request

POST
/api.v4/address_book_group.php?api_key=...

You can expect this API response:

{
	"member_id": 1,
	"group_name": "All Group",
	"group_color": "92e1c0",
	"group_icon": null,
	"filter": {
		"condition": "AND",
		"rules": [
			{
				"id": "address_1",
				"field": "address_1",
				"operator": "not_equal",
				"value": "qwerty123456"
			}
		]
	},
	"group_id": "8A2401FE169B31E2136B4F7AECA3FB51"
}

Update a Group

Updates an address book group belonged to the user account.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data payload data A valid JSON object string. See the Address Book Group JSON Schema as a guide.
<job id="Update Address Book Group">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/address_book_group.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="update_addressbook_group_data.json"
			
			Set r4m=New Route4Me
			
			r4m.OutputFile = "update_addressbook_group_RESPONSE.json"
			
			r4m.HttpPutRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
ECHO OFF

SET url=https://api.route4me.com/api.v4/address_book_group.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of updating an address book group.
:: Note: you can find the allowed colors for the address book group at this link:
:: https://github.com/route4me/route4me-json-schemas/blob/master/ColorSamples/AddressBookGroupAvailableColors.png 

ECHO ON

curl -o update_addressbook_group_RESPONSE.json -k -d "@update_addressbook_group_data.json" -X PUT -H "Content-Type: application/json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

 # The example refers to the process of updating an address book group.
 # Note: you can find the allowed colors for the address book group at this link:
 # https://github.com/route4me/route4me-json-schemas/blob/master/ColorSamples/AddressBookGroupAvailableColors.png 

url=https://api.route4me.com/api.v4/address_book_group.php
apikey=11111111111111111111111111111111

curl -o update_addressbook_group_RESPONSE.json -g -k -X PUT -H "Content-Type: application/json" -d "@update_addressbook_group_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 30
public void UpdateAddressBookGroupTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	AddressBookGroupRule addressBookGroupRule = new AddressBookGroupRule()
	{
		ID = "address_1",
		Field = "address_1",
		Operator = "not_equal",
		Value = "qwerty1234567"
	};

	AddressBookGroupFilter addressBookGroupFilter = new AddressBookGroupFilter()
	{
		Condition = "AND",
		Rules = new AddressBookGroupRule[] { addressBookGroupRule }
	};

	AddressBookGroup addressBookGroupParameters = new AddressBookGroup()
	{
		groupID = group2.groupID,
		groupColor = "cd74e6",
		Filter = addressBookGroupFilter
	};

	// Run the query
	string errorString;
	AddressBookGroup addressBookGroup = route4Me.UpdateAddressBookGroup(addressBookGroupParameters, out errorString);

	Assert.IsNotNull(addressBookGroup, "UpdateAddressBookGroupTest failed... " + errorString);
}
Public Sub UpdateAddressBookGroupTest()
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)

	Dim addressBookGroupRule As AddressBookGroupRule = New AddressBookGroupRule() With {
		.ID = "address_1",
		.Field = "address_1",
		.[Operator] = "not_equal",
		.Value = "qwerty1234567"
	}

	Dim addressBookGroupFilter As AddressBookGroupFilter = New AddressBookGroupFilter() With {
		.Condition = "AND",
		.Rules = New AddressBookGroupRule() {addressBookGroupRule}
	}

	Dim addressBookGroupParameters As AddressBookGroup = New AddressBookGroup() With {
		.groupID = group2.groupID,
		.groupColor = "cd74e6",
		.Filter = addressBookGroupFilter
	}

	Dim errorString As String
	Dim addressBookGroup As AddressBookGroup = route4Me.UpdateAddressBookGroup(addressBookGroupParameters, errorString)

	Assert.IsNotNull(addressBookGroup, "UpdateAddressBookGroupTest failed... " & errorString)
End Sub
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$abGroup = new AddressBookGroup();

// The example refers to the process of updating an address book group.
// Note: you can find the allowed colors for the address book group at this link:
// https://github.com/route4me/route4me-json-schemas/blob/master/ColorSamples/AddressBookGroupAvailableColors.png

$groupId=$abGroup->getAddressBookGroupIdByName('Louisville Group Temp');

if ($groupId==null) {
    include('CreateAddressBookGroup.php');
    $groupId=$abGroup->getAddressBookGroupIdByName('Louisville Group Temp');
}

$updateParameters= [
    'group_id' => $groupId,
    'group_color'  => '7bd148'
];

$results = $abGroup->updateAddressBookGroup($updateParameters);

Route4Me::simplePrint($results);
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.


HTTP Request

PUT
/api.v4/address_book_group.php?api_key=...

You can expect this API response:

{
	"group_id": "492D586CCCAF4C89EACC9C8A4C517ACA",
	"group_name": "All Group",
	"group_color": "cd74e6",
	"group_icon": "",
	"member_id": 1,
	"filter": {
		"condition": "AND",
		"rules": [
			{
				"id": "address_1",
				"field": "address_1",
				"operator": "not_equal",
				"value": "qwerty1234567"
			}
		]
	}
}

Get Groups

Retrieves the address book groups.


PARAMETERS

Parameter Type Description
api_key string API key of the user
offset integer Search starting position
limit integer The number of records to return.
<job id="Get Address Book Groups">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/address_book_group.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			offset="0"
			limit="10"
			url=url&"&offset="&offset
			url=url&"&limit="&limit
			
			Set r4m=New Route4Me
			
			r4m.OutputFile = "get_addressbook_groups_RESPONSE.json"
			
			r4m.HttpGetRequest(url)
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
ECHO OFF

SET url=https://api.route4me.com/api.v4/address_book_group.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of getting limited number of the address book groups.

ECHO ON

curl -o get_addressbook_groups_RESPONSE.json -k -X GET "%url%?api_key=%apikey%&offset=0&limit=10"

timeout /t 30
 #!/bin/bash

 # The example refers to the process of getting limited number of the address book groups.

url=https://api.route4me.com/api.v4/address_book_group.php
apikey=11111111111111111111111111111111
offset=0
limit=10

curl -o get_addressbook_groups_RESPONSE.json -g -k -XGET "$url?api_key=$apikey&offset=$offset&limit=$limit"

echo "Finished..."

sleep 30
public void GetAddressBookGroupsTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	AddressBookGroupParameters addressBookGroupParameters = new AddressBookGroupParameters()
	{
		Limit = 10,
		Offset = 0
	};

	// Run the query
	string errorString;
	AddressBookGroup[] groups = route4Me.GetAddressBookGroups(addressBookGroupParameters, out errorString);

	Assert.IsInstanceOfType(groups, typeof(AddressBookGroup[]), "GetAddressBookGroupsTest failed... " + errorString);
}
Public Sub GetAddressBookGroupsTest()
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)
	
	Dim addressBookGroupParameters As AddressBookGroupParameters = New AddressBookGroupParameters() With {
		.Limit = 10,
		.Offset = 0
	}
	
	Dim errorString As String
	Dim groups As AddressBookGroup() = route4Me.GetAddressBookGroups(addressBookGroupParameters, errorString)
	
	Assert.IsInstanceOfType(groups, GetType(AddressBookGroup()), "GetAddressBookGroupsTest failed... " & errorString)
End Sub
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$abGroup = new AddressBookGroup();

// The example refers to the process of getting limited number of the address book groups.
$addressBookGroupParameters = [
    'limit' => 20,
    'offset' => 0,
];

$addressBookGroups = $abGroup->getAddressBookGroups($addressBookGroupParameters);

Route4Me::simplePrint($addressBookGroups);
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.
Example Coming Soon in this Language. Please see another language for reference.


HTTP Request

GET
/api.v4/address_book_group.php?api_key=...&offset=...&limit=...

You can expect this API response:

[
	{
		"group_id": "8A2401FE169B31E2136B4F7AECA3FB51",
		"group_name": "All Group",
		"group_color": "92e1c0",
		"group_icon": null,
		"member_id": 1,
		"filter": {
			"condition": "AND",
			"rules": [
				{
					"id": "address_1",
					"field": "address_1",
					"operator": "not_equal",
					"value": "qwerty123456"
				}
			]
		}
	},
	{
		"group_id": "54AC71733C0DE0A1B67EE1B39BDE1142",
		"group_name": "All Group",
		"group_color": "92e1c0",
		"group_icon": null,
		"member_id": 1,
		"filter": {
			"condition": "AND",
			"rules": [
				{
					"id": "address_1",
					"field": "address_1",
					"operator": "not_equal",
					"value": "qwerty123456"
				}
			]
		}
	},
	{
		"group_id": "D42FEF1C1B824EC040D1E2874FE3897F",
		"group_name": "All Group",
		"group_color": "92e1c0",
		"group_icon": null,
		"member_id": 1,
		"filter": {
			"condition": "AND",
			"rules": [
				{
					"id": "address_1",
					"field": "address_1",
					"operator": "not_equal",
					"value": "qwerty123456"
				}
			]
		}
	},
	{
		"group_id": "22813F499204474E8E66380CBD8A78F8",
		"group_name": "FL",
		"group_color": "92e1c0",
		"group_icon": null,
		"member_id": 1,
		"filter": {
			"condition": "AND",
			"rules": [
				{
					"id": "address_1",
					"field": "address_1",
					"type": "string",
					"input": "text",
					"operator": "has_word",
					"value": "FL"
				}
			]
		}
	},
	{
		"group_id": "6CDC2A86D2073FB6F9FBD3884B9ACB92",
		"group_name": "ca",
		"group_color": "9fe1e7",
		"group_icon": null,
		"member_id": 1,
		"filter": {
			"condition": "AND",
			"rules": [
				{
					"id": "address_1",
					"field": "address_1",
					"type": "string",
					"input": "text",
					"operator": "has_word",
					"value": "CA"
				}
			]
		}
	}
]

Get a Group

Retrieves an address book group by group ID.


PARAMETERS

Parameter Type Description
api_key string API key of the user
group_id string Unique ID of the address book group
<job id="Get Address Book Group">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/address_book_group.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			group_id="54AC71733C0DE0A1B67EE1B39BDE1142"
			url=url&"&group_id="&group_id
			
			Set r4m=New Route4Me
			
			r4m.OutputFile = "get_addressbook_group_RESPONSE.json"
			
			r4m.HttpGetRequest(url)
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
ECHO OFF

SET url=https://api.route4me.com/api.v4/address_book_group.php
SET apikey=11111111111111111111111111111111
SET group_id=1322968F9B217C64785752B838849200

:: The example refers to the process of getting an adddress book group by group ID.

ECHO ON

curl -o get_addressbook_group_RESPONSE.json -k -X GET "%url%?api_key=%apikey%&group_id=%group_id%"

timeout /t 30
 #!/bin/bash

 # The example refers to the process of getting an adddress group by group ID.

url=https://api.route4me.com/api.v4/address_book_group.php
apikey=11111111111111111111111111111111
group_id="D42FEF1C1B824EC040D1E2874FE3897F"

curl -o get_addressbook_group_RESPONSE.json -g -k -XGET "$url?api_key=$apikey&group_id=$group_id"

echo "Finished..."

sleep 30
public void GetAddressBookGroupTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	AddressBookGroupParameters addressBookGroupParameters = new AddressBookGroupParameters()
	{
		GroupId = group2.groupID
	};

	// Run the query
	string errorString;
	AddressBookGroup addressBookGroup = route4Me.GetAddressBookGroup(addressBookGroupParameters, out errorString);

	Assert.IsInstanceOfType(addressBookGroup, typeof(AddressBookGroup), "GetAddressBookGroupTest failed... " + errorString);
}
Public Sub GetAddressBookGroupTest()
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)

	Dim addressBookGroupParameters As AddressBookGroupParameters = New AddressBookGroupParameters() With {
		.GroupId = group2.groupID
	}

	Dim errorString As String
	Dim addressBookGroup As AddressBookGroup = route4Me.GetAddressBookGroup(addressBookGroupParameters, errorString)

	Assert.IsInstanceOfType(addressBookGroup, GetType(AddressBookGroup), "GetAddressBookGroupTest failed... " & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$abGroup = new AddressBookGroup();

// The example refers to the process of getting an address book group by group ID.

// Get reandom address book group
$addressBookGroupParameters = [
    'limit' => 20,
    'offset' => 0,
];

$randomGroup = $abGroup->getRandomAddressBookGroup($addressBookGroupParameters);

if (assert(null != $randomGroup, 'Cannot get a random address book group'));

// Get the address book group by group_id
$groupId = $randomGroup['group_id'];

$abgResult = $abGroup->getAddressBookGroup(['group_id' => $groupId]);

Route4Me::simplePrint($abgResult);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
api.v4/address_book_group.php?api_key=...&group_id=...

You can expect this API response:

{
	"group_id": "35DC986E1AECDD71C9389641675024EE",
	"group_name": "All Group",
	"group_color": "92e1c0",
	"group_icon": null,
	"member_id": 1,
	"filter": {
		"condition": "AND",
		"rules": [
			{
				"field": "address_1",
				"id": "address_1",
				"operator": "not_equal",
				"value": "qwerty123456"
			}
		]
	}
}

Remove a Group

Removes an address book group from a user account.


PARAMETERS

Parameter Type Description
api_key string API key of the user
group_id string Unique ID of the address book group
<job id="Remove Address Book Group">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/address_book_group.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="remove_addressbook_group_data.json"
			
			Set r4m=New Route4Me
			
			r4m.OutputFile = "remove_addressbook_group_RESPONSE.json"
			
			r4m.HttpDeleteRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
ECHO OFF

SET url=https://api.route4me.com/api.v4/address_book_group.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of removing an address book group from a user's account.

ECHO ON

curl -o remove_addressbook_group_RESPONSE.json -k -d "@remove_addressbook_group_data.json" -X DELETE -H "Content-Type: application/json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

 # The example refers to the process of removing an address book group from a user's account.

url=https://api.route4me.com/api.v4/address_book_group.php
apikey=11111111111111111111111111111111

curl -o remove_addressbook_group_RESPONSE.json -g -k -X DELETE -H "Content-Type: application/json" -d "@remove_addressbook_group_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 30
private static StatusResponse DeleteAddreessBookGroup(string remeoveGroupID, out string errorString)
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	AddressBookGroupParameters addressGroupParams = new AddressBookGroupParameters()
	{
		groupID = remeoveGroupID
	};

	errorString = "";
	StatusResponse status = route4Me.RemoveAddressBookGroup(addressGroupParams, out errorString);
	
	return status;
}
Private Shared Function DeleteAddreessBookGroup(ByVal remeoveGroupID As String, ByRef errorString As String) As StatusResponse
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)

	Dim addressGroupParams As AddressBookGroupParameters = New AddressBookGroupParameters() With {
		.GroupId_ = remeoveGroupID ' Payload parameter is GroupId_, url query parameter: GroupId
	}

	errorString = ""
	Dim status As StatusResponse = route4Me.RemoveAddressBookGroup(addressGroupParams, errorString)

	Return status
End Function
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$abGroup = new AddressBookGroup();

// The example refers to the process of removing an address book group from a user's account.
$groupId=$abGroup->getAddressBookGroupIdByName('Louisville Group Temp');

if ($groupId==null) {
    include('CreateAddressBookGroup.php');
    $groupId=$abGroup->getAddressBookGroupIdByName('Louisville Group Temp');
}

$updateParameters= [
    'group_id' => $groupId
];

$result = $abGroup->removeAddressBookGroup($updateParameters);

Route4Me::simplePrint($result);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
api.v4/address_book_group.php?api_key=...&group_id=...

You can expect this API response:

{
	"status": true
}

Get Contacts by Group

Retrieves address book contacts by group by sending HTTP POST request.


PARAMETERS

Parameter Type Description
api_key string API key of the user
fields array Array of the field names
group_id string Unique ID of the address book group
<job id="Get Contacts By Group">
	<script language="VBScript" src="../../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			Dim jFile
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api/address_book/get_search_group_addresses.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="get_addressbook_by_group_data.json"
			
			Set r4m=New Route4Me
			
			r4m.OutputFile = "get_addressbook_by_group_RESPONSE.json"
			
			r4m.HttpPostRequest url,jFile
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
ECHO OFF

SET url=https://api.route4me.com/api/address_book/get_search_group_addresses.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of getting the address book locations by a geoup ID.

ECHO ON

curl -o get_addressbook_by_group_RESPONSE.json -k -XPOST -H "Content-Type: application/json" -d "@get_addressbook_by_group_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

 # The example refers to the process of searching for the locations by a group ID.

url=https://api.route4me.com/api/address_book/get_search_group_addresses.php
apikey=11111111111111111111111111111111

curl -o get_addressbook_by_group_RESPONSE.json -g -k -XPOST -H "Content-Type: application/json" -d "@get_addressbook_by_group_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 30
public void GetAddressBookContactsByGroupTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	AddressBookGroupParameters addressBookGroupParameters = new AddressBookGroupParameters()
	{
		groupID = group2.groupID
	};

	// Run the query
	string errorString;
	AddressBookContactsResponse addressBookGroup = route4Me.GetAddressBookContactsByGroup(addressBookGroupParameters, out errorString);

	Assert.IsInstanceOfType(addressBookGroup, typeof(AddressBookContactsResponse), "GetAddressBookContactsByGroupTest failed... " + errorString);
}
Public Sub GetAddressBookContactsByGroupTest()
	Dim route4Me As Route4MeManager = New Route4MeManager(c_ApiKey)

	Dim addressBookGroupParameters As AddressBookGroupParameters = New AddressBookGroupParameters() With {
		.GroupId_ = group2.groupID
	}

	Dim errorString As String
	Dim addressBookGroup As AddressBookContactsResponse = route4Me.GetAddressBookContactsByGroup(addressBookGroupParameters, errorString)

	Assert.IsInstanceOfType(addressBookGroup, GetType(AddressBookContactsResponse), "GetAddressBookContactsByGroupTest failed... " & errorString)
End Sub
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$abGroup = new AddressBookGroup();

// The example refers to the process of getting the address book locations by a group ID.
$groupId=$abGroup->getAddressBookGroupIdByName( 'Louisville Group Temp');

if ($groupId==null) {
    include('CreateAddressBookGroup.php');
    $groupId=$abGroup->getAddressBookGroupIdByName('Louisville Group Temp');
}

$searchParameters = [
    'fields' => ['address_id'],
    'group_id' => $groupId,
];

$addressBookContacts = $abGroup->getAddressBookContactsByGroup($searchParameters);

Route4Me::simplePrint($addressBookContacts, true);
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api.v4/order.php?api_key=...

You can expect this API response:

{"status":true}

Avoidance Zones

An avoidance zone refers to a geographic region or territory to avoid, defined by a user for an optimization problem.

See the Avoidance Zone JSON Schema in our GitHub repository.

Avoidance Zone Properties

Attribute Type Description
api_key string API key of the user
territory_id string Avoidance zone ID
member_id integer Member ID
territory_name string Avoidance zone name
territory_color string Avoidance zone color
territory object Territory property in Datatype

Create an Avoidance Zone

a) Create an Avoidance Zone object with a circular shape

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
input data POST data A valid JSON object string. See the Avoidance Zone JSON Schema as a guide.
<job id="Create Circle Avoidance Zone">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/avoidance.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="create_circle_zone_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Add Avoidance Zone
    /// </summary>
    /// <returns> ID of added territory </returns>
    public string AddAvoidanceZone()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      AvoidanceZoneParameters avoidanceZoneParameters = new AvoidanceZoneParameters()
      {
        TerritoryName = "Test Territory",
        TerritoryColor = "ff0000",
        Territory = new Territory()
        {
          Type = TerritoryType.Circle.Description(),
          Data = new string[] { "37.569752822786455,-77.47833251953125",
                                "5000"}
        }
      };

      // Run the query
      string errorString;
      AvoidanceZone avoidanceZone = route4Me.AddAvoidanceZone(avoidanceZoneParameters, out errorString);

      Console.WriteLine("");

      if (avoidanceZone != null)
      {
        Console.WriteLine("AddAvoidanceZone executed successfully");

        Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId);

        return avoidanceZone.TerritoryId;
      }
      else
      {
        Console.WriteLine("AddAvoidanceZone error: {0}", errorString);

        return null;
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Add Avoidance Zone
        ''' </summary>
        ''' <returns> ID of added territory </returns>
        Public Function AddAvoidanceZone() As String
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim avoidanceZoneParameters As New AvoidanceZoneParameters() With { _
                .TerritoryName = "Test Territory", _
                .TerritoryColor = "ff0000", _
                .Territory = New Territory() With { _
                    .Type = EnumHelper.GetEnumDescription(TerritoryType.Circle), _
                    .Data = New String() {"37.569752822786455,-77.47833251953125", "5000"} _
                } _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim avoidanceZone As AvoidanceZone = route4Me.AddAvoidanceZone(avoidanceZoneParameters, errorString)

            Console.WriteLine("")

            If avoidanceZone IsNot Nothing Then
                Console.WriteLine("AddAvoidanceZone executed successfully")

                Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId)

                Return avoidanceZone.TerritoryId
            Else
                Console.WriteLine("AddAvoidanceZone error: {0}", errorString)

                Return Nothing
            End If
        End Function
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    avoidance_zones = route4me.avoidance_zones
    print 'Creating Circle Shape Zone'
    territory = {"territory_name": "Circle Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "circle",
                               "data": ["37.569752822786455,-77.47833251953125",
                                        "5000",
                                        ]
                               }
                 }
    response = avoidance_zones.add_avoidance_zone(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Territory ID: {}'.format(response.territory_id)
        print '\tTerritory Name: {}'.format(response.territory_name)
        print '\tTerritory Color: {}'.format(response.territory_color)
        print '\tMember ID: {}'.format(response.member_id)
        print '\tTerritory Type: {}'.format(response.territory.type)
        if response.territory.data:
            print '\tData: '
            for data in response.territory.data:
                print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Example refers to the process of creating an avoidance zone with circle shape

$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::CIRCLE;
$territoryParams['data'] = array(
    "37.569752822786455,-77.47833251953125",
    "5000"
);

$AvoidanceZoneParameters = AvoidanceZone::fromArray(array(
    "territory_name"   => "Test Circle Avoidance Zone ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$avoidancezone = new AvoidanceZone();

$result = $avoidancezone->addAvoidanceZone($AvoidanceZoneParameters);

Route4Me::simplePrint($result, true);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
  
  zone := &territories.AvoidanceZone{
    Name:  "Some zone",
    Color: "beeeee", //hexadecimal color
    Territory: territories.TerritoryShape{
      Type: territories.Circle, //Type of an area
      Data: []string{"37.569752822786455,-77.47833251953125", "5000"},
    },
  }
  newZone, err := service.AddAvoidanceZone(zone)
  if err != nil {
    //handle errors
    return
  }
}
package AddAvoidanceZone;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::QueryTypes::AvoidanceZoneParameters;
use Route4MeSDK::DataTypes::Territory;
use Route4MeSDK::DataTypes::TerritoryType;
sub AddAvoidanceZone {
    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $avoidanceZoneParameters = AvoidanceZoneParameters->new(
        territory_name => "Test Territory",
        territory_color => "ff0000",
        territory => Territory->new(
            type => TerritoryType->Circle,
            data => ['37.569752822786455,-77.47833251953125', '5000']
        )
    );

    my $errorString = "";

    my $avoidanceZone = $route4Me->addAvoidanceZone($avoidanceZoneParameters, \$errorString);

    print "\n";

    if ($avoidanceZone) {
        print "AddAvoidanceZone executed successfully\n";

        printf "Territory ID: %s\n", $avoidanceZone->territory_id;

        return $avoidanceZone->territory_id;
    } else {
        printf "AddAvoidanceZone error: %s\n", $errorString;

        return undef;
    }
}
1;
@ECHO OFF
SET url=https://api.route4me.com/api.v4/avoidance.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: Example demonstrates creating an avoidance zone with circle shape by sending HTTP parameters

curl -o file1.txt -g -k -X POST -d "@create_circle_zone_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/avoidance.php
apikey=11111111111111111111111111111111

 # Example demonstrates creating an avoidance zone with circle shape by sending HTTP parameters
 
curl -o file1.txt -g -k -X POST -d "@create_circle_zone_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;
import com.route4me.sdk.services.territories.TerritoryData;
import com.route4me.sdk.services.routing.Constants;
import java.util.ArrayList;
import java.util.List;

public class AddAvoidanceZone {
    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        
        List<String> circleTerritoryDataList = new ArrayList<>();
        circleTerritoryDataList.add("37.569752822786455,-77.47833251953125");
        circleTerritoryDataList.add("5000");
        TerritoryData circleTerritoryData = new TerritoryData();
        circleTerritoryData.setData(circleTerritoryDataList);
        Territory circleTerritory = new Territory();
        circleTerritory.setTerritoryName("Circle Territory");
        circleTerritory.setTerritoryColor("ff0000");
        circleTerritory.setTerritory(circleTerritoryData);
        circleTerritoryData.setType(Constants.TerritoryType.CIRCLE.toString());
        responseObject = territoriesManager.addAvoidanceZone(circleTerritory);

        System.out.println("Circle Territory");
        System.out.println(responseObject.toString());
        System.out.println();
    }
}
unit AddCircleAvoidanceZoneUnit;

interface

uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit;

type
  TAddCircleAvoidanceZone = class(TBaseExample)
  public
    function Execute: NullableString;
  end;

implementation

uses TerritoryUnit, AvoidanceZoneUnit;

function TAddCircleAvoidanceZone.Execute: NullableString;

var
  ErrorString: String;
  AvoidanceZone: TAvoidanceZone;
  Territory: TCircleTerritory;
  NewAvoidanceZone: TAvoidanceZone;
  TerritoryName, TerritoryColor: String;
begin
  Result := NullableString.Null;

  TerritoryName := 'Circle Territory';
  TerritoryColor := 'ff0000';
  Territory := TCircleTerritory.Create(37.5697528227865, -77.4783325195313, 5000);
  AvoidanceZone := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
  try
    NewAvoidanceZone := Route4MeManager.AvoidanceZone.Add(AvoidanceZone, ErrorString);
    try
      WriteLn('');

      if (NewAvoidanceZone <> nil) then
      begin
        WriteLn('AddCircleAvoidanceZone executed successfully');
        WriteLn(Format('Territory ID: %s', [NewAvoidanceZone.TerritoryId.Value]));

        Result := NewAvoidanceZone.TerritoryId;
      end
      else
        WriteLn(Format('AddCircleAvoidanceZone error: "%s"', [ErrorString]));
    finally
      FreeAndNil(NewAvoidanceZone);
    end;
  finally
    FreeAndNil(AvoidanceZone);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/avoidance.php?api_key=...&territory_id=...

You can expect this API response:

{
  "territory_id": "70B125103B97F7170D17D344F713468E",
  "member_id": "1",
  "territory_name": "Test Territory",
  "territory_color": "ff0000",
  "territory": {
    "type": "circle",
    "data": [
      "37.569752822786455,-77.47833251953125",
      "5000"
    ]
  }
}

b) Create an Avoidance Zone object with a polygon shape

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Territory ID
input data POST data A valid JSON object string. See the Avoidance Zone JSON Schema as a guide.
<job id="Create Poly Avoidance Zone">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/avoidance.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="create_poly_zone_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/avoidance.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates creating an avoidance zone with a polygon shape by sending HTTP parameters

curl -o file1.txt -g -k -X POST -d "@create_poly_zone_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/avoidance.php
apikey=11111111111111111111111111111111

# The example demonstrates creating an avoidance zone with a polygon shape by sending HTTP parameters
 
curl -o file1.txt -g -k -X POST -d "@create_poly_zone_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Add Polygon Avoidance Zone
        /// </summary>
        /// <returns> ID of added territory </returns>
        public string AddPolygonAvoidanceZone()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AvoidanceZoneParameters avoidanceZoneParameters = new AvoidanceZoneParameters
            {
                TerritoryName = "Test Territory",
                TerritoryColor = "ff0000",
                Territory = new Territory
                {
                    Type = TerritoryType.Poly.Description(),
                    Data = new string[] {
                  "37.569752822786455,-77.47833251953125",
                  "37.75886716305343,-77.68974800109863",
                  "37.74763966054455,-77.6917221069336",
                  "37.74655084306813,-77.68863220214844",
                  "37.7502255383101,-77.68125076293945",
                  "37.74797991274437,-77.67498512268066",
                  "37.73327960206065,-77.6411678314209",
                  "37.74430510679532,-77.63172645568848",
                  "37.76641925847049,-77.66846199035645"
                }
                }
            };

            // Run the query
            string errorString;
            AvoidanceZone avoidanceZone = route4Me.AddAvoidanceZone(avoidanceZoneParameters, out errorString);

            Console.WriteLine("");

            if (avoidanceZone != null)
            {
                Console.WriteLine("AddPolygonAvoidanceZone executed successfully");

                Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId);

                return avoidanceZone.TerritoryId;
            }
            else
            {
                Console.WriteLine("AddPolygonAvoidanceZone error: {0}", errorString);

                return null;
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Add Polygon Avoidance Zone
        ''' </summary>
        ''' <returns> ID of added territory </returns>
        Public Function AddPolygonAvoidanceZone() As String
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim avoidanceZoneParameters As New AvoidanceZoneParameters() With { _
                .TerritoryName = "Test Territory", _
                .TerritoryColor = "ff0000", _
                .Territory = New Territory() With { _
                    .Type = EnumHelper.GetEnumDescription(TerritoryType.Poly), _
                    .Data = New String() { _
                        "37.569752822786455,-77.47833251953125", _
                        "37.75886716305343,-77.68974800109863", _
                        "37.74763966054455,-77.6917221069336", _
                        "37.74655084306813,-77.68863220214844", _
                        "37.7502255383101,-77.68125076293945", _
                        "37.74797991274437,-77.67498512268066", _
                        "37.73327960206065,-77.6411678314209", _
                        "37.74430510679532,-77.63172645568848", _
                        "37.76641925847049,-77.66846199035645"} _
                } _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim avoidanceZone As AvoidanceZone = route4Me.AddAvoidanceZone(avoidanceZoneParameters, errorString)

            Console.WriteLine("")

            If avoidanceZone IsNot Nothing Then
                Console.WriteLine("AddPolygonAvoidanceZone executed successfully")

                Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId)

                Return avoidanceZone.TerritoryId
            Else
                Console.WriteLine("AddPolygonAvoidanceZone error: {0}", errorString)

                Return Nothing
            End If
        End Function
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    avoidance_zones = route4me.avoidance_zones
    print 'Creating Polygon Shape Zone'
    territory = {"territory_name": "Polygon Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "poly",
                               "data": ["56.127184156131065,56.93115234375",
                                        "58.41322259056806,59.501953125",
                                        "61.53840616716746,59.315185546875",
                                        "61.047650586031104,51.998291015625",
                                        "59.254649544483726,53.63525390625",
                                        "56.47462805805596,54.42626953125"
                                        ]
                               }
                 }
    response = avoidance_zones.add_avoidance_zone(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Territory ID: {}'.format(response.territory_id)
        print '\tTerritory Name: {}'.format(response.territory_name)
        print '\tTerritory Color: {}'.format(response.territory_color)
        print '\tMember ID: {}'.format(response.member_id)
        print '\tTerritory Type: {}'.format(response.territory.type)
        if response.territory.data:
            print '\tData: '
            for data in response.territory.data:
                print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;
import com.route4me.sdk.services.territories.TerritoryData;
import com.route4me.sdk.services.routing.Constants;
import java.util.ArrayList;
import java.util.List;

public class AddAvoidanceZone {
    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        List<String> polyTerritoryDataList = new ArrayList<>();
        polyTerritoryDataList.add("56.127184156131065,56.93115234375");
        polyTerritoryDataList.add("58.41322259056806,59.501953125");
        polyTerritoryDataList.add("61.53840616716746,59.315185546875");
        polyTerritoryDataList.add("61.047650586031104,51.998291015625");
        polyTerritoryDataList.add("59.254649544483726,53.63525390625");
        polyTerritoryDataList.add("56.47462805805596,54.42626953125");
        TerritoryData polyTerritoryData = new TerritoryData();
        polyTerritoryData.setData(polyTerritoryDataList);
        Territory polyTerritory = new Territory();
        polyTerritory.setTerritoryName("Polygon Territory");
        polyTerritory.setTerritoryColor("ff0000");
        polyTerritory.setTerritory(polyTerritoryData);
        polyTerritoryData.setType(Constants.TerritoryType.POLY.toString());
        Territory responseObject = territoriesManager.addAvoidanceZone(polyTerritory);

        System.out.println("Polygon Territory");
        System.out.println(responseObject.toString());
        System.out.println();
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
  
  zone := &territories.AvoidanceZone{
    Name:  "Some zone",
    Color: "beeeee", //hexadecimal color
    Territory: territories.TerritoryShape{
      Type: territories.Polygonal, //Type of an area
      Data: []string{"37.769752822786455,-77.67833251953125",
        "37.75886716305343,-77.68974800109863",
        "37.74763966054455,-77.6917221069336",
        "37.74655084306813,-77.68863220214844",
        "37.7502255383101,-77.68125076293945",
        "37.74797991274437,-77.67498512268066",
        "37.73327960206065,-77.6411678314209",
        "37.74430510679532,-77.63172645568848",
        "37.76641925847049,-77.66846199035645"},
    },
  }
  newZone, err := service.AddAvoidanceZone(zone)
  if err != nil {
    //handle errors
    return
  }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example refers to the process of creating an avoidance zone with a polygon shape

$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::POLY;
$territoryParams['data'] = array(
    "37.769752822786455,-77.67833251953125",
    "37.75886716305343,-77.68974800109863",
    "37.74763966054455,-77.6917221069336",
    "37.74655084306813,-77.68863220214844",
    "37.7502255383101,-77.68125076293945",
    "37.74797991274437,-77.67498512268066",
    "37.73327960206065,-77.6411678314209",
    "37.74430510679532,-77.63172645568848",
    "37.76641925847049,-77.66846199035645"
);

$AvoidanceZoneParameters = AvoidanceZone::fromArray(array(
    "territory_name"   => "Test Poligonian Avoidance Zone ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$avoidancezone = new AvoidanceZone();

$result = $avoidancezone->addAvoidanceZone($AvoidanceZoneParameters);

Route4Me::simplePrint($result, true);
unit AddPolygonAvoidanceZoneUnit;

interface

uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit;

type
  TAddPolygonAvoidanceZone = class(TBaseExample)
  public
    function Execute: NullableString;
  end;

implementation

uses TerritoryUnit, AvoidanceZoneUnit;

function TAddPolygonAvoidanceZone.Execute: NullableString;

var
  ErrorString: String;
  AvoidanceZone: TAvoidanceZone;
  Territory: TPolygonTerritory;
  NewAvoidanceZone: TAvoidanceZone;
  TerritoryName, TerritoryColor: String;
begin
  Result := NullableString.Null;

  TerritoryName := 'Polygon Territory';
  TerritoryColor := 'ff0000';
  Territory := TPolygonTerritory.Create();
  Territory.AddPoint(37.7697528227865, -77.6783325195313);
  Territory.AddPoint(37.7588671630534, -77.6897480010986);
  Territory.AddPoint(37.7476396605445, -77.6917221069336);
  Territory.AddPoint(37.7465508430681, -77.6886322021484);
  Territory.AddPoint(37.7502255383101, -77.6812507629394);
  Territory.AddPoint(37.7479799127443, -77.6749851226806);
  Territory.AddPoint(37.7332796020606, -77.6411678314209);
  Territory.AddPoint(37.7443051067953, -77.6317264556884);
  Territory.AddPoint(37.7664192584704, -77.6684619903564);

  AvoidanceZone := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
  try
    NewAvoidanceZone := Route4MeManager.AvoidanceZone.Add(AvoidanceZone, ErrorString);
    try
      WriteLn('');

      if (NewAvoidanceZone <> nil) then
      begin
        WriteLn('AddPolygonAvoidanceZone executed successfully');
        WriteLn(Format('Territory ID: %s', [NewAvoidanceZone.TerritoryId.Value]));

        Result := NewAvoidanceZone.TerritoryId;
      end
      else
        WriteLn(Format('AddPolygonAvoidanceZone error: "%s"', [ErrorString]));
    finally
      FreeAndNil(NewAvoidanceZone);
    end;
  finally
    FreeAndNil(AvoidanceZone);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);
    ifstream inf("poly.json");
    if(!inf.is_open()) {
        cout << "Can't find a file with an avoidance zone" << endl;
        return -1;
    }
    Json::Value poly_data;
    inf >> poly_data;
    if (route.add_avoidance_zone("ABC", poly_data) == 0) {
        cout << "Added poly:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "Failed adding poly: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);

    char data_file[] = "poly.json";
    char id[] = "A1";
    char* data = NULL;

    if (deserialize(data_file, &data) == -1)
    {
        printf("Missing poly.json\n");
        return -1;
    }

    if (!get_multiple_routes(data_file, data))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

POST
/api.v4/avoidance.php?api_key=...&territory_id=...

You can expect this API response:

{
  "territory_id": "F1B1865C7F713893CCF87A34D6604617",
  "member_id": "1",
  "territory_name": "Polygon Territory",
  "territory_color": "ff0000",
  "territory": {
    "type": "poly",
    "data": [
      "37.769752822786455,-77.67833251953125",
      "37.75886716305343,-77.68974800109863",
      "37.74763966054455,-77.6917221069336",
      "37.74655084306813,-77.68863220214844",
      "37.7502255383101,-77.68125076293945",
      "37.74797991274437,-77.67498512268066",
      "37.73327960206065,-77.6411678314209",
      "37.74430510679532,-77.63172645568848",
      "37.76641925847049,-77.66846199035645"
    ]
  }
}

c) Create an Avoidance Zone object with a rectangular shape

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Territory ID
input data POST data A valid JSON object string. See the Avoidance Zone JSON Schema as a guide.
<job id="Create Rectangle Avoidance Zone">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      url="https://api.route4me.com/api.v4/avoidance.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      jFile="create_rect_zone_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPostRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/avoidance.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates creating an avoidance zone with a rectangle shape by sending HTTP parameters

curl -o file1.txt -g -k -X POST -d "@create_rect_zone_data.json" "%url%?api_key=%apikey%%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/avoidance.php
apikey=11111111111111111111111111111111

# The example demonstrates creating an avoidance zone with a rectangle shape by sending HTTP parameters

curl -o file1.txt -g -k -X POST -d "@create_rect_zone_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Add Rectangular Avoidance Zone
        /// </summary>
        /// <returns> ID of added territory </returns>
        public string AddRectAvoidanceZone()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AvoidanceZoneParameters avoidanceZoneParameters = new AvoidanceZoneParameters
            {
                TerritoryName = "Test Territory",
                TerritoryColor = "ff0000",
                Territory = new Territory
                {
                    Type = TerritoryType.Rect.Description(),
                    Data = new string[] {
                  "43.51668853502909,-109.3798828125",
                  "46.98025235521883,-101.865234375"
                }
                }
            };

            // Run the query
            string errorString;
            AvoidanceZone avoidanceZone = route4Me.AddAvoidanceZone(avoidanceZoneParameters, out errorString);

            Console.WriteLine("");

            if (avoidanceZone != null)
            {
                Console.WriteLine("AddRectAvoidanceZone executed successfully");

                Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId);

                return avoidanceZone.TerritoryId;
            }
            else
            {
                Console.WriteLine("AddRectAvoidanceZone error: {0}", errorString);

                return null;
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Add Rectangular Avoidance Zone
        ''' </summary>
        ''' <returns> ID of added territory </returns>
        Public Function AddRectAvoidanceZone() As String
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim avoidanceZoneParameters As New AvoidanceZoneParameters() With { _
                .TerritoryName = "Test Territory", _
                .TerritoryColor = "ff0000", _
                .Territory = New Territory() With { _
                    .Type = EnumHelper.GetEnumDescription(TerritoryType.Rect), _
                    .Data = New String() { _
                        "43.51668853502909,-109.3798828125", _
                        "46.98025235521883,-101.865234375"} _
                } _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim avoidanceZone As AvoidanceZone = route4Me.AddAvoidanceZone(avoidanceZoneParameters, errorString)

            Console.WriteLine("")

            If avoidanceZone IsNot Nothing Then
                Console.WriteLine("AddRectAvoidanceZone executed successfully")

                Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId)

                Return avoidanceZone.TerritoryId
            Else
                Console.WriteLine("AddRectAvoidanceZone error: {0}", errorString)

                Return Nothing
            End If
        End Function
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    avoidance_zones = route4me.avoidance_zones
    print 'Creating Rectangular Shape Zone'
    territory = {"territory_name": "Rect Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "rect",
                               "data": ["43.51668853502909,-109.3798828125",
                                        "46.98025235521883,-101.865234375"
                                        ]
                               }
                 }
    response = avoidance_zones.add_avoidance_zone(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Territory ID: {}'.format(response.territory_id)
        print '\tTerritory Name: {}'.format(response.territory_name)
        print '\tTerritory Color: {}'.format(response.territory_color)
        print '\tMember ID: {}'.format(response.member_id)
        print '\tTerritory Type: {}'.format(response.territory.type)
        if response.territory.data:
            print '\tData: '
            for data in response.territory.data:
                print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;
import com.route4me.sdk.services.territories.TerritoryData;
import com.route4me.sdk.services.routing.Constants;
import java.util.ArrayList;
import java.util.List;

public class AddAvoidanceZone {
    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        
        List<String> rectTerritoryDataList = new ArrayList<>();
        rectTerritoryDataList.add("43.51668853502909,-109.3798828125");
        rectTerritoryDataList.add("46.98025235521883,-101.865234375");
        TerritoryData rectTerritoryData = new TerritoryData();
        rectTerritoryData.setData(rectTerritoryDataList);
        Territory rectTerritory = new Territory();
        rectTerritory.setTerritoryName("Rect Territory");
        rectTerritory.setTerritoryColor("ff0000");
        rectTerritory.setTerritory(rectTerritoryData);
        rectTerritoryData.setType(Constants.TerritoryType.RECT.toString());
        responseObject = territoriesManager.addAvoidanceZone(rectTerritory);

        System.out.println("Rect Territory");
        System.out.println(responseObject.toString());
        System.out.println();
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
  
  zone := &territories.AvoidanceZone{
    Name:  "Some zone",
    Color: "beeeee", //hexadecimal color
    Territory: territories.TerritoryShape{
      Type: territories.Rectangular, //Type of an area
      Data: []string{"43.51668853502909,-109.3798828125","46.98025235521883,-101.865234375"},
    },
  }
  newZone, err := service.AddAvoidanceZone(zone)
  if err != nil {
    //handle errors
    return
  }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example refers to the process of creating an avoidance zone with a rectangle shape

$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::RECT;
$territoryParams['data'] = array(
    "43.51668853502909,-109.3798828125",
    "46.98025235521883,-101.865234375"
);

$AvoidanceZoneParameters = AvoidanceZone::fromArray(array(
    "territory_name"   => "Test Rectangular Avoidance Zone ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$avoidancezone = new AvoidanceZone();

$result = $avoidancezone->addAvoidanceZone($AvoidanceZoneParameters);

Route4Me::simplePrint($result, true);
unit AddRectangularAvoidanceZoneUnit;

interface

uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit;

type
  TAddRectangularAvoidanceZone = class(TBaseExample)
  public
    function Execute: NullableString;
  end;

implementation

uses TerritoryUnit, AvoidanceZoneUnit;

function TAddRectangularAvoidanceZone.Execute: NullableString;

var
  ErrorString: String;
  AvoidanceZone: TAvoidanceZone;
  Territory: TRectangularTerritory;
  NewAvoidanceZone: TAvoidanceZone;
  TerritoryName, TerritoryColor: String;
begin
  Result := NullableString.Null;

  TerritoryName := 'Rect Territory';
  TerritoryColor := 'ff0000';
  Territory := TRectangularTerritory.Create(
    43.5166885350291, -109.3798828125, 46.9802523552188, -101.865234375);
  AvoidanceZone := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
  try
    NewAvoidanceZone := Route4MeManager.AvoidanceZone.Add(AvoidanceZone, ErrorString);
    try
      WriteLn('');

      if (NewAvoidanceZone <> nil) then
      begin
        WriteLn('AddRectangularAvoidanceZone executed successfully');
        WriteLn(Format('Territory ID: %s', [NewAvoidanceZone.TerritoryId.Value]));

        Result := NewAvoidanceZone.TerritoryId;
      end
      else
        WriteLn(Format('AddRectangularAvoidanceZone error: "%s"', [ErrorString]));
    finally
      FreeAndNil(NewAvoidanceZone);
    end;
  finally
    FreeAndNil(AvoidanceZone);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/avoidance.php?api_key=...&territory_id=...

You can expect this API response:

{
  "territory_id": "00BDD621FFF56266ED0BF7276B8DF7BA",
  "member_id": "1",
  "territory_name": "Rect Territory",
  "territory_color": "ff0000",
  "territory": {
    "type": "rect",
    "data": [
      "43.51668853502909,-109.3798828125",
      "46.98025235521883,-101.865234375"
    ]
  }
}

Get an Avoidance Zone

Get a specified Avoidance Zone object by its ID.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Avoidance zone ID
<job id="Get Avoidance Zone By ID">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example refers to the process of getting an Avoidance Zone object using an Avoidance Zone ID.
      
      url="https://api.route4me.com/api.v4/avoidance.php"
      apikey="11111111111111111111111111111111"
      terid="02ACC3A8A552A5F2F0C09E6839DBB761"
      
      url=url&"?api_key="&apikey
      url=url&"&territory_id="&terid
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Get Avoidance Zone
    /// </summary>
    /// <param name="territoryId"> Avoidance Zone ID </param>
    public void GetAvoidanceZone(string territoryId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      AvoidanceZoneQuery avoidanceZoneQuery = new AvoidanceZoneQuery()
      {
        TerritoryId = territoryId
      };

      // Run the query
      string errorString;
      AvoidanceZone avoidanceZone = route4Me.GetAvoidanceZone(avoidanceZoneQuery, out errorString);

      Console.WriteLine("");

      if (avoidanceZone != null)
      {
        Console.WriteLine("GetAvoidanceZone executed successfully");

        Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId);
      }
      else
      {
        Console.WriteLine("GetAvoidanceZone error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get Avoidance Zone
        ''' </summary>
        ''' <param name="territoryId"> Avoidance Zone ID </param>
        Public Sub GetAvoidanceZone(territoryId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim avoidanceZoneQuery As New AvoidanceZoneQuery() With { _
                .TerritoryId = territoryId _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim avoidanceZone As AvoidanceZone = route4Me.GetAvoidanceZone(avoidanceZoneQuery, errorString)

            Console.WriteLine("")

            If avoidanceZone IsNot Nothing Then
                Console.WriteLine("GetAvoidanceZone executed successfully")

                Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId)
            Else
                Console.WriteLine("GetAvoidanceZone error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    avoidance_zones = route4me.avoidance_zones
    response = avoidance_zones.get_avoidance_zones()
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        territory_id = response[0].territory_id
        print 'Getting Territory ID: {}'.format(territory_id)
        response = avoidance_zones.get_avoidance_zone(territory_id=territory_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Territory ID: {}'.format(response.territory_id)
            print '\tTerritory Name: {}'.format(response.territory_name)
            print '\tTerritory Color: {}'.format(response.territory_color)
            print '\tMember ID: {}'.format(response.member_id)
            print '\tTerritory Type: {}'.format(response.territory.type)
            if response.territory.data:
                print '\tData: '
                for data in response.territory.data:
                    print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Add Avoidance Zone and get territory_id
$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::CIRCLE;
$territoryParams['data'] = array(
    "37.569752822786455,-77.47833251953125",
    "5000"
);

$AvoisanceZoneParameters = AvoidanceZone::fromArray(array(
    "territory_name"   => "Test Territory ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$avoidancezone = new AvoidanceZone();

$result = (array)$avoidancezone->addAvoidanceZone($AvoisanceZoneParameters);

assert(isset($result), "Failed to create new Avoidance Zone");

$territory_id = $result["territory_id"];

echo "New Avoidance Zone with territory_id = $territory_id created successfully<br>";

$result1 = $avoidancezone->getAvoidanceZone($territory_id);

Route4Me::simplePrint($result1, true);
@ECHO OFF

SET url=https://api.route4me.com/api.v4/avoidance.php
SET apikey=11111111111111111111111111111111
SET terid=02ACC3A8A552A5F2F0C09E6839DBB761

:: The example refers to the process of getting an Avoidance Zone object using an Avoidance Zone ID.

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%&territory_id=%terid%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/avoidance.php
apikey=11111111111111111111111111111111
terid=02ACC3A8A552A5F2F0C09E6839DBB761

# The example refers to the process of getting an Avoidance Zone object using an Avoidance Zone ID.

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey&territory_id=$terid"

echo "Finished..."

sleep 15
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;
import java.util.List;

public class GetAvoidanceZone {

    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);;
        List<Territory> territories = territoriesManager.getAvoidanceZones();
        String territoryID;
        territoryID = territories.get(0).getTerritoryId();
        Territory responseObject = territoriesManager.getAvoidanceZone(territoryID);
        System.out.println(responseObject);
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
  
  zone, err := service.GetAvoidanceZone(&territories.Query{ID: "zoneid"})
  if err != nil {
    //handle error
    return
  }
  //do something with the zone
}
unit GetAvoidanceZoneUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAvoidanceZone = class(TBaseExample)
  public
    procedure Execute(TerritoryId: String);
  end;

implementation

uses AvoidanceZoneUnit;

procedure TGetAvoidanceZone.Execute(TerritoryId: String);

var
  ErrorString: String;
  AvoidanceZone: TAvoidanceZone;
begin
  AvoidanceZone := Route4MeManager.AvoidanceZone.Get(TerritoryId, ErrorString);
  try
    WriteLn('');

    if (AvoidanceZone <> nil) then
    begin
      WriteLn('GetAvoidanceZone executed successfully');
      WriteLn(Format('Territory ID: %s', [AvoidanceZone.TerritoryId.Value]));
    end
    else
      WriteLn(Format('GetAvoidanceZone error: %s', [ErrorString]));
  finally
    FreeAndNil(AvoidanceZone);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    if (route.get_avoidance_zone("") == 0) {
        cout << "Zone:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "No zone: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);

    if (!get_avoidance_zone("A1"))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
  return 0;
}


HTTP Request

GET
/api.v4/avoidance.php?api_key=...&territory_id=...

You can expect this API response:

{
  "territory_id": "02ACC3A8A552A5F2F0C09E6839DBB761",
  "member_id": "1",
  "territory_name": "Zone 1",
  "territory_color": "ffad46",
  "territory": {
    "type": "poly",
    "data": ["37.569752822786455,-77.47833251953125",
    "37.55886716305343,-77.48974800109863",
    "37.54763966054455,-77.4917221069336",
    "37.54655084306813,-77.48863220214844",
    "37.5502255383101,-77.48125076293945",
    "37.54797991274437,-77.47498512268066",
    "37.53327960206065,-77.4411678314209",
    "37.54430510679532,-77.43172645568848",
    "37.56641925847049,-77.46846199035645"]
  }
}

Get Multiple Avoidance Zones

Get all Avoidance Zone objects defined by a user.


PARAMETERS

Parameter Type Description
api_key string API key of the user
<job id="Get Avoidance Zones">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example refers to the process of getting all avoidance zones from a user account.
      
      url="https://api.route4me.com/api.v4/avoidance.php"
      apikey="11111111111111111111111111111111"
      
      url=url&"?api_key="&apikey
      
      Set r4m=New Route4Me
      
      r4m.HttpGetRequest(url)
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
  
  zones, err := service.GetAvoidanceZones(&territories.Query{})
  if err != nil {
    //Handle error
    return
  }
  //do something with zones, it's a []AvoidanceZone
}
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Get Avoidance Zone list
    /// </summary>
    public void GetAvoidanceZones()
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      AvoidanceZoneQuery avoidanceZoneQuery = new AvoidanceZoneQuery()
      {
        
      };

      // Run the query
      string errorString;
      AvoidanceZone[] avoidanceZones = route4Me.GetAvoidanceZones(avoidanceZoneQuery, out errorString);

      Console.WriteLine("");

      if (avoidanceZones != null)
      {
        Console.WriteLine("GetAvoidanceZones executed successfully, {0} zones returned", avoidanceZones.Length);
      }
      else
      {
        Console.WriteLine("GetAvoidanceZones error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get Avoidance Zone list
        ''' </summary>
        Public Sub GetAvoidanceZones()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim avoidanceZoneQuery As New AvoidanceZoneQuery()

            ' Run the query
            Dim errorString As String = ""
            Dim avoidanceZones As AvoidanceZone() = route4Me.GetAvoidanceZones(avoidanceZoneQuery, errorString)

            Console.WriteLine("")

            If avoidanceZones IsNot Nothing Then
                Console.WriteLine("GetAvoidanceZones executed successfully, {0} zones returned", avoidanceZones.Length)
            Else
                Console.WriteLine("GetAvoidanceZones error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    avoidance_zones = route4me.avoidance_zones
    response = avoidance_zones.get_avoidance_zones()
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        for i, territory in enumerate(response):
            print '{0}  - Territory ID: {1}'.format(i + 1,
                                                    territory.territory_id)
            print '\tTerritory Name: {}'.format(territory.territory_name)
            print '\tTerritory Color: {}'.format(territory.territory_color)
            print '\tMember ID: {}'.format(territory.member_id)
            print '\tTerritory Type: {}'.format(territory.territory.type)
            if territory.territory.data:
                print '\tData: '
                for data in territory.territory.data:
                    print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$avoidancezone = new AvoidanceZone();

$queryparameters = array ();

$azones = $avoidancezone->getAvoidanceZones($queryparameters);

foreach ($azones as $azone) {
    Route4Me::simplePrint($azone);
    echo "<br>";
}
package GetAvoidanceZones;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::QueryTypes::AvoidanceZoneQuery;
sub GetAvoidanceZones {
    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $avoidanceZoneQuery = AvoidanceZoneQuery->new();

    my $errorString;

    my @avoidanceZones = $route4Me->getAvoidanceZones($avoidanceZoneQuery, $errorString);

    print "\n";

    if (@avoidanceZones)
    {
        printf "GetAvoidanceZones executed successfully, %s zones returned\n", scalar @avoidanceZones;
    }
    else
    {
        printf "GetAvoidanceZones error: %s\n", $errorString;
    }
}
@ECHO OFF

SET url=https://api.route4me.com/api.v4/avoidance.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of getting all avoidance zones from a user account.

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/avoidance.php
apikey=11111111111111111111111111111111

# The example refers to the process of getting all avoidance zones from a user account.

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey"

echo "Finished..."

sleep 15
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;

import java.util.List;

public class GetAvoidanceZones {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        try {
            List<Territory> territories = territoriesManager.getAvoidanceZones();
            for (Territory territory : territories) {
                System.out.println(territory);
            }
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
unit GetAvoidanceZonesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetAvoidanceZones = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses AvoidanceZoneUnit;

procedure TGetAvoidanceZones.Execute;

var
  ErrorString: String;
  AvoidanceZones: TAvoidanceZoneList;
begin
  AvoidanceZones := Route4MeManager.AvoidanceZone.GetList(ErrorString);
  try
    WriteLn('');

    if (AvoidanceZones.Count > 0) then
      WriteLn(Format('GetAvoidanceZones executed successfully, %d zones returned',
        [AvoidanceZones.Count]))
    else
      WriteLn(Format('GetAvoidanceZones error: "%s"', [ErrorString]));
  finally
    FreeAndNil(AvoidanceZones);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    if (route.get_avoidance_zones() == 0) {
        cout << "All zones:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "No zones found: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/avoidance.php?api_key=...


See the sample JSON response of this method.


Remove an Avoidance Zone

Deletes a specified Avoidance Zone object.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Avoidance zone ID
<job id="Delete Avoidance Zone">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example refers to the process of removing an avoidance zone from a user account.
      
      url="https://api.route4me.com/api.v4/avoidance.php"
      apikey="11111111111111111111111111111111"
      terid1="F31128DB9EEA076B85ECDE37274A4D78"
      
      url=url&"?api_key="&apikey
      url=url&"&territory_id="&terid1
      
      jFile=""
      
      Set r4m=New Route4Me
      
      r4m.HttpDeleteRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Delete Avoidance Zone
    /// </summary>
    /// <param name="territoryId"> Avoidance Zone ID </param>
    public void DeleteAvoidanceZone(string territoryId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      AvoidanceZoneQuery avoidanceZoneQuery = new AvoidanceZoneQuery()
      {
        TerritoryId = territoryId
      };

      // Run the query
      string errorString;
      route4Me.DeleteAvoidanceZone(avoidanceZoneQuery, out errorString);

      Console.WriteLine("");

      if (errorString == "")
      {
        Console.WriteLine("DeleteAvoidanceZone executed successfully");

        Console.WriteLine("Territory ID: {0}", territoryId);
      }
      else
      {
        Console.WriteLine("DeleteAvoidanceZone error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Delete Avoidance Zone
        ''' </summary>
        ''' <param name="territoryId"> Avoidance Zone ID </param>
        Public Sub DeleteAvoidanceZone(territoryId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim avoidanceZoneQuery As New AvoidanceZoneQuery() With { _
                .TerritoryId = territoryId _
            }

            ' Run the query
            Dim errorString As String = ""
            route4Me.DeleteAvoidanceZone(avoidanceZoneQuery, errorString)

            Console.WriteLine("")

            If errorString = "" Then
                Console.WriteLine("DeleteAvoidanceZone executed successfully")

                Console.WriteLine("Territory ID: {0}", territoryId)
            Else
                Console.WriteLine("DeleteAvoidanceZone error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    avoidance_zones = route4me.avoidance_zones
    print 'Creating Poly Zone'
    territory = {"territory_name": "Polygon Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "poly",
                               "data": ["56.127184156131065,56.93115234375",
                                        "58.41322259056806,59.501953125",
                                        "61.53840616716746,59.315185546875",
                                        "61.047650586031104,51.998291015625",
                                        "59.254649544483726,53.63525390625",
                                        "56.47462805805596,54.42626953125"
                                        ]
                               }
                 }
    response = avoidance_zones.add_avoidance_zone(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        territory_id = response.territory_id
        print 'Territory ID: {0} -> Created'.format(territory_id)
        response = avoidance_zones.delete_avoidance_zone(
            territory_id=territory_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Territory ID: {0} -> Deleted: {1}'.format(territory_id,
                                                             response.status)

if __name__ == '__main__':
    main()
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Add Avoidance Zone and get territory_id
$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::CIRCLE;
$territoryParams['data'] = array(
    "37.569752822786455,-77.47833251953125",
    "5000"
);

$AvoisanceZoneParameters = AvoidanceZone::fromArray(array(
    "territory_name"   => "Test Territory ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$avoidancezone = new AvoidanceZone();

$result = (array)$avoidancezone->addAvoidanceZone($AvoisanceZoneParameters);

assert(isset($result), "Failed to create new Avoidance Zone");

$territory_id = $result["territory_id"];

echo "New Avoidance Zone with territory_id = $territory_id created successfully<br>";

$result1 = $avoidancezone->deleteAvoidanceZone($territory_id);

assert(isset($result), "Failed to delete the avoidance zone with territory_id = ".$territory_id);

echo "Avoidance Zone with territory_id = $territory_id was deleted successfully<br>";

Route4Me::simplePrint($result1);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
  
  err := service.DeleteAvoidanceZone(&territories.Query{ID: "zoneid"})
  if err != nil {
    //handle error
    return
  }
}
package DeleteAvoidanceZone;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::QueryTypes::AvoidanceZoneQuery;

sub DeleteAvoidanceZone {
    my ($self, $territoryId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $avoidanceZoneQuery = AvoidanceZoneQuery->new(
        territory_id => $territoryId
    );

    my $errorString = "";
    $route4Me->deleteAvoidanceZone($avoidanceZoneQuery, $errorString);

    print "\n";

    if ($errorString eq "")
    {
        print "DeleteAvoidanceZone executed successfully.\n";
        printf "Territory ID: %s\n", $territoryId;
    }
    else
    {
        printf "DeleteAvoidanceZone error: %s\n", $errorString;
    }
}
1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/avoidance.php
SET apikey=11111111111111111111111111111111
SET terid1=083F0E34A2271FCAFA5476A364F32B4E

:: The example refers to the process of removing an avoidance zone from a user account.

ECHO ON

curl -o file1.txt -g -k -X DELETE "%url%?api_key=%apikey%&territory_id=%terid1%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/avoidance.php
apikey=11111111111111111111111111111111
terid1=083F0E34A2271FCAFA5476A364F32B4E

 # The example refers to the process of removing an avoidance zone from a user account.

curl -o file1.txt -g -k -X DELETE "$url?api_key=$apikey&territory_id=$terid1"

echo "Finished..."

sleep 15
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Constants;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;
import com.route4me.sdk.services.territories.TerritoryData;

import java.util.ArrayList;
import java.util.List;

public class DeleteAvoidanceZone {

    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        List<String> polyTerritoryDataList = new ArrayList<>();
        polyTerritoryDataList.add("56.127184156131065,56.93115234375");
        polyTerritoryDataList.add("58.41322259056806,59.501953125");
        polyTerritoryDataList.add("61.53840616716746,59.315185546875");
        polyTerritoryDataList.add("61.047650586031104,51.998291015625");
        polyTerritoryDataList.add("59.254649544483726,53.63525390625");
        polyTerritoryDataList.add("56.47462805805596,54.42626953125");
        TerritoryData polyTerritoryData = new TerritoryData();
        polyTerritoryData.setData(polyTerritoryDataList);
        Territory polyTerritory = new Territory();
        polyTerritory.setTerritoryName("Polygon Territory");
        polyTerritory.setTerritoryColor("ff0000");
        polyTerritory.setTerritory(polyTerritoryData);
        polyTerritoryData.setType(Constants.TerritoryType.POLY.toString());
        Territory responseObject = territoriesManager.addAvoidanceZone(polyTerritory);

        System.out.println("Polygon Territory");
        System.out.println(responseObject.toString());
        System.out.println();

        System.out.println("Deleting Territory");
        boolean response = territoriesManager.deleteAvoidanceZone(responseObject.getTerritoryId());
        System.out.println(response);
    }
}
unit DeleteAvoidanceZoneUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TDeleteAvoidanceZone = class(TBaseExample)
  public
    procedure Execute(TerritoryId: String);
  end;

implementation

procedure TDeleteAvoidanceZone.Execute(TerritoryId: String);

var
  ErrorString: String;
begin
  Route4MeManager.AvoidanceZone.Remove(TerritoryId, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    WriteLn('DeleteAvoidanceZone executed successfully');
    WriteLn(Format('Territory ID: %s', [TerritoryId]));
  end
  else
    WriteLn(Format('DeleteAvoidanceZone error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    if (route.remove_avoidance_zone("ABC") == 0) {
        cout << "Zone removed:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "Zone removal failed: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please /*see */the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/api.v4/avoidance.php?api_key=...&territory_id=...

You can expect this API response:

{"status":true}

Update an Avoidance Zone

Updates a specified Avoidance Zone object with a circular shape.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Avoidance zone ID
input data POST data A valid JSON object string. See the Avoidance Zone JSON Schema as a guide.
<job id="Update Circle Avoidance Zone">
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
    WScript.Quit main()
    
    Function main()
      Dim r4m
      Dim jFile
      
      WScript.Echo "Please, press OK and wait..."
      
      ' The example refers to the process of updating an avoidance zone by sending HTTP parameters.
      
      url="https://api.route4me.com/api.v4/avoidance.php"
      apikey="11111111111111111111111111111111"
      terid="33C1D8EA0B3078B6238626259FBA914F"
      
      url=url&"?api_key="&apikey
      url=url&"&territory_id="&terid
      
      jFile="update_circle_zone_data.json"
      
      Set r4m=New Route4Me
      
      r4m.HttpPutRequest url,jFile
      
      main=1
      
      WScript.Echo "Finished..."
    End Function
  </script>
</job>
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
  public sealed partial class Route4MeExamples
  {
    /// <summary>
    /// Update Avoidance Zone
    /// </summary>
    /// <param name="territoryId"> Avoidance Zone ID </param>
    public void UpdateAvoidanceZone(string territoryId)
    {
      // Create the manager with the API key
      Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

      AvoidanceZoneParameters avoidanceZoneParameters = new AvoidanceZoneParameters()
      {
        TerritoryId = territoryId,
        TerritoryName = "Test Territory Updated",
        TerritoryColor = "ff00ff",
        Territory = new Territory()
        {
          Type = TerritoryType.Circle.Description(),
          Data = new string[] { "38.41322259056806,-78.501953234",
                                "3000"}
        }
      };

      // Run the query
      string errorString;
      AvoidanceZone avoidanceZone = route4Me.UpdateAvoidanceZone(avoidanceZoneParameters, out errorString);

      Console.WriteLine("");

      if (avoidanceZone != null)
      {
        Console.WriteLine("UpdateAvoidanceZone executed successfully");

        Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId);
      }
      else
      {
        Console.WriteLine("UpdateAvoidanceZone error: {0}", errorString);
      }
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Update Avoidance Zone
        ''' </summary>
        ''' <param name="territoryId"> Avoidance Zone ID </param>
        Public Sub UpdateAvoidanceZone(territoryId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim avoidanceZoneParameters As New AvoidanceZoneParameters() With { _
                .TerritoryId = territoryId, _
                .TerritoryName = "Test Territory Updated", _
                .TerritoryColor = "ff00ff", _
                .Territory = New Territory() With { _
                    .Type = EnumHelper.GetEnumDescription(TerritoryType.Circle), _
                    .Data = New String() {"38.41322259056806,-78.501953234", "3000"} _
                } _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim avoidanceZone As AvoidanceZone = route4Me.UpdateAvoidanceZone(avoidanceZoneParameters, errorString)

            Console.WriteLine("")

            If avoidanceZone IsNot Nothing Then
                Console.WriteLine("UpdateAvoidanceZone executed successfully")

                Console.WriteLine("Territory ID: {0}", avoidanceZone.TerritoryId)
            Else
                Console.WriteLine("UpdateAvoidanceZone error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    avoidance_zones = route4me.avoidance_zones
    print 'Creating Poly Zone'
    territory = {"territory_name": "Polygon Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "poly",
                               "data": ["56.127184156131065,56.93115234375",
                                        "58.41322259056806,59.501953125",
                                        "61.53840616716746,59.315185546875",
                                        "61.047650586031104,51.998291015625",
                                        "59.254649544483726,53.63525390625",
                                        "56.47462805805596,54.42626953125"
                                        ]
                               }
                 }
    response = avoidance_zones.add_avoidance_zone(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        territory_id = response.territory_id
        print 'Territory ID: {0} -> Created'.format(territory_id)
        print '\tTerritory Name: {}'.format(response.territory_name)
        print '\tTerritory Color: {}'.format(response.territory_color)
        print '\tMember ID: {}'.format(response.member_id)
        print '\tTerritory Type: {}'.format(response.territory.type)
        if response.territory.data:
            print '\tData: '
            for data in response.territory.data:
                print '\t\t{0}'.format(data)
        territory = {"territory_name": "Polygon Territory Updated",
                     "territory_color": "ff00ff",
                     "territory": {"type": "poly",
                                   "data": [
                                       "56.127184156131065,56.93115234375",
                                       "58.41322259056806,59.501953125",
                                       "61.53840616716746,59.315185546875",
                                       "61.047650586031104,51.998291015625",
                                       "59.254649544483726,53.63525390625",
                                       "56.47462805805596,54.42626953125"
                                   ]
                                   }
                     }
        response = avoidance_zones.update_avoidance_zone(
            territory_id=territory_id, **territory)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Territory ID: {}'.format(response.territory_id)
            print '\tTerritory Name: {}'.format(response.territory_name)
            print '\tTerritory Color: {}'.format(response.territory_color)
            print '\tMember ID: {}'.format(response.member_id)
            print '\tTerritory Type: {}'.format(response.territory.type)
            if response.territory.data:
                print '\tData: '
                for data in response.territory.data:
                    print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Add Avoidance Zone and get territory_id
$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::CIRCLE;
$territoryParams['data'] = array(
    "37.569752822786455,-77.47833251953125",
    "5000"
);

$AvoidanceZoneParameters = AvoidanceZone::fromArray(array(
    "territory_name"   => "Test Territory ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$avoidancezone = new AvoidanceZone();

$result = (array)$avoidancezone->addAvoidanceZone($AvoidanceZoneParameters);

assert(isset($result), "Failed to create new Avoidance Zone");

$territory_id = $result["territory_id"];

echo "New Avoidance Zone with territory_id = $territory_id created successfully<br>";

$territory = new Territory();
$territory->type = TerritoryTypes::RECT;
$territory->data = array(
    "37.869752822786455,-77.49833251953125",
    "5000"
);

$AvoidanceZoneParameters = array(
    "territory_id"     => $territory_id,
    "territory_name"   => "Test Territory Updated",
    "territory_color"  => "ff5500",
    "territory"        => $territory
);

$result1 = $avoidancezone->updateAvoidanceZone($AvoidanceZoneParameters);

assert(isset($result), "Can't update the avoidance zone with territory_id = $territory_id");

echo "Avoidance Zone with territory_id = $territory_id was updated successfully<br>";

Route4Me::simplePrint($result1, true);
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
  
  zone := //get zone using Get, GetAll or constructing yourself.
  contact, err := service.UpdateAvoidanceZone(zone)
  if err != nil {
    t.Error(err)
    return
  }
}
package UpdateAvoidanceZone;
use strict;
use warnings FATAL => 'all';
use Route4MeSDK::DataTypes::TerritoryType;

sub UpdateAvoidanceZone {
    my ($self, $territoryId) = @_;

    my $route4Me = Route4MeManager->new( ExamplesInfrastructure->ApiKey );

    my $avoidanceZoneParameters = new AvoidanceZoneParameters(
        territory_id => $territoryId,
        territory_name => "Test Territory Updated",
        territory_color => "ff00ff",
        territory => Territory->new(
          type => TerritoryType->Circle,
          data => ['38.41322259056806,-78.501953234', '3000']
        )
    );

    my $errorString;
    my $avoidanceZone = $route4Me->updateAvoidanceZone($avoidanceZoneParameters, $errorString);

    print "\n";

    if ($avoidanceZone)
    {
        print "UpdateAvoidanceZone executed successfully\n";
        printf "Territory ID: %s\n", $avoidanceZone->territory_id;
    }
    else
    {
        printf "UpdateAvoidanceZone error: %s\n", $errorString;
    }
}
1;
@ECHO OFF

SET url=https://api.route4me.com/api.v4/avoidance.php
SET apikey=11111111111111111111111111111111
SET terid=33C1D8EA0B3078B6238626259FBA914F

:: The example refers to the process of updating an avoidance zone by sending HTTP parameters.

ECHO ON

curl -o file1.txt -g -k -X PUT -d "@update_circle_zone_data.json" "%url%?api_key=%apikey%&territory_id=%terid%"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v4/avoidance.php
apikey=11111111111111111111111111111111
terid=33C1D8EA0B3078B6238626259FBA914F

# The example refers to the process of updating an avoidance zone by sending HTTP parameters.

curl -o file1.txt -g -k -X PUT -d '@update_circle_zone_data.json' "$url?api_key=$apikey&territory_id=$terid"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
unit UpdateAvoidanceZoneUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TUpdateAvoidanceZone = class(TBaseExample)
  public
    procedure Execute(TerritoryId: String);
  end;

implementation

uses AvoidanceZoneUnit, TerritoryUnit;

procedure TUpdateAvoidanceZone.Execute(TerritoryId: String);

var
  ErrorString: String;
  AvoidanceZone: TAvoidanceZone;
  Territory: TTerritory;
  NewAvoidanceZone: TAvoidanceZone;
  TerritoryName, TerritoryColor: String;
begin
  TerritoryName := 'Test Territory Updated';
  TerritoryColor := 'ff00ff';
  Territory := TCircleTerritory.Create(38.4132225905681, -78.501953234, 3000);
  AvoidanceZone := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
  try
    AvoidanceZone.TerritoryId := TerritoryId;

    NewAvoidanceZone := Route4MeManager.AvoidanceZone.Update(AvoidanceZone, ErrorString);
    try
      WriteLn('');

      if (NewAvoidanceZone <> nil) then
      begin
        WriteLn('UpdateAvoidanceZone executed successfully');
        WriteLn(Format('Territory ID: %s', [NewAvoidanceZone.TerritoryId.Value]));
      end
      else
        WriteLn(Format('UpdateAvoidanceZone error: "%s"', [ErrorString]));
    finally
      FreeAndNil(NewAvoidanceZone);
    end;
  finally
    FreeAndNil(AvoidanceZone);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    CRoute4Me route(KEY);

    if (route.update_avoidance_zone("ABC", poly_data) == 0) {
        cout << "Zone updated:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "Zone update failed: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/avoidance.php?api_key=...&territory_id=...&territory_id=...

You can expect this API response:

{
  "territory_id": "33C1D8EA0B3078B6238626259FBA914F",
  "member_id": "1",
  "territory_name": "Test Territory",
  "territory_color": "ff0000",
  "territory": {
    "type": "circle",
    "data": ["37.569752822786455,-77.47833251953125",
    "5000"]
  }
}

Territories

Territory refers to an area that is made up of smaller areas that are all joined together. For example:

See the Territory JSON Schema in our GitHub repository.

Territory Properties

Attribute Type Description
api_key string API key of the user
territory_id string Territory ID
member_id integer Member ID
territory_name string Avoidance zone name
territory_color string Avoidance zone color
territory object Territory property in Datatype

Create a Territory

a) Create a new territory with a circular shape

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Territory ID
input data POST data A valid JSON object string. See the Territory JSON Schema as a guide.
<job id="Create Circle Zone">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            WScript.Echo "Please, press OK and wait..."
            
            ' The example refers to the process of creating a territory zone with circle shape by sending HTTP data.
            
            url="https://api.route4me.com/api.v4/territory.php"
            apikey="11111111111111111111111111111111"
            
            url=url&"?api_key="&apikey
            
            jFile="create_circle_zone_data.json"
            
            Set r4m=New Route4Me
            
            r4m.HttpPostRequest url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/territory.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of creating a territory zone with circle shape by sending HTTP data.

ECHO ON

curl -o file1.txt -g -k -X POST -d "@create_circle_zone_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/territory.php
apikey=11111111111111111111111111111111

curl -o file1.txt -g -k -X POST -d "@create_circle_zone_data.json" "$url?api_key=$apikey"

 # The example refers to the process of creating a territory zone with circle shape by sending HTTP data.

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Create Territory with Circular Shape
        /// </summary>
        public void CreateTerritory()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AvoidanceZoneParameters territoryParameters = new AvoidanceZoneParameters
            {
                TerritoryName = "Test Territory",
                TerritoryColor = "ff0000",
                Territory = new Territory
                {
                    Type = TerritoryType.Circle.Description(),
                    Data = new string[] {
                        "37.569752822786455,-77.47833251953125",
                        "5000"
                    }
                }
            };

            // Run the query
            string errorString = "";
            AvoidanceZone territory = route4Me.CreateTerritory(territoryParameters, out errorString);

            Console.WriteLine("");

            if (territory != null)
            {
                Console.WriteLine("CreateTerritory executed successfully");

                Console.WriteLine("Territory ID: {0}", territory.TerritoryId);
            }
            else
            {
                Console.WriteLine("CreateTerritory error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Add Avoidance Zone
        ''' </summary>
        Public Sub CreateTerritory()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim territoryParameters As New AvoidanceZoneParameters() With { _
                .TerritoryName = "Test Territory", _
                .TerritoryColor = "ff0000", _
                .Territory = New Territory() With { _
                    .Type = EnumHelper.GetEnumDescription(TerritoryType.Circle), _
                    .Data = New String() {"37.569752822786455,-77.47833251953125", "5000"} _
                } _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim territory As AvoidanceZone = route4Me.CreateTerritory(territoryParameters, errorString)

            Console.WriteLine("")

            If territory IsNot Nothing Then
                Console.WriteLine("CreateTerritory executed successfully")

                Console.WriteLine("Territory ID: {0}", territory.TerritoryId)
            Else
                Console.WriteLine("CreateTerritory error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    territories = route4me.territory

    print 'Creating Circle Territory'
    territory = {"territory_name": "Circle Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "circle",
                               "data": ["37.569752822786455,-77.47833251953125",
                                        "5000",
                                        ]
                               }
                 }
    response = territories.add_territory(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Territory ID: {}'.format(response.territory_id)
        print '\tTerritory Name: {}'.format(response.territory_name)
        print '\tTerritory Color: {}'.format(response.territory_color)
        print '\tMember ID: {}'.format(response.member_id)
        print '\tTerritory Type: {}'.format(response.territory.type)
        if response.territory.data:
            print '\tData: '
            for data in response.territory.data:
                print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Constants;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;
import com.route4me.sdk.services.territories.TerritoryData;

import java.util.ArrayList;
import java.util.List;

public class AddTerritory {
    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        
        List<String> circleTerritoryDataList = new ArrayList<>();
        circleTerritoryDataList.add("37.569752822786455,-77.47833251953125");
        circleTerritoryDataList.add("5000");
        TerritoryData circleTerritoryData = new TerritoryData();
        circleTerritoryData.setData(circleTerritoryDataList);
        Territory circleTerritory = new Territory();
        circleTerritory.setTerritoryName("Circle Territory");
        circleTerritory.setTerritoryColor("ff0000");
        circleTerritory.setTerritory(circleTerritoryData);
        circleTerritoryData.setType(Constants.TerritoryType.CIRCLE.toString());
        responseObject = territoriesManager.addTerritory(circleTerritory);

        System.out.println("Circle Territory");
        System.out.println(responseObject.toString());
        System.out.println();
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
    
    territory := &territories.Territory{
        Name:  "Some territory",
        Color: "beeeee", //hexadecimal color
        Territory: territories.TerritoryShape{
            Type: territories.Circle, //Type of an area
            Data: []string{"37.569752822786455,-77.47833251953125", "5000"},
        },
    }
    newTerritory, err := service.AddTerritory(zone)
    if err != nil {
        //handle errors
        return
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::CIRCLE;
$territoryParams['data'] = array(
    "37.569752822786455,-77.47833251953125",
    "5000"
);

$TerritoryParameters = Territory::fromArray(array(
    "territory_name"   => "Test Territory ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$territory = new Territory();

$result = $territory->addTerritory($TerritoryParameters);

Route4Me::simplePrint($result, true);
unit AddCircleTerritoryUnit;

interface

uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit;

type
  TAddCircleTerritory = class(TBaseExample)
  public
    function Execute: NullableString;
  end;

implementation

uses TerritoryContourUnit;

function TAddCircleTerritory.Execute: NullableString;

var
  ErrorString: String;
  TerritoryName, TerritoryColor: String;
  TerritoryContour: TTerritoryContour;
  TerritoryId: NullableString;
begin
  TerritoryName := 'Circle Territory';
  TerritoryColor := 'ff0000';
  TerritoryContour := TTerritoryContour.MakeCircleContour(
    37.5697528227865, -77.4783325195313, 5000);

  TerritoryId := Route4MeManager.Territory.Add(
    TerritoryName, TerritoryColor, TerritoryContour, ErrorString);

  WriteLn('');

  if (TerritoryId.IsNotNull) then
  begin
    WriteLn('AddCircleTerritory executed successfully');
    WriteLn(Format('Territory ID: %s', [TerritoryId.Value]));
  end
  else
    WriteLn(Format('AddCircleTerritory error: "%s"', [ErrorString]));

  Result := TerritoryId;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    ifstream inf("territory.json");
    if(!inf.is_open()) {
        cout << "Can't find a file with territory" << endl;
        return -1;
    }

    Json::Value territory_data;
    inf >> territory_data;
    CRoute4Me route(KEY);

     if (route.add_territory(territory_data) == 0) {
        cout << "Added territory:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "Failed adding territory: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/territory.php?api_key=...&territory_id=...

You can expect this API response:

{
    "territory_id": "206CB7EC7E94D82B29926C0801664184",
    "member_id": "1",
    "territory_name": "Test Territory",
    "territory_color": "ff0000",
    "addresses": [],
    "territory": {
        "type": "circle",
        "data": ["37.569752822786455,-77.47833251953125",
        "5000"]
    }
}

b) Create a new territory with a polygon shape

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Territory ID
input data POST data A valid JSON object string. See the Territory JSON Schema as a guide.
<job>
  <script language="VBScript" src="../Route4Me.vbs"/>
  <script language="VBScript">
      WScript.Quit main()
      
      Function main()
          Dim r4m
          Dim jFile
          
          WScript.Echo "Please, press OK and wait..."
          
          ' The example refers to the process of creating a territory zone with a polygon shape by sending HTTP data.
          
          url="https://api.route4me.com/api.v4/territory.php"
          apikey="11111111111111111111111111111111"
          
          url=url&"?api_key="&apikey
          
          jFile="create_poly_zone_data.json"
          
          Set r4m=New Route4Me
          
          r4m.HttpPostRequest url,jFile
          
          main=1
          
          WScript.Echo "Finished..."
      End Function
  </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/territory.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of creating a territory zone with a polygon shape by sending HTTP data.

ECHO ON

curl -o file1.txt -g -k -X POST -d "@create_poly_zone_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/territory.php
apikey=11111111111111111111111111111111

 # The example refers to the process of creating a territory zone with a polygon shape by sending HTTP data.

curl -o file1.txt -g -k -X POST -d "@create_poly_zone_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Create Territory with Polygon Shape
        /// </summary>
        public void CreatePolygonTerritory()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AvoidanceZoneParameters territoryParameters = new AvoidanceZoneParameters
            {
                TerritoryName = "Test Territory",
                TerritoryColor = "ff0000",
                Territory = new Territory
                {
                    Type = TerritoryType.Poly.Description(),
                    Data = new string[] {
                        "37.569752822786455,-77.47833251953125",
                        "37.75886716305343,-77.68974800109863",
                        "37.74763966054455,-77.6917221069336",
                        "37.74655084306813,-77.68863220214844",
                        "37.7502255383101,-77.68125076293945",
                        "37.74797991274437,-77.67498512268066",
                        "37.73327960206065,-77.6411678314209",
                        "37.74430510679532,-77.63172645568848",
                        "37.76641925847049,-77.66846199035645"
                    }
                }
            };

            // Run the query
            string errorString = "";
            AvoidanceZone territory = route4Me.CreateTerritory(territoryParameters, out errorString);

            Console.WriteLine("");

            if (territory != null)
            {
                Console.WriteLine("CreatePolygonTerritory executed successfully");

                Console.WriteLine("Territory ID: {0}", territory.TerritoryId);
            }
            else
            {
                Console.WriteLine("CreatePolygonTerritory error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Add Polygon Territory
        ''' </summary>
        Public Sub CreatePolygonTerritory()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim territoryParameters As New AvoidanceZoneParameters() With { _
                .TerritoryName = "Test Territory", _
                .TerritoryColor = "ff0000", _
                .Territory = New Territory() With { _
                    .Type = EnumHelper.GetEnumDescription(TerritoryType.Poly), _
                    .Data = New String() { _ 
                    "37.569752822786455,-77.47833251953125", _
                    "37.75886716305343,-77.68974800109863", _
                    "37.74763966054455,-77.6917221069336", _
                    "37.74655084306813,-77.68863220214844", _
                    "37.7502255383101,-77.68125076293945", _
                    "37.74797991274437,-77.67498512268066", _
                    "37.73327960206065,-77.6411678314209", _
                    "37.74430510679532,-77.63172645568848", _
                    "37.76641925847049,-77.66846199035645"} _
                } _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim territory As AvoidanceZone = route4Me.CreateTerritory(territoryParameters, errorString)

            Console.WriteLine("")

            If territory IsNot Nothing Then
                Console.WriteLine("CreatePolygonTerritory executed successfully")

                Console.WriteLine("Territory ID: {0}", territory.TerritoryId)
            Else
                Console.WriteLine("CreatePolygonTerritory error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    territories = route4me.territory
    
    print 'Creating Poly Territory'
    territory = {"territory_name": "Polygon Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "poly",
                               "data": ["56.127184156131065,56.93115234375",
                                        "58.41322259056806,59.501953125",
                                        "61.53840616716746,59.315185546875",
                                        "61.047650586031104,51.998291015625",
                                        "59.254649544483726,53.63525390625",
                                        "56.47462805805596,54.42626953125"
                                        ]
                               }
                 }
    response = territories.add_territory(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Territory ID: {}'.format(response.territory_id)
        print '\tTerritory Name: {}'.format(response.territory_name)
        print '\tTerritory Color: {}'.format(response.territory_color)
        print '\tMember ID: {}'.format(response.member_id)
        print '\tTerritory Type: {}'.format(response.territory.type)
        if response.territory.data:
            print '\tData: '
            for data in response.territory.data:
                print '\t\t{0}'.format(data)
 
if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Constants;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;
import com.route4me.sdk.services.territories.TerritoryData;

import java.util.ArrayList;
import java.util.List;

public class AddTerritory {
    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        List<String> polyTerritoryDataList = new ArrayList<>();
        polyTerritoryDataList.add("56.127184156131065,56.93115234375");
        polyTerritoryDataList.add("58.41322259056806,59.501953125");
        polyTerritoryDataList.add("61.53840616716746,59.315185546875");
        polyTerritoryDataList.add("61.047650586031104,51.998291015625");
        polyTerritoryDataList.add("59.254649544483726,53.63525390625");
        polyTerritoryDataList.add("56.47462805805596,54.42626953125");
        TerritoryData polyTerritoryData = new TerritoryData();
        polyTerritoryData.setData(polyTerritoryDataList);
        Territory polyTerritory = new Territory();
        polyTerritory.setTerritoryName("Polygon Territory");
        polyTerritory.setTerritoryColor("ff0000");
        polyTerritory.setTerritory(polyTerritoryData);
        polyTerritoryData.setType(Constants.TerritoryType.POLY.toString());
        Territory responseObject = territoriesManager.addTerritory(polyTerritory);

        System.out.println("Polygon Territory");
        System.out.println(responseObject.toString());
        System.out.println();
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
    
    territory := &territories.Territory{
        Name:  "Some territory",
        Color: "beeeee", //hexadecimal color
        Territory: territories.TerritoryShape{
            Type: territories.Polygonal, //Type of an area
            Data: []string{"37.769752822786455,-77.67833251953125",
                "37.75886716305343,-77.68974800109863",
                "37.74763966054455,-77.6917221069336",
                "37.74655084306813,-77.68863220214844",
                "37.7502255383101,-77.68125076293945",
                "37.74797991274437,-77.67498512268066",
                "37.73327960206065,-77.6411678314209",
                "37.74430510679532,-77.63172645568848",
                "37.76641925847049,-77.66846199035645"},
        },
    }
    newTerritory, err := service.AddTerritory(territory)
    if err != nil {
        //handle errors
        return
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example refers to the process of creating a territory with a polygon shape

$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::POLY;
$territoryParams['data'] = array(
    "37.769752822786455,-77.67833251953125",
    "37.75886716305343,-77.68974800109863",
    "37.74763966054455,-77.6917221069336",
    "37.74655084306813,-77.68863220214844",
    "37.7502255383101,-77.68125076293945",
    "37.74797991274437,-77.67498512268066",
    "37.73327960206065,-77.6411678314209",
    "37.74430510679532,-77.63172645568848",
    "37.76641925847049,-77.66846199035645"
);

$TerritoryParameters = Territory::fromArray(array(
    "territory_name"   => "Test Polygonian Territory ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$territory = new Territory();

$result = $territory->addTerritory($TerritoryParameters);

Route4Me::simplePrint($result, true);
unit AddPolygonTerritoryUnit;

interface

uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit;

type
  TAddPolygonTerritory = class(TBaseExample)
  public
    function Execute: NullableString;
  end;

implementation

uses TerritoryContourUnit, TerritoryUnit, PositionUnit;

function TAddPolygonTerritory.Execute: NullableString;

var
  ErrorString: String;
  TerritoryContour: TTerritoryContour;
  TerritoryName, TerritoryColor: String;
  TerritoryId: NullableString;
begin
  Result := NullableString.Null;

  TerritoryName := 'Polygon Territory';
  TerritoryColor := 'ff0000';
  TerritoryContour := TTerritoryContour.MakePolygonContour([
    TPosition.Create(37.7697528227865, -77.6783325195313),
    TPosition.Create(37.7588671630534, -77.6897480010986),
    TPosition.Create(37.7476396605445, -77.6917221069336),
    TPosition.Create(37.7465508430681, -77.6886322021484),
    TPosition.Create(37.7502255383101, -77.6812507629394),
    TPosition.Create(37.7479799127443, -77.6749851226806),
    TPosition.Create(37.7332796020606, -77.6411678314209),
    TPosition.Create(37.7443051067953, -77.6317264556884),
    TPosition.Create(37.7664192584704, -77.6684619903564)
  ]);

  TerritoryId := Route4MeManager.Territory.Add(
    TerritoryName, TerritoryColor, TerritoryContour, ErrorString);

  WriteLn('');

  if (TerritoryId.IsNotNull) then
  begin
    WriteLn('AddPolygonTerritory executed successfully');
    WriteLn(Format('Territory ID: %s', [Result.Value]));
  end
  else
    WriteLn(Format('AddPolygonTerritory error: "%s"', [ErrorString]));

  Result := TerritoryId;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    char* data = NULL;
    init(key, 0);

    if (deserialize("create_poly_zone_data.json", &data))
    {
        printf("Data file not found!\n");
    }

    if (!add_territory(data))
    {
       json_object* opt_lst = getJSONResponse();
       json_object* opt_id = json_object_object_get(opt_lst, "territory_id");
       printf("Territory added: %s\n", json_object_to_json_string(opt_id));
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    if (data)
    {
        free(data);
    }
    cleanUp();
    return 0;
}


HTTP Request

POST
/api.v4/territory.php?api_key=...&territory_id=...

You can expect this API response:

{
    "territory_id": "FBCEA43FC1E1B48B573F3E89A4CDFBEF",
    "member_id": "1",
    "territory_name": "Polygon Territory",
    "territory_color": "ff0000",
    "addresses": [],
    "territory": {
        "type": "poly",
        "data": ["37.769752822786455,-77.67833251953125",
        "37.75886716305343,-77.68974800109863",
        "37.74763966054455,-77.6917221069336",
        "37.74655084306813,-77.68863220214844",
        "37.7502255383101,-77.68125076293945",
        "37.74797991274437,-77.67498512268066",
        "37.73327960206065,-77.6411678314209",
        "37.74430510679532,-77.63172645568848",
        "37.76641925847049,-77.66846199035645"]
    }
}

c) Create a new territory with a rectangular shape

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Territory ID
input data POST data A valid JSON object string. See the Territory JSON Schema as a guide.
<job id="Create Rectangle Zone">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            WScript.Echo "Please, press OK and wait..."
            
            ' The example refers to the process of creating a territory zone with rectangle shape by sending HTTP data.
            
            url="https://api.route4me.com/api.v4/territory.php"
            apikey="11111111111111111111111111111111"
            
            url=url&"?api_key="&apikey
            
            jFile="create_rect_zone_data.json"
            
            Set r4m=New Route4Me
            
            r4m.HttpPostRequest url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/territory.php
SET apikey=11111111111111111111111111111111

:: The example refers to the process of creating a territory zone with rectangle shape by sending HTTP data.

ECHO ON

curl -o file1.txt -g -k -X POST -d "@create_rect_zone_data.json" "%url%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/territory.php
apikey=11111111111111111111111111111111

 # The example refers to the process of creating a territory zone with rectangle shape by sending HTTP data.

curl -o file1.txt -g -k -X POST -d "@create_rect_zone_data.json" "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Create Territory with Rectangular Shape
        /// </summary>
        public void CreateRectTerritory()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AvoidanceZoneParameters territoryParameters = new AvoidanceZoneParameters
            {
                TerritoryName = "Test Territory",
                TerritoryColor = "ff0000",
                Territory = new Territory
                {
                    Type = TerritoryType.Rect.Description(),
                    Data = new string[] {
                        "43.51668853502909,-109.3798828125",
                        "46.98025235521883,-101.865234375"
                    }
                }
            };

            // Run the query
            string errorString = "";
            AvoidanceZone territory = route4Me.CreateTerritory(territoryParameters, out errorString);

            Console.WriteLine("");

            if (territory != null)
            {
                Console.WriteLine("CreateRectTerritory executed successfully");
                Console.WriteLine("Territory ID: {0}", territory.TerritoryId);
            }
            else
            {
                Console.WriteLine("CreateRectTerritory error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Add Rectangle Territory
        ''' </summary>
        Public Sub CreateRectTerritory()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim territoryParameters As New AvoidanceZoneParameters() With { _
                .TerritoryName = "Test Territory", _
                .TerritoryColor = "ff0000", _
                .Territory = New Territory() With { _
                    .Type = EnumHelper.GetEnumDescription(TerritoryType.Rect), _
                    .Data = New String() { _
                        "43.51668853502909,-109.3798828125", _
                        "46.98025235521883,-101.865234375" _
                        } _
                } _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim territory As AvoidanceZone = route4Me.CreateTerritory(territoryParameters, errorString)

            Console.WriteLine("")

            If territory IsNot Nothing Then
                Console.WriteLine("CreateRectTerritory executed successfully")

                Console.WriteLine("Territory ID: {0}", territory.TerritoryId)
            Else
                Console.WriteLine("CreateRectTerritory error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    territories = route4me.territory
    
    print 'Creating Rect Territory'
    territory = {"territory_name": "Rect Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "rect",
                               "data": ["43.51668853502909,-109.3798828125",
                                        "46.98025235521883,-101.865234375"
                                        ]
                               }
                 }
    response = territories.add_territory(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        print 'Territory ID: {}'.format(response.territory_id)
        print '\tTerritory Name: {}'.format(response.territory_name)
        print '\tTerritory Color: {}'.format(response.territory_color)
        print '\tMember ID: {}'.format(response.member_id)
        print '\tTerritory Type: {}'.format(response.territory.type)
        if response.territory.data:
            print '\tData: '
            for data in response.territory.data:
                print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Constants;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;
import com.route4me.sdk.services.territories.TerritoryData;

import java.util.ArrayList;
import java.util.List;

public class AddTerritory {
    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        
        List<String> rectTerritoryDataList = new ArrayList<>();
        rectTerritoryDataList.add("43.51668853502909,-109.3798828125");
        rectTerritoryDataList.add("46.98025235521883,-101.865234375");
        TerritoryData rectTerritoryData = new TerritoryData();
        rectTerritoryData.setData(rectTerritoryDataList);
        Territory rectTerritory = new Territory();
        rectTerritory.setTerritoryName("Rect Territory");
        rectTerritory.setTerritoryColor("ff0000");
        rectTerritory.setTerritory(rectTerritoryData);
        rectTerritoryData.setType(Constants.TerritoryType.RECT.toString());
        responseObject = territoriesManager.addTerritory(rectTerritory);

        System.out.println("Rect Territory");
        System.out.println(responseObject.toString());
        System.out.println();
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
    
    territory := &territories.Territory{
        Name:  "Some zone",
        Color: "beeeee", //hexadecimal color
        Territory: territories.TerritoryShape{
            Type: territories.Rectangular, //Type of an area
            Data: []string{"43.51668853502909,-109.3798828125","46.98025235521883,-101.865234375"},
        },
    }
    newTerritory, err := service.AddTerritory(territory)
    if err != nil {
        //handle errors
        return
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// The example refers to the process of creating a territory with a rectangular shape

$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::RECT;
$territoryParams['data'] = array(
    "43.51668853502909,-109.3798828125",
    "46.98025235521883,-101.865234375"
);

$TerritoryParameters = Territory::fromArray(array(
    "territory_name"   => "Test Rectangular Territory ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$territory = new Territory();

$result = $territory->addTerritory($TerritoryParameters);

Route4Me::simplePrint($result, true);
unit AddRectangularTerritoryUnit;

interface

uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit;

type
  TAddRectangularTerritory = class(TBaseExample)
  public
    function Execute: NullableString;
  end;

implementation

uses TerritoryContourUnit, TerritoryUnit;

function TAddRectangularTerritory.Execute: NullableString;

var
  ErrorString: String;
  TerritoryContour: TTerritoryContour;
  TerritoryName, TerritoryColor: String;
  TerritoryId: NullableString;
begin
  Result := NullableString.Null;

  TerritoryName := 'Rect Territory';
  TerritoryColor := 'ff0000';
  TerritoryContour := TTerritoryContour.MakeRectangularContour(
    43.5166885350291, -109.3798828125, 46.9802523552188, -101.865234375);

  TerritoryId := Route4MeManager.Territory.Add(
    TerritoryName, TerritoryColor, TerritoryContour, ErrorString);

  WriteLn('');

  if (TerritoryId.IsNotNull) then
  begin
    WriteLn('AddRectangularTerritory executed successfully');
    WriteLn(Format('Territory ID: %s', [Result.Value]));
  end
  else
    WriteLn(Format('AddRectangularTerritory error: "%s"', [ErrorString]));

  Result := TerritoryId;
end;
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/api.v4/territory.php?api_key=...&territory_id=...

You can expect this API response:

{
    "territory_id": "C480883359A9C4EC528509CD8D65E121",
    "member_id": "****",
    "territory_name": "Rect Territory",
    "territory_color": "ff0000",
    "addresses": [],
    "territory": {
        "type": "rect",
        "data": ["43.51668853502909,-109.3798828125",
        "46.98025235521883,-101.865234375"]
    }
}

Get a Territory

Get a specified Territory object by its ID.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Territory ID
addresses integer If equal to 1, the enclosed addresses will be included in the response.
orders integer If equal to 1, the enclosed orders will be included in the response.
<job id="Get Territory Zone By Id">
	<script language="VBScript" src="../Route4Me.vbs"/>
	<script language="VBScript">
		WScript.Quit main()
		
		Function main()
			Dim r4m
			
			WScript.Echo "Please, press OK and wait..."
			
			url="https://api.route4me.com/api.v4/territory.php"
			apikey="11111111111111111111111111111111"
			terid="63E27D8186AAE43F202CB97DECBFD826"
			addresses=1
			orders=1
			
			url=url&"?api_key="&apikey
			url=url&"&territory_id="&terid
			url=url&"&addresses="&addresses
			url=url&"&orders="&orders
			
			Set r4m=New Route4Me
			
			r4m.outputFile="get_territory_with_addresses_orders_RESPONSE.json"
			
			r4m.HttpGetRequest(url)
			
			main=1
			
			WScript.Echo "Finished..."
		End Function
	</script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/territory.php

SET apikey=11111111111111111111111111111111
SET terid=63E27D8186AAE43F202CB97DECBFD826
SET addresses=1
SET orders=1

ECHO ON

:: The example refers to the process of getting Territory zone with covered addresses and orders.

curl -o get_territory_with_addresses_orders_RESPONSE.json -g -k -X GET "%url%?api_key=%apikey%&territory_id=%terid%&addresses=%addresses%&orders=%orders%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/territory.php
apikey=11111111111111111111111111111111
terid=63E27D8186AAE43F202CB97DECBFD826
addresses=1
orders=1

 # The example refers to the process of getting Territory zone with covered addresses and orders.

curl -o get_territory_with_addresses_orders_RESPONSE.json -g -k -X GET "$url?api_key=$apikey&territory_id=$terid&addresses=$addresses&orders=$orders"

echo "Finished..."

sleep 15
public void GetTerritoryTest()
{
	Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

	string territoryId = "";

	if (lsTerritories.Count > 1) territoryId = lsTerritories[1];

	TerritoryQuery territoryQuery = new TerritoryQuery()
	{
		TerritoryId = territoryId,
		Addresses = 1,
		Orders = 1
	};

	// Run the query
	string errorString;
	TerritoryZone territory = route4Me.GetTerritory(territoryQuery, out errorString);

	Assert.IsNotNull(territory, "GetTerritoryTest failed... " + errorString);
}
 Public Sub GetTerritoryTest()
	Dim route4Me As New Route4MeManager(c_ApiKey)

	Dim territoryId As String = ""

	If lsTerritories.Count > 1 Then
		territoryId = lsTerritories(1)
	End If

	Dim territoryQuery As New TerritoryQuery() With {
		.TerritoryId = territoryId,
		.Addresses = 1,
		.Orders = 1
	}

	' Run the query
	Dim errorString As String = ""
	Dim territory As TerritoryZone = route4Me.GetTerritory(territoryQuery, errorString)

	Assert.IsNotNull(territory, Convert.ToString("GetTerritoryTest failed... ") & errorString)
End Sub
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    territories = route4me.territory
    response = territories.get_territories()
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        territory_id = response[0].territory_id
        print 'Getting Territory ID: {}'.format(territory_id)
        response = territories.get_territory(territory_id=territory_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Territory ID: {}'.format(response.territory_id)
            print '\tTerritory Name: {}'.format(response.territory_name)
            print '\tTerritory Color: {}'.format(response.territory_color)
            print '\tMember ID: {}'.format(response.member_id)
            print '\tTerritory Type: {}'.format(response.territory.type)
            if response.territory.data:
                print '\tData: '
                for data in response.territory.data:
                    print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;

import java.util.List;

public class GetTerritory {

    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);;
        List<Territory> territories = territoriesManager.getTerritories();
        String territoryID;
        territoryID = territories.get(0).getTerritoryId();
        Territory responseObject = territoriesManager.getTerritory(territoryID);
        System.out.println(responseObject);
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
    
    territory, err := service.GetTerritory(&territories.Query{ID: "territory id"})
    if err != nil {
        //handle error
        return
    }
    //do something with the territory
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the api key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$territory = new Territory();

// Select a terriotry with the enclosed addresses and orders from the list
$params = [
    'offset'    => 0,
    'limit'     => 50,
    'addresses' => 1,
    'orders'    => 1
];

$results = $territory->getTerritories($params);

assert(!is_null($results), "Cannot retrieve the territories with addresses");

$territory1 = null;

foreach ($results as $terr) {
    if (isset($terr['addresses'])) {
        if (sizeof($terr['addresses']) > 0) {
            $territory1 = $terr;
            break;
        }
    }
}

assert(isset($territory1['territory_id']), "Cannot retrieve a random territory ID");

$territory_id = $territory1['territory_id'];

echo "Territory ID -> $territory_id <br><br>";

// Get a territory with the addresses
$params = [
    'territory_id' => $territory_id,
    'addresses' => 1,
];

$result1 = $territory->getTerritory($params);

Route4Me::simplePrint($result1, true);
unit GetTerritoryUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetTerritory = class(TBaseExample)
  public
    procedure Execute(TerritoryId: String);
  end;

implementation

uses TerritoryUnit;

procedure TGetTerritory.Execute(TerritoryId: String);

var
  ErrorString: String;
  Territory: TTerritory;
  GetEnclosedAddresses: boolean;
begin
  GetEnclosedAddresses := False;
  Territory := Route4MeManager.Territory.Get(
    TerritoryId, GetEnclosedAddresses, ErrorString);
  try
    WriteLn('');

    if (Territory <> nil) then
    begin
      WriteLn('GetTerritory executed successfully');
      WriteLn(Format('Territory ID: %s', [Territory.Id.Value]));
    end
    else
      WriteLn(Format('GetTerritory error: %s', [ErrorString]));
  finally
    FreeAndNil(Territory);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    Json::Value territory_data;
    inf >> territory_data;
    CRoute4Me route(KEY);

    if (route.get_territory("DCBBBF90D8E9399B99C4D6FF11ED999F") == 0) {
        cout << "Found territories:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "No territories found: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);
    const char id[] = "F8320C21984385D473DFA73C1A86339D";

    if (!get_territory(id))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}


HTTP Request

GET
/api.v4/territory.php?api_key=...&territory_id=...

You can expect this API response:

{
	"territory_id": "63E27D8186AAE43F202CB97DECBFD826",
	"member_id": "1",
	"territory_name": "Houston Test Area",
	"territory_color": "16a765",
	"addresses": [
		50240057, 50240056, 50240055, 50240054,
		50240053, 50240052, 50240051, 50240050,
		50240049, 50240048
	],
	"orders": [
		36864, 37120, 37376, 37632,
		38144, 38400, 38656, 39168,
		39424, 39680, 40192, 40448,
		40704, 40960, 41216
	],
	"territory": {
		"type": "poly",
		"data": [
			"29.761136250306,-95.373945236206",
			"29.76139703434,-95.37119865417",
			"29.75487722975,-95.360083580017",
			"29.753386929151,-95.358324050903",
			"29.751486763744,-95.358281135559",
			"29.7502199667945,-95.36021232605",
			"29.7510396607664,-95.36403179168",
			"29.7541693397318,-95.368323326110",
			"29.758602884318,-95.374588966369"
		]
	}
}

Get Multiple Territories

Get all Territory objects defined by a user.


PARAMETERS

Parameter Type Description
api_key string API key of the user
<job id="Get Territory Zones">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            
            WScript.Echo "Please, press OK and wait..."
            
            ' The example refers to the process of getting the territory zones from a user's account.
            
            url="https://api.route4me.com/api.v4/territory.php"
            apikey="11111111111111111111111111111111"
            
            url=url&"?api_key="&apikey
            
            Set r4m=New Route4Me
            
            r4m.HttpGetRequest(url)
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/territory.php
SET apikey=11111111111111111111111111111111
SET addresses=1

:: The example refers to the process of getting the territory zones from a user's account.

ECHO ON
curl -o file1.txt -g -k -X GET "%URL%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/territory.php
apikey=11111111111111111111111111111111

 # The example refers to the process of getting the territory zones from a user's account.

curl -o file1.txt -g -k -X GET "$url?api_key=$apikey"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Get Territories
        /// </summary>
        public void GetTerritories()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            AvoidanceZoneQuery territoryQuery = new AvoidanceZoneQuery();

            // Run the query
            string errorString = "";
            AvoidanceZone[] territories = route4Me.GetTerritories(territoryQuery, out errorString);

            Console.WriteLine("");

            if (territories != null)
            {
                Console.WriteLine("GetTerritories executed successfully");

                Console.WriteLine("GetAvoidanceZones executed successfully, {0} territories returned", territories.Length);
            }
            else
            {
                Console.WriteLine("GetTerritories error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Get Territories
        ''' </summary>
        Public Sub GetTerritories()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim territoryQuery As New AvoidanceZoneQuery()

            ' Run the query
            Dim errorString As String = ""
            Dim territories As AvoidanceZone() = route4Me.GetTerritories(territoryQuery, errorString)

            Console.WriteLine("")

            If territories IsNot Nothing Then
                Console.WriteLine("GetTerritories executed successfully")

                Console.WriteLine("GetAvoidanceZones executed successfully, {0} territories returned", territories.Count)
            Else
                Console.WriteLine("GetTerritories error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    territory = route4me.territory
    response = territory.get_territories()
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        for i, territory in enumerate(response):
            print '{0}  - Territory ID: {1}'.format(i + 1,
                                                    territory.territory_id)
            print '\tTerritory Name: {}'.format(territory.territory_name)
            print '\tTerritory Color: {}'.format(territory.territory_color)
            print '\tMember ID: {}'.format(territory.member_id)
            print '\tTerritory Type: {}'.format(territory.territory.type)
            if territory.territory.data:
                print '\tData: '
                for data in territory.territory.data:
                    print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;

import java.util.List;

public class GetTerritories {

    public static void main(String[] args) {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        try {
            List<Territory> territories = territoriesManager.getTerritories();
            for (Territory territory : territories) {
                System.out.println(territory);
            }
        } catch (APIException e) {
            //handle exception
            e.printStackTrace();
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
    
    territories, err := service.GetTerritories(&territories.Query{})
    if err != nil {
        //Handle error
        return
    }
    //do something with territories, it's a []Territory
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

$territory = new Territory();

$queryparameters = array (
    "offset" => 0,
    "limit"  => 20
);

$response = $territory->getTerritories($queryparameters);

foreach ($response as $terr1) {
    Route4Me::simplePrint($terr1, true);
    echo "<br>";
}
unit GetTerritoriesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetTerritories = class(TBaseExample)
  public
    procedure Execute;
  end;

implementation

uses TerritoryUnit;

procedure TGetTerritories.Execute;

var
  ErrorString: String;
  Territories: TTerritoryList;
begin
  Territories := Route4MeManager.Territory.GetList(ErrorString);
  try
    WriteLn('');

    if (Territories.Count > 0) then
      WriteLn(Format('GetTerritories executed successfully, %d zones returned',
        [Territories.Count]))
    else
      WriteLn(Format('GetTerritories error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Territories);
  end;
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    Json::Value territory_data;
    inf >> territory_data;
    CRoute4Me route(KEY);

    if (route.get_all_territories() == 0) {
        cout << "Found territories:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "No territories found: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    
    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/api.v4/territory.php?api_key=...


See the sample JSON response of this method.


Remove a Territory

Deletes a specified Territory object.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Territory ID
<job id="Delete Zone">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            WScript.Echo "Please, press OK and wait..."
            
            ' The example refers to the process of removing a territory zone from a user's account.
            
            url="https://api.route4me.com/api.v4/territory.php"
            apikey="11111111111111111111111111111111"
            terid1="F31128DB9EEA076B85ECDE37274A4D78"
            
            url=url&"?api_key="&apikey
            url=url&"&territory_id="&terid1
            
            jFile=""
            
            Set r4m=New Route4Me
            
            r4m.HttpDeleteRequest url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/territory.php
SET apikey=11111111111111111111111111111111
SET terid1=8506E4725A006B59D5CA2EA375E08B97

:: The example refers to the process of removing a territory zone from a user's account.

ECHO ON

curl -o file1.txt -g -k -X DELETE "%url%?api_key=%apikey%&territory_id=%terid1%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/territory.php
apikey=11111111111111111111111111111111
terid1=083F0E34A2271FCAFA5476A364F32B4E

 # The example refers to the process of removing a territory zone from a user's account.

curl -o file1.txt -g -k -X DELETE "$url?api_key=$apikey&territory_id=$terid1"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Remove Territory
        /// </summary>
        public void RemoveTerritory()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            string territoryId = "12ABBFA3B5E4FB007BB0ED73291576C2";

            AvoidanceZoneQuery territoryQuery = new AvoidanceZoneQuery { TerritoryId = territoryId };

            // Run the query
            string errorString = "";
            route4Me.RemoveTerritory(territoryQuery, out errorString);

            Console.WriteLine("");

            if (string.IsNullOrEmpty(errorString))
            {
                Console.WriteLine("RemoveTerritory executed successfully");

                Console.WriteLine("Territory ID: {0}", territoryId);
            }
            else
            {
                Console.WriteLine("RemoveTerritory error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Remove Territory
        ''' </summary>
        Public Sub RemoveTerritory()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim territoryId As String = "12ABBFA3B5E4FB007BB0ED73291576C2"

            Dim territoryQuery As New AvoidanceZoneQuery() With { _
                .TerritoryId = territoryId _
            }

            ' Run the query
            Dim errorString As String = ""
            route4Me.RemoveTerritory(territoryQuery, errorString)

            Console.WriteLine("")

            If errorString = "" Then
                Console.WriteLine("RemoveTerritory executed successfully")

                Console.WriteLine("Territory ID: {0}", territoryId)
            Else
                Console.WriteLine("RemoveTerritory error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    territories = route4me.territory
    print 'Creating Poly Territory'
    territory = {"territory_name": "Polygon Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "poly",
                               "data": ["56.127184156131065,56.93115234375",
                                        "58.41322259056806,59.501953125",
                                        "61.53840616716746,59.315185546875",
                                        "61.047650586031104,51.998291015625",
                                        "59.254649544483726,53.63525390625",
                                        "56.47462805805596,54.42626953125"
                                        ]
                               }
                 }
    response = territories.add_territory(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        territory_id = response.territory_id
        print 'Territory ID: {0} -> Created'.format(territory_id)
        response = territories.delete_territory(territory_id=territory_id)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Territory ID: {0} -> Deleted: {1}'.format(territory_id,
                                                             response.status)

if __name__ == '__main__':
    main()
package com.route4me.sdk.examples.territories;

import com.route4me.sdk.exception.APIException;
import com.route4me.sdk.services.routing.Constants;
import com.route4me.sdk.services.territories.TerritoriesManager;
import com.route4me.sdk.services.territories.Territory;
import com.route4me.sdk.services.territories.TerritoryData;

import java.util.ArrayList;
import java.util.List;

public class DeleteTerritory {

    public static void main(String[] args) throws APIException {
        String apiKey = "11111111111111111111111111111111";
        TerritoriesManager territoriesManager = new TerritoriesManager(apiKey);
        List<String> polyTerritoryDataList = new ArrayList<>();
        polyTerritoryDataList.add("56.127184156131065,56.93115234375");
        polyTerritoryDataList.add("58.41322259056806,59.501953125");
        polyTerritoryDataList.add("61.53840616716746,59.315185546875");
        polyTerritoryDataList.add("61.047650586031104,51.998291015625");
        polyTerritoryDataList.add("59.254649544483726,53.63525390625");
        polyTerritoryDataList.add("56.47462805805596,54.42626953125");
        TerritoryData polyTerritoryData = new TerritoryData();
        polyTerritoryData.setData(polyTerritoryDataList);
        Territory polyTerritory = new Territory();
        polyTerritory.setTerritoryName("Polygon Territory");
        polyTerritory.setTerritoryColor("ff0000");
        polyTerritory.setTerritory(polyTerritoryData);
        polyTerritoryData.setType(Constants.TerritoryType.POLY.toString());
        Territory responseObject = territoriesManager.addTerritory(polyTerritory);

        System.out.println("Polygon Territory");
        System.out.println(responseObject.toString());
        System.out.println();

        System.out.println("Deleting Territory");
        boolean response = territoriesManager.deleteTerritory(responseObject.getTerritoryId());
        System.out.println(response);
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
    
    err := service.DeleteTerritory(&territories.Query{ID: "territory id"})
    if err != nil {
        //handle error
        return
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Create a territory and get territory_id
$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::CIRCLE;
$territoryParams['data'] = array(
    "37.569752822786455,-77.47833251953125",
    "5000"
);

$TerritoryParameters = Territory::fromArray(array(
    "territory_name"   => "Test Territory ".strval(rand(10000, 99999)),
    "territory_color"  => "ff7700",
    "territory"        => $territoryParams
));

$territory = new Territory();

$result = (array)$territory->addTerritory($TerritoryParameters);

assert(!is_null($result), "Can't create a territory");
assert(isset($result["territory_id"]), "Can't create a territory");

$territory_id = $result["territory_id"];

echo "New Territory with territory_id = $territory_id created successfully<br>";
echo "------------------------------------------------------------------------<br><br>";

$result1 = $territory->deleteTerritory($territory_id);
assert(isset($result), "Can't delete the territory");
echo "Territory with territory_id = $territory_id was deleted successfully<br>";

Route4Me::simplePrint($result1);
unit RemoveTerritoryUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TRemoveTerritory = class(TBaseExample)
  public
    procedure Execute(TerritoryId: String);
  end;

implementation

procedure TRemoveTerritory.Execute(TerritoryId: String);

var
  ErrorString: String;
begin
  Route4MeManager.Territory.Remove(TerritoryId, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    WriteLn('RemoveTerritory executed successfully');
    WriteLn(Format('Territory ID: %s', [TerritoryId]));
  end
  else
    WriteLn(Format('RemoveTerritory error: "%s"', [ErrorString]));
end;
end.
#include <iostream>
#include <fstream>
#include "../include/route4me.h"

#define KEY "11111111111111111111111111111111"

using namespace std;

int main()
{
    // global init
    CRoute4Me::init();

    Json::Value territory_data;
    inf >> territory_data;
    CRoute4Me route(KEY);

    if (route.remove_territory("DCBBBF90D8E9399B99C4D6FF11ED999F") == 0) {
        cout << "Remove territory:" << endl << Json::FastWriter().write(route.get_json_resp()) << endl;
    }
    else {
        cout << "Failed to remove territory: " << Json::FastWriter().write(route.get_json_resp()) << endl;
    }

    CRoute4Me::cleanup();
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
#include <stdio.h>
#include "../include/route4me.h"

static char key[] = "11111111111111111111111111111111";

int main(int argc, char* argv[])
{
    init(key, 0);
    const char id[] = "a1";

    if (!remove_territory(id))
    {
       json_object* opt_lst = getJSONResponse();
       printf("%s\n", json_object_to_json_string(opt_lst));
    }

    struct response_data response = getCurrentResponse();
    printf("Return code: %d\n Response: %s\n", response.m_err_code, response.m_raw_resp);

    cleanUp();
    return 0;
}


HTTP Request

DELETE
/api.v4/territory.php?api_key=...&territory_id=...

You can expect this API response:

{
    "status":true
}

Update a Territory

Updates a specified Territory object with a circular shape.

See the sample input JSON data for this method.


PARAMETERS

Parameter Type Description
api_key string API key of the user
territory_id string Territory ID
input data POST data A valid JSON object string. See the Territory JSON Schema as a guide.
<job id="Update Circle Zone">
    <script language="VBScript" src="../Route4Me.vbs"/>
    <script language="VBScript">
        WScript.Quit main()
        
        Function main()
            Dim r4m
            Dim jFile
            
            WScript.Echo "Please, press OK and wait..."
            
            ' The example refers to the process of updating a territory zone by sending HTTP parameters.
            
            url="https://api.route4me.com/api.v4/territory.php"
            apikey="11111111111111111111111111111111"
            terid="39236C3A30F92CA338C41EB0978F9D8A"
            
            url=url&"?api_key="&apikey
            url=url&"&territory_id="&terid
            
            jFile="update_circle_zone_data.json"
            
            Set r4m=New Route4Me
            
            r4m.HttpPutRequest url,jFile
            
            main=1
            
            WScript.Echo "Finished..."
        End Function
    </script>
</job>
@ECHO OFF

SET url=https://api.route4me.com/api.v4/territory.php
SET apikey=11111111111111111111111111111111
SET terid1=39236C3A30F92CA338C41EB0978F9D8A

ECHO ON

:: The example refers to the process of updating a territory zone by sending HTTP parameters.

curl -o file1.txt -g -k -X PUT -d "@update_circle_zone_data.json" "%url%?api_key=%apikey%&territory_id=%terid1%"

timeout /t 30
 #!/bin/bash

url=https://api.route4me.com/api.v4/territory.php
apikey=11111111111111111111111111111111
terid=39236C3A30F92CA338C41EB0978F9D8A

 # The example refers to the process of updating a territory zone by sending HTTP parameters.

curl -o file1.txt -g -k -X PUT -d "@update_circle_zone_data.json" "$url?api_key=$apikey&territory_id=$terid"

echo "Finished..."

sleep 15
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Update Territory
        /// </summary>
        public void UpdateTerritory()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            string territoryId = "1CEFEC7568D900FB781C21603780775E";

            AvoidanceZoneParameters territoryParameters = new AvoidanceZoneParameters
            {
                TerritoryId = territoryId,
                TerritoryName = "Test Territory Updated",
                TerritoryColor = "ff0000",
                Territory = new Territory
                {
                    Type = TerritoryType.Circle.Description(),
                    Data = new string[] {
                        "37.569752822786455,-77.47833251953125",
                        "6000"
                    }
                }
            };

            // Run the query
            string errorString = "";
            AvoidanceZone territory = route4Me.UpdateTerritory(territoryParameters, out errorString);

            Console.WriteLine("");

            if (territory != null)
            {
                Console.WriteLine("UpdateTerritory executed successfully");
                Console.WriteLine("Territory ID: {0}", territory.TerritoryId);
            }
            else
            {
                Console.WriteLine("UpdateTerritory error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Update Territory
        ''' </summary>
        Public Sub UpdateTerritory()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim territoryId As String = "4703BC24F64E43C45DA852ABAFB5B404"

            Dim territoryParameters As New AvoidanceZoneParameters() With { _
                .TerritoryId = territoryId, _
                .TerritoryName = "Test Territory Updated", _
                .TerritoryColor = "ff0000", _
                .Territory = New Territory() With { _
                    .Type = EnumHelper.GetEnumDescription(TerritoryType.Circle), _
                    .Data = New String() {"37.569752822786455,-77.47833251953125", "5000"} _
                } _
            }

            ' Run the query
            Dim errorString As String = ""
            Dim territory As AvoidanceZone = route4Me.UpdateTerritory(territoryParameters, errorString)

            Console.WriteLine("")

            If territory IsNot Nothing Then
                Console.WriteLine("UpdateTerritory executed successfully")

                Console.WriteLine("Territory ID: {0}", territory.TerritoryId)
            Else
                Console.WriteLine("UpdateTerritory error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    territories = route4me.territory
    print 'Creating Poly Zone'
    territory = {"territory_name": "Polygon Territory",
                 "territory_color": "ff0000",
                 "territory": {"type": "poly",
                               "data": ["56.127184156131065,56.93115234375",
                                        "58.41322259056806,59.501953125",
                                        "61.53840616716746,59.315185546875",
                                        "61.047650586031104,51.998291015625",
                                        "59.254649544483726,53.63525390625",
                                        "56.47462805805596,54.42626953125"
                                        ]
                               }
                 }
    response = territories.add_territory(**territory)
    if hasattr(response, 'errors'):
        print '. '.join(response.errors)
    else:
        territory_id = response.territory_id
        print 'Territory ID: {0} -> Created'.format(territory_id)
        print '\tTerritory Name: {}'.format(response.territory_name)
        print '\tTerritory Color: {}'.format(response.territory_color)
        print '\tMember ID: {}'.format(response.member_id)
        print '\tTerritory Type: {}'.format(response.territory.type)
        if response.territory.data:
            print '\tData: '
            for data in response.territory.data:
                print '\t\t{0}'.format(data)
        territory = {"territory_name": "Polygon Territory Updated",
                     "territory_color": "ff00ff",
                     "territory": {"type": "poly",
                                   "data": [
                                       "56.127184156131065,56.93115234375",
                                       "58.41322259056806,59.501953125",
                                       "61.53840616716746,59.315185546875",
                                       "61.047650586031104,51.998291015625",
                                       "59.254649544483726,53.63525390625",
                                       "56.47462805805596,54.42626953125",
                                   ]
                                   }
                     }
        response = territories.update_territory(territory_id=territory_id,
                                                **territory)
        if hasattr(response, 'errors'):
            print '. '.join(response.errors)
        else:
            print 'Territory ID: {}'.format(response.territory_id)
            print '\tTerritory Name: {}'.format(response.territory_name)
            print '\tTerritory Color: {}'.format(response.territory_color)
            print '\tMember ID: {}'.format(response.member_id)
            print '\tTerritory Type: {}'.format(response.territory.type)
            if response.territory.data:
                print '\tData: '
                for data in response.territory.data:
                    print '\t\t{0}'.format(data)

if __name__ == '__main__':
    main()
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
import (
    "github.com/route4me/route4me-go-sdk"
    "github.com/route4me/route4me-go-sdk/territories"
)

func main() {
    client := route4me.NewClient("your-api-key")
    service := &territories.Service{Client: client}
    
    territory := //get zone using Get, GetAll or constructing yourself.
    contact, err := service.UpdateTerritory(territory)
    if err != nil {
        t.Error(err)
        return
    }
}
<?php
namespace Route4Me;

$root = realpath(dirname(__FILE__).'/../../');
require $root.'/vendor/autoload.php';

use Route4Me\Route4Me;
use Route4Me\Enum\TerritoryTypes;

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_BAIL, 1);

// Set the API key in the Route4Me class
Route4Me::setApiKey('11111111111111111111111111111111');

// Add Avoidance Zone and get territory_id
$territory = new Territory();

$territoryParams['type'] = TerritoryTypes::CIRCLE;
$territoryParams['data'] = array(
    "37.569752822786455,-77.47833251953125",
    "5000"
);

$TerritoryParameters = Territory::fromArray(array(
    "territory_name"  => "Test Territory ".strval(rand(10000, 99999)),
    "territory_color" => "ff7700",
    "territory"       => $territoryParams
));

$result = (array)$territory->addTerritory($TerritoryParameters);
assert(!is_null($result), "Can't create a territory");

$territory_id = $result["territory_id"];

echo "New Territory with territory_id = $territory_id created successfully<br>";
echo "---------------------------------------------------------------<br><br>";

// Update territory
$territoryParameters = array (
    "type" => TerritoryTypes::RECT,
    "data" => array(
        "29.6600127358956,-95.6593322753906",
        "29.8966150753098,-95.3146362304688"
       )
   );

$TerritoryParameters = Territory::fromArray(array(
    "territory_id"     => $territory_id,
    "territory_name"   => "Test Territory Updated as rectangle",
    "territory_color"  => "ff5500",
    "territory"        => $territoryParameters
));

$result1 = $territory->updateTerritory($TerritoryParameters);
assert(isset($result1), "Can't update the territory");

Route4Me::simplePrint($result1, true);
unit UpdateTerritoryUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TUpdateTerritory = class(TBaseExample)
  public
    procedure Execute(TerritoryId: String);
  end;

implementation


uses TerritoryUnit, TerritoryContourUnit;

procedure TUpdateTerritory.Execute(TerritoryId: String);

var
  ErrorString: String;
  Territory: TTerritory;
  TerritoryContour: TTerritoryContour;
  NewTerritory: TTerritory;
  TerritoryName, TerritoryColor: String;
begin
  TerritoryName := 'Test Territory Updated';
  TerritoryColor := 'ff00ff';
  TerritoryContour := TerritoryContour.MakeCircleContour(
    38.4132225905681, -78.501953234, 3000);
  Territory := TTerritory.Create(TerritoryName, TerritoryColor, TerritoryContour);
  try
    Territory.Id := TerritoryId;

    NewTerritory := Route4MeManager.Territory.Update(Territory, ErrorString);
    try
      WriteLn('');

      if (NewTerritory <> nil) then
      begin
        WriteLn('UpdateTerritory executed successfully');
        WriteLn(Format('Territory ID: %s', [NewTerritory.Id.Value]));
      end
      else
        WriteLn(Format('UpdateTerritory error: "%s"', [ErrorString]));
    finally
      FreeAndNil(NewTerritory);
    end;
  finally
    FreeAndNil(Territory);
  end;
end;
end.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/api.v4/territory.php?api_key=...&territory_id=...

You can expect this API response:

{
    "territory_id": "39236C3A30F92CA338C41EB0978F9D8A",
    "member_id": "1",
    "territory_name": "Test Territory",
    "territory_color": "ff0000",
    "addresses": [],
    "territory": {
        "type": "circle",
        "data": ["37.569752822786455,-77.47833251953125",
        "5000"]
    }
}

Telematics Connections

A telematics connection allows you to import and synchronize your telematics vendor’s data to your account in the Operational Assessment system. It’s the system’s abstraction in using and communicating with the Telematics Gateway API. Under the hood, the system communicates with the Telematics Gateway API through this connection to retrieve your telematics vendor’s data.

Useful links:
- An online tool for choosing a telematics vendor
- Get an API key
- Telematics Articles
- Route4Me Telematics Integrations


Get Telematics Connection List

Returns a list of active connections from the Telematics Gateway.


PARAMETERS

Parameter Parameter Type Description Data Type
x-auth-token header The authorization token that will be given after signing in. string
x-api-key header Use the API with an API key without authorization. string
offset query Only records from that offset will be considered integer
api_key query Use the API with an API key without authorization. string
x-original-api-key header Authorization by Route4Me key in the HTTP request header, for Route4Me users. string
auth_token query The authorization token that will be given after signing in. string
limit query The number of records to return. integer
original_api_key query Authorization by Route4Me key, for Route4Me users. string

As a guide, see this method’s JSON schema for its: - input parameters - response

An example for this language will be added in the future. For now, please see the other languages available for reference.
ECHO OFF

:: Use your API key in the `api_key` parameter.
SET url=https://oa.route4me.com/api/v1/user/telematics-connections
SET api_key=1111111111111111111111111111111111111111111111111111111111111111
SET offset=0
SET limit=3

:: The example demonstrates the process of getting the telematics connections.

ECHO ON

curl -o User_telematics_connections_get_RESPONSE.json -H "Accept: application/json" -g -k -X GET  "%url%?api_key=%api_key%&offset=%offset%&limit=%limit%"

timeout /t 30
#!/bin/bash

# Use your API key in the `api_key` parameter.

url=https://oa.route4me.com/api/v1/user/telematics-connections

api_key=1111111111111111111111111111111111111111111111111111111111111111
offset=0
limit=100

# The example demonstrates the process of getting the telematics connections.

curl -o User_telematics_connections_get_RESPONSE.json -H "Accept: application/json" -g -k -X GET  "$url?api_key=$api_key&offset=$offset&limit=$limit"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/user/telematics-connections?offset=...&limit=...

You can expect this API response:

{
  "data": [{
    "is_active": true,
    "password": "route4me",
    "email": "[email protected]",
    "account_id": "nnnnnnnnnn",
    "telematics_connection_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    "user_id": "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
    "telematics_id": 10100,
    "created_at": 1533131149,
    "vendor_name": "TelServ",
    "vendor_id": 4,
    "host": "",
    "virtual_password": "PPPPPPPP",
    "name": "geo",
    "device_position_refresh_rate": 60,
    "virtual_email": "[email protected]",
    "updated_at": 1533131149,
    "username": "[email protected]",
    "telematics_connection_token": "ssssssssssssssssssssssssssssssss",
    "last_name": "xx1",
    "telematics_api_token": "66666666666666666666666666666666",
    "company_name": "xx2",
    "first_name": "evhen"
  },
  {
    "is_active": true,
    "email": "[email protected]",
    "name": "r4me_changed",
    "updated_at": 1533131360,
    "last_name": "tekhon",
    "api_key": "11111111111111111111111111111111",
    "telematics_connection_id": "BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    "user_id": "EDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
    "virtual_email": "[email protected]",
    "telematics_id": 10101,
    "device_position_refresh_rate": 60,
    "telematics_connection_token": "asssssssssssssssssssssssssssssss",
    "vendor_name": "Route4Me",
    "vendor_id": 9,
    "created_at": 1533130795,
    "first_name": "evora",
    "virtual_password": "ttttttttttt",
    "company_name": "simple",
    "telematics_api_token": "76666666666666666666666666666666"
  },
  {
    "is_active": true,
    "email": "[email protected]",
    "name": "r4m1",
    "updated_at": 1533112869,
    "last_name": "participant 3",
    "api_key": "11111111111111111111111111111111",
    "telematics_connection_id": "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    "user_id": "FDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
    "virtual_email": "[email protected]",
    "telematics_id": 10102,
    "device_position_refresh_rate": 60,
    "telematics_connection_token": "bsssssssssssssssssssssssssssssss",
    "vendor_name": "Route4Me",
    "vendor_id": 9,
    "created_at": 1533112817,
    "first_name": "evhen",
    "virtual_password": "5555555555",
    "company_name": "3pa3 OA",
    "telematics_api_token": "86666666666666666666666666666666"
  }],
  "metadata": {
    "limit": 3,
    "total": 70,
    "user_id": "EBEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE",
    "offset": 0
  }
}

Create Telematics Connection

Creates a telematics connection on the Telematics Gateway that’s tied to a chosen participant that doesn’t have any connections yet.

See the sample input JSON data for this method.


PARAMETERS

Parameter Parameter Type Description Data Type
participant_ user_id path Participant user ID string
original_api_key query Authorization by Route4Me key, for Route4Me users. string
x-original-api-key header Authorization by Route4Me key in the HTTP request header, for Route4Me users. string
x-auth-token header The authorization token that will be given after signing in. string
api_key query Use the API with an API key without authorization. string
auth_token query The authorization token that will be given after signing in. string
payload body JSON payload data Model
x-api-key header Use the API with an API key without authorization. string

As a guide, see this method’s JSON schema for its: - input parameters - response - payload data

An example for this language will be added in the future. For now, please see the other languages available for reference.
ECHO OFF

:: Use your API key in the `api_key` parameter.
SET url=https://oa.route4me.com/api/v1/user/participants/
SET api_key=1111111111111111111111111111111111111111111111111111111111111111
SET participant_user_id=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

:: The example demonstrates the process of creating a connection to a telematics vendor.

ECHO ON

curl -o User_participant_telematics_connection_create_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -k -X POST -d "@User_participant_telematics_connection_create_data.json" "%url%%participant_user_id%/telematics-connection?api_key=%api_key%"

timeout /t 30
#!/bin/bash

# Use your API key in the `api_key` parameter.

url=https://oa.route4me.com/api/v1/user/participants/

api_key=1111111111111111111111111111111111111111111111111111111111111111
participant_user_id=9B6D55A57AD44B57850371564C95AEE8

# The example demonstrates the process of creating a connection to a telematics vendor.

curl -o User_participant_telematics_connection_create_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -k -X POST -d "@User_participant_telematics_connection_create_data.json" "$url$participant_user_id/telematics-connection?api_key=$api_key"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

POST
/user/participants/{participant_user_id}/telematics-connection

You can expect this API response:

{
  "data": {
    "is_active": true,
    "email": null,
    "name": "Test Connection",
    "updated_at": 1533044746,
    "last_name": null,
    "api_key": "33333333333333333333333333333333",
    "telematics_connection_id": "55555555555555555555555555555555",
    "user_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    "virtual_email": "[email protected]",
    "telematics_id": 100000,
    "device_position_refresh_rate": 60,
    "telematics_connection_token": "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR",
    "vendor_name": "Route4Me",
    "vendor_id": 9,
    "created_at": 1532651489,
    "first_name": null,
    "virtual_password": "o4yCk6P8jGW",
    "company_name": null,
    "telematics_api_token": "782cf32dc5243a42723b2ef0793ed72c"
  },
  "metadata": {
    "user_id": "EBA794354DC847E3BC19AEE49CF4AB1B",
    "participant": {
      "original_r4m_api_key": "44444444444444444444444444444444",
      "email": "[email protected]",
      "vendor_company_name": "",
      "locale": null,
      "timezone": null,
      "affiliate_user_id": "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
      "affiliate_email": "",
      "user_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
      "measurement": 0,
      "affiliate_company_name": "",
      "origin_r4m_member_id": 888888,
      "vendor_user_id": "11111111111111111111111111111111",
      "vendor_id": 9,
      "phone_number": null,
      "last_name": "Doe",
      "r4m_api_key": "99999999999999999999999999999999",
      "website": null,
      "company_name": null,
      "r4m_member_id": 222222,
      "first_name": "John"
    }
  }
}

Delete Telematics Connection

Deletes a telematics connection on the Telematics Gateway. Once a connection is deleted, the Operational Assessment system stops receiving raw GPS points from the telematics control unit(s) associated with the connection.


PARAMETERS

Parameter Parameter Type Description Data Type
participant_ user_id path Participant user ID string
telematic_ connection_id path Telematics connection ID string
original_api_key query Authorization by Route4Me key, for Route4Me users. string
x-original-api-key header Authorization by Route4Me key in the HTTP request header, for Route4Me users. string
api_key query Use the API with an API key without authorization. string
auth_token query The authorization token that will be given after signing in. string
x-auth-token header The authorization token that will be given after signing in. string
x-api-key header Use the API with an API key without authorization. string

As a guide, see this method’s JSON schema for its: - input parameters - response - failure response

An example for this language will be added in the future. For now, please see the other languages available for reference.
ECHO OFF

:: Use your API key in the `api_key` parameter.
SET url=https://oa.route4me.com/api/v1/user/participants/
SET api_key=1111111111111111111111111111111111111111111111111111111111111111
SET participant_user_id=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SET telematic_connection_id=22222222222222222222222222222222

:: The example demonstrates the process of deleting a participant's connection from a telematics vendor.

ECHO ON

curl -o User_participant_telematics_connection_delete_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -k -X DELETE "%url%%participant_user_id%/telematics-connection/%telematic_connection_id%?api_key=%api_key%"

timeout /t 30
#!/bin/bash

# Use your API key in the `api_key` parameter.

url=https://oa.route4me.com/api/v1/user/participants/

api_key=1111111111111111111111111111111111111111111111111111111111111111
participant_user_id=474868258B914C35BABBF333EFD7C7EC
telematic_connection_id=89139BD0A3C343D6B1AE74D1BE612A93

# The example demonstrates the process of deleting a participant's connection from a telematics vendor.

curl -o User_participant_telematics_connection_delete_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -k -X DELETE "$url$participant_user_id/telematics-connection/$telematic_connection_id?api_key=$api_key"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

DELETE
/user/participants/{participant_user_id}/telematics-connection/{telematic_connection_id}

You can expect this API response:

{
  "data": null,
  "metadata": {
    "user_id": "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"
  }
}

Get a Telematics Connection

Returns the information about a participant’s telematics connection by setting the values of these path parameters: telematic_connection_id and participant_user_id.


PARAMETERS

Parameter Parameter Type Description Data Type
telematic_ connection_id path Telematics connection ID string
participant_ user_id path Participant user ID string
original_api_key query Authorization by Route4Me key, for Route4Me users. string
x-original-api-key header Authorization by Route4Me key in the HTTP request header, for Route4Me users. string
api_key query Use the API with an API key without authorization. string
auth_token query The authorization token that will be given after signing in. string
x-auth-token header The authorization token that will be given after signing in. string
x-api-key header Use the API with an API key without authorization. string

As a guide, see this method’s JSON schema for its: - input parameters - response

An example for this language will be added in the future. For now, please see the other languages available for reference.
ECHO OFF

:: Use your API key in the `api_key` parameter.
SET url=https://oa.route4me.com/api/v1/user/participants/
SET api_key=1111111111111111111111111111111111111111111111111111111111111111
SET participant_user_id=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SET telematic_connection_id=22222222222222222222222222222222

:: The example demonstrates the process of getting a participant's telematics connection.

ECHO ON

curl -o User_participant_telematics_connection_get_RESPONSE.json -H "Accept: application/json" -g -k -X GET  "%url%%participant_user_id%/telematics-connection/%telematic_connection_id%?api_key=%api_key%"

timeout /t 30
#!/bin/bash

# Use your API key in the `api_key` parameter.

url=https://oa.route4me.com/api/v1/user/participants/

api_key=1111111111111111111111111111111111111111111111111111111111111111
participant_user_id=A2F8FE5085EA4412BE9B7AB00665F0E1
telematic_connection_id=A25C3B365005429490B4D08345BC5DDA

# The example demonstrates the process of getting a participant's telematics connection.

curl -o User_participant_telematics_connection_get_RESPONSE.json -H "Accept: application/json" -g -k -X GET  "$url$participant_user_id/telematics-connection/$telematic_connection_id?api_key=$api_key"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
/user/participants/{participant_user_id}/telematics-connection/{telematic_connection_id}

You can expect this API response:

{
  "data": {
    "is_active": true,
    "email": null,
    "name": "Test Connection",
    "updated_at": 1533044746,
    "last_name": null,
    "api_key": "33333333333333333333333333333333",
    "telematics_connection_id": "22222222222222222222222222222222",
    "user_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    "virtual_email": "[email protected]",
    "telematics_id": 10020,
    "device_position_refresh_rate": 60,
    "telematics_connection_token": "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR",
    "vendor_name": null,
    "vendor_id": null,
    "created_at": 1532651489,
    "first_name": null,
    "virtual_password": "ooooooooooo",
    "company_name": null,
    "telematics_api_token": "77777777777777777777777777777777"
  },
  "metadata": {
    "user_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
  }
}

Update a Telematics Connection

Updates the description and refresh rate of a telematics connection.

See the sample input JSON data for this method.


PARAMETERS

Parameter Parameter Type Description Data Type
telematic_ connection_id path Telematic connection ID string
participant_ user_id path Participant user ID string
original_api_key query Authorization by Route4Me key, for Route4Me users. string
x-original-api-key header Authorization by Route4Me key in the HTTP request header, for Route4Me users. string
api_key query Use the API with an API key without authorization. string
auth_token query The authorization token that will be given after signing in. string
x-auth-token header The authorization token that will be given after signing in. string
payload body JSON payload data Model
x-api-key header Use the API with an API key without authorization. string

As a guide, see this method’s JSON schema for its: - input parameters - response - payload data

An example for this language will be added in the future. For now, please see the other languages available for reference.
ECHO OFF

:: Use your API key in the `api_key` parameter.
SET url=https://oa.route4me.com/api/v1/user/participants/
SET api_key=1111111111111111111111111111111111111111111111111111111111111111
SET participant_user_id=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SET telematic_connection_id=22222222222222222222222222222222

:: The example demonstrates the process of updating the name of a participant's telematics connection.

ECHO ON

curl -o User_participant_tc_update_name_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -k -X PUT -d "@User_participant_tc_update_name_data.json" "%url%%participant_user_id%/telematics-connection/%telematic_connection_id%?api_key=%api_key%"

timeout /t 30
#!/bin/bash

# Use your API key in the `api_key` parameter.

url=https://oa.route4me.com/api/v1/user/participants/

api_key=1111111111111111111111111111111111111111111111111111111111111111
participant_user_id=A2F8FE5085EA4412BE9B7AB00665F0E1
telematic_connection_id=A25C3B365005429490B4D08345BC5DDA

# The example demonstrates the process of updating the name of a participant's telematics connection.

curl -o User_participant_tc_update_name_RESPONSE.json -H "Content-Type: application/json" -H "Accept: application/json" -g -k -X PUT -d "@User_participant_tc_update_name_data.json" "$url$participant_user_id/telematics-connection/$telematic_connection_id?api_key=$api_key"

echo "Finished..."

sleep 15
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

PUT
/user/participants/{participant_user_id}/telematics-connection/{telematic_connection_id}

You can expect this API response:

{
  "data": {
    "is_active": true,
    "email": null,
    "name": "Renamed Test Connection",
    "updated_at": 1533124666,
    "last_name": null,
    "api_key": "33333333333333333333333333333333",
    "telematics_connection_id": "22222222222222222222222222222222",
    "user_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
    "virtual_email": "[email protected]",
    "telematics_id": 10100,
    "device_position_refresh_rate": 60,
    "telematics_connection_token": "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR",
    "vendor_name": "Route4Me",
    "vendor_id": 9,
    "created_at": 1532651489,
    "first_name": null,
    "virtual_password": "ooooooooooo",
    "company_name": null,
    "telematics_api_token": "77777777777777777777777777777777"
  },
  "metadata": {
    "user_id": "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"
  }
}