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

Authentication to the Operational Assessment API’s

The Operational Assessment (OA) API requires a unique API key for authentication. Use your OA API key provided in the OA website’s user management form, or, if your account was imported from the Route4Me website, then use your Route4Me API key.

Example:

https://oa.route4me.com/api/v1/analysis/download/report?api_key=11111111111111111111111111111111 or

https://oa.route4me.com/api/v1/analysis/download/report?original_api_key=11111111111111111111111111111111

To view or retrieve your API keys, login to your account in the Operational Assessment website and go to My Profile.


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.


Hybrid Optimization

Route4Me’s Hybrid Optimization feature allows you to plan routes by merging recurrent customer visits from the scheduled address book contacts and with scheduled orders. It’s mainly divided into 3 steps:

  1. Get Hybrid Optimization;
  2. Add depots to the Hybrid Optimization;
  3. Re-optimize the Hybrid Optimization.

1. Get Hybrid Optimization

This step searches for the scheduled address book locations and orders and generates the Hybrid Optimization, without the routes at this stage.

Parameter Type Description
api_key string API key of the user
target_date_string string The specified date the Hybrid Optimization is targeted to.
timezone_offset_minutes integer Local timezone


HTTP Request

GET
/api.v4/hybrid_date_optimization.php?api_key=..&target_date_string=..&timezone_offset_minutes=..



See the sample JSON response of this method.

2. Add the depots to the Hybrid Optimization

This step adds selected depots to the generated Hybrid Optimization.

Parameter Type Description
api_key string API key of the user
optimization_problem_id string Optimization problem ID
delete_old_depots boolean If true, the old depots in the Hybrid Optimization will be deleted.
new_depots array An array of address objects.

See the sample input JSON data for this method.


HTTP Request

POST
/api/change_hybrid_optimization_depot.php?api_key=..&optimization_problem_id=...



See the sample JSON response of this method.

3. Re-optimize the Hybrid Optimization

This step re-optimizes the Hybrid Optimization with added depots.

Parameter Type Description
api_key string API key of the user
optimization_problem_id string Optimization problem ID
reoptimize integer If equal to 1, the optimization will be re-optimized.


HTTP Request

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



See the sample JSON response of 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 apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates the process of creating a Hybrid Optimization using scheduled addresses and orders.
:: Useful links:
:: http://support.route4me.com/route-planning-help.php?id=manual11:tutorial2:chapter7
:: http://support.route4me.com/route-planning-help.php?id=manual11:tutorial3:chapter12

:: ===== Get Hybrid Optimization ======================================================
SET url=https://api.route4me.com/api.v4/hybrid_date_optimization.php

SET "scheduled_data=2017-12-20"
SET tz_minutes=480
SET "houtput=output/get_hybrid_route_20_12_17_RESPONSE.json"

START /WAIT curl -o %houtput% -g -k -X GET "%url%?api_key=%apikey%&target_date_string=%scheduled_data%&timezone_offset_minutes=%tz_minutes%"

timeout /t 30
:: ====================================================================================

:: ===== Reoptimization ======================================================

:: jq-win64 is a JSON parser for batch scripts.  Manual: https://stedolan.github.io/jq/manual/

::type "%houtput%" | jq-win64 ".optimization_problem_id" >"input/optimization_problem_id.txt"
type "%cd%\output\get_hybrid_route_20_12_17_RESPONSE.json" | jq-win64 ".optimization_problem_id" > "%cd%\input\optimization_problem_id.txt"

set /p opt_id=<"input/optimization_problem_id.txt"

echo %opt_id%

:: ==== Define Hybrid Optimization Depots ===========================
SET url=https://api.route4me.com/api/change_hybrid_optimization_depot.php
SET "hinput1=input\depots.json"
SET "hinput2=input\depots2.json"

type "%hinput1%" | jq-win64 ".optimization_problem_id = \"%opt_id%\" " > "%hinput2%"

START /WAIT curl -o "output/depots_RESPONSE.json" -g -X POST -k -d "@%hinput2%" %url%?api_key=%apikey%&optimization_problem_id=%opt_id%"

::===================================================================

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

START /WAIT curl -o "output/reoptimization_RESPONSE.json" -g -X PUT -k "%url%?api_key=%apikey%&optimization_problem_id=%opt_id%&reoptimize=1"

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 HybridOptimizationFrom1000Addresses()
{
  #region ======= Get Hybrid Optimization ================================

  TimeSpan tsp1day = new TimeSpan(1, 0, 0, 0);
  List<string> lsScheduledDays = new List<string>();
  DateTime curDate = DateTime.Now;
  for (int i = 0; i < 5; i++)
  {
    curDate += tsp1day;
    lsScheduledDays.Add(curDate.ToString("yyyy-MM-dd"));
  }

  Address[] Depots = new Address[] {
    new Address {
        AddressString = "2017 Ambler Ave, Abilene, TX, 79603-2239",
        IsDepot = true,
        Latitude = 32.474395,
        Longitude = -99.7447021,
        CurbsideLatitude = 32.474395,
        CurbsideLongitude = -99.7447021
      },
    new Address {
        AddressString = "807 Ridge Rd, Alamo, TX, 78516-9596",
        IsDepot = true,
        Latitude = 26.170834,
        Longitude = -98.116201,
        CurbsideLatitude = 26.170834,
        CurbsideLongitude = -98.116201
      },
    new Address {
        AddressString = "1430 W Amarillo Blvd, Amarillo, TX, 79107-5505",
        IsDepot = true,
        Latitude = 35.221969,
        Longitude = -101.835288,
        CurbsideLatitude = 35.221969,
        CurbsideLongitude = -101.835288
      },
    new Address {
        AddressString = "3611 Ne 24Th Ave, Amarillo, TX, 79107-7242",
        IsDepot = true,
        Latitude = 35.236626,
        Longitude = -101.795117,
        CurbsideLatitude = 35.236626,
        CurbsideLongitude = -101.795117
      },
    new Address {
        AddressString = "1525 New York Ave, Arlington, TX, 76010-4723",
        IsDepot = true,
        Latitude = 32.720524,
        Longitude = -97.080195,
        CurbsideLatitude = 32.720524,
        CurbsideLongitude = -97.080195
      }
  };

  string errorString1;
  string errorString2;
  string errorString3;

  foreach (string ScheduledDay in lsScheduledDays)
  {
    HybridOptimizationParameters hparams = new HybridOptimizationParameters()
    {
      target_date_string = ScheduledDay,
      timezone_offset_minutes = 480
    };

    DataObject resultOptimization = route4Me.GetHybridOptimization(hparams, out errorString1);

    string HybridOptimizationId = "";

    if (resultOptimization != null)
    {
      HybridOptimizationId = resultOptimization.OptimizationProblemId;
      Console.WriteLine("Hybrid optimization generating executed successfully");

      Console.WriteLine("Generated hybrid optimization ID: {0}", HybridOptimizationId);
    }
    else
    {
      Console.WriteLine("Hybrid optimization generating error: {0}", errorString1);
      continue;
    }

    //============== Add Depot To Hybrid Optimization ===============
    HybridDepotParameters hDepotParams = new HybridDepotParameters()
    {
      optimization_problem_id = HybridOptimizationId,
      delete_old_depots = true,
      new_depots = new Address[] { Depots[lsScheduledDays.IndexOf(ScheduledDay)] }
    };

    var addDepotResult = route4Me.AddDepotsToHybridOptimization(hDepotParams, out errorString3);

    Thread.Sleep(5000);

    //============== Reoptimization =================================
    OptimizationParameters optimizationParameters = new OptimizationParameters()
    {
      OptimizationProblemID = HybridOptimizationId,
      ReOptimize = true
    };

    DataObject finalOptimization = route4Me.UpdateOptimization(optimizationParameters, out errorString2);

    if (finalOptimization != null) lsOptimizationIDs.Add(finalOptimization.OptimizationProblemId);


    Thread.Sleep(5000);
    //=================================================================
  }

  bool removeOrders = tdr.RemoveOrders(lsOrders, ApiKey);

  #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\OptimizationProblem;
use Route4Me\Route4Me;

/* The example demonstrates the process of creating a Hybrid Optimization using scheduled addresses and orders.

 * Useful links:
 * http://support.route4me.com/route-planning-help.php?id=manual11:tutorial2:chapter7
 * http://support.route4me.com/route-planning-help.php?id=manual11:tutorial3:chapter12
*/ 

// Please use your API key for this example and not this demo key.
Route4Me::setApiKey('11111111111111111111111111111111');

$source_file = "addresses_1000.csv";
$max_line_length = 512;
$delimiter = ',';

ini_set('max_execution_time', 180);

/* Add Address Book Locations with schedules from a CSV file */

/* Mapping of a CSV file with address book locations, of which the columns in the CSV file corresponds to the Address Book object's fields/properties. */

$locationsFieldsMapping['cached_lat'] = 0;
$locationsFieldsMapping['cached_lng'] = 1;
$locationsFieldsMapping['address_alias'] = 2;
$locationsFieldsMapping['address_1'] = 3;
$locationsFieldsMapping['address_city'] = 4;
$locationsFieldsMapping['address_state_id'] = 5;
$locationsFieldsMapping['address_zip'] = 6;
$locationsFieldsMapping['address_phone_number'] = 7;
$locationsFieldsMapping['schedule_mode'] = 8;
$locationsFieldsMapping['schedule_enabled'] = 9;
$locationsFieldsMapping['schedule_every'] = 10;
$locationsFieldsMapping['schedule_weekdays'] = 11;
$locationsFieldsMapping['monthly_mode'] = 12;
$locationsFieldsMapping['monthly_dates'] = 13;
$locationsFieldsMapping['monthly_nth_n'] = 16;
$locationsFieldsMapping['monthly_nth_what'] = 17;

if (($handle = fopen("$source_file", "r"))!==FALSE) {
    $oAbook = new AddressBookLocation();

    $results = $oAbook->addLocationsFromCsvFile($handle, $locationsFieldsMapping);
    
    echo "Errors: <br><br>";
    
    foreach ($results['fail'] as $evalue) {
        echo $evalue."<br>";
    }
    
    echo "Successes: <br><br>";
    
    foreach ($results['success'] as $svalue) {
        echo $svalue."<br>";
    }
}

/* Add orders with schedules from a CSV file */

$orders_file = "orders_baton.csv";

/* Mapping of a CSV file with orders, of which the columns in the CSV file corresponds to the Order object's fields/properties. */

$ordersFieldsMapping['cached_lat'] = 1;
$ordersFieldsMapping['cached_lng'] = 0;
$ordersFieldsMapping['address_alias'] = 2;
$ordersFieldsMapping['address_1'] = 3;
$ordersFieldsMapping['order_city'] = 4;
$ordersFieldsMapping['order_state_id'] = 5;
$ordersFieldsMapping['order_zip_code'] = 6;
$ordersFieldsMapping['EXT_FIELD_phone'] = 7;
$ordersFieldsMapping['day_scheduled_for_YYMMDD'] = 8;

if (($handle = fopen("$orders_file", "r"))!==FALSE) {
    $order = new Order();
    $results = $order->addOrdersFromCsvFile($handle, $ordersFieldsMapping);

    echo "Errors: <br><br>";

    foreach ($results['fail'] as $evalue) {
        echo $evalue."<br>";
    }

    echo "Successes: <br><br>";

    foreach ($results['success'] as $svalue) {
        echo $svalue."<br>";
    }
}

/* Get Hybrid Optimization */

$ep = time()+604800;
$sched_date = date("Y-m-d", $ep);

$hybridParams = array(
    "target_date_string" => $sched_date,
    "timezone_offset_minutes" => 480
);

$optimization = new OptimizationProblem(); 
$hybridOptimization = $optimization->getHybridOptimization($hybridParams);

if ($hybridOptimization!=null) {
    if (isset($hybridOptimization['optimization_problem_id'])) {
        $optid = $hybridOptimization['optimization_problem_id'];
        
        echo "Hybrid optimization with optimization_problem_id = $optid <br><br>";

        /* Add depots to the Hybrid Optimization */
        $depotfile = "depots.csv";

        if (($handle = fopen("$depotfile", "r"))!==FALSE) {
            $columns = fgetcsv($handle, $max_line_length, $delimiter);
            
            if (empty($columns)) {
                $error['message'] = 'Empty';
                return ($error);
            }
            
            $depotsParams = array(
                'optimization_problem_id' => $optid,
                'delete_old_depots'       => true,
            );
            
            $iRow = 1;
            $depotAddresses = array();
            
            while (($rows = fgetcsv($handle, $max_line_length, $delimiter))!==false) {
                if ($rows[0] && $rows[1] && $rows[3] && array(null)!==$rows) {
                    $depotAddress['lat'] = $rows[0];
                    $depotAddress['lng'] = $rows[1];
                    $depotAddress['address'] = $rows[3];   
                    array_push($depotAddresses, $depotAddress);
                }
            }
            
            $depotsParams['new_depots'] = $depotAddresses;
            
            $optProblem = new OptimizationProblem();
            
            $resultDepots = $optProblem->addDepotsToHybrid($depotsParams);
            
            /* Reoptimize the Hybrid Optimization */
            
            if ($resultDepots!=null) {
                $problemParams = array(
                    'optimization_problem_id'  =>  $optid
                );
                $problem = OptimizationProblem::reoptimize($problemParams);
                
                Route4Me::simplePrint($problem);
            }
        }
    }
}
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages 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 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_id=...

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
<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.Route;
import com.route4me.sdk.services.routing.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

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);
        } 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

a) 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.


b) Resequence all destinations

Resequence all destinations of a route.


PARAMETERS

Parameter Type Description
api_key string API key of the user
route_id string Route ID
disable_optimization integer If equal to 1, the optimization is disabled. Otherwise, use 0.
optimize string Optimization type
<job id="Resequence Route All">
  <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 resequencing all addresses inside a route.
      
      url="https://api.route4me.com/api.v3/route/reoptimize_2.php"
      apikey="11111111111111111111111111111111"
      routeid="5C15E83A4BE005BCD1537955D28D51D7"
      
      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&disable_optimization=0"
      url=url&"&optimize=Distance"
      
      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.v3/route/reoptimize_2.php
SET apikey=11111111111111111111111111111111
SET routeid=CA902292134DBC134EAF8363426BD247

:: The example demonstrates the process of resequencing all addresses inside a route.

ECHO ON

curl -o file1.txt -g -k -X GET "%url%?api_key=%apikey%&route_id=%routeid%&disable_optimization=0&optimize=Distance;"

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/api.v3/route/reoptimize_2.php
apikey=11111111111111111111111111111111
routeid=5C15E83A4BE005BCD1537955D28D51D7
disopt=0
optimize=Distance

# The example demonstrates the process of resequencing all addresses inside a route.

curl -o file1.txt -g -X GET "$url?api_key=$apikey&route_id=$routeid&disable_optimization=$disopt&optimize=$optimize"

echo "Finished..."

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

namespace Route4MeSDK.Examples
{
    /// <summary>
    /// Resequence/Reoptimize All Route Destinations
    /// </summary>
    public sealed partial class Route4MeExamples
    {
        public void ResequenceReoptimizeRoute(string routeId)
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            Dictionary<string, string> roParameters = new Dictionary<string, string>()
            {
                {"route_id","CA902292134DBC134EAF8363426BD247"},
                {"disable_optimization","0"},
                {"optimize","Distance"},
            };

            // Run the query
            string errorString;
            bool result = route4Me.ResequenceReoptimizeRoute(roParameters, out errorString);

            Console.WriteLine("");

            if (result)
            {
                Console.WriteLine("ResequenceReoptimizeRoute executed successfully");
            }
            else
            {
                Console.WriteLine("ResequenceReoptimizeRoute error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Resequence & Reoptimize a Route
        ''' </summary>
        Public Sub ResequenceReoptimizeRoute(routeId As String)
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)

            Dim roParameters As New Dictionary(Of String, String)
            With roParameters
                .Add("route_id", "CA902292134DBC134EAF8363426BD247")
                .Add("disable_optimization", "0")
                .Add("optimize", "Distance")
            End With

            ' Run the query
            Dim errorString As String = ""
            Dim result As Boolean = route4Me.ResequenceReoptimizeRoute(roParameters, errorString)

            Console.WriteLine("")

            If result Then
                Console.WriteLine("ResequenceReoptimizeRoute executed successfully")
            Else
                Console.WriteLine("ResequenceReoptimizeRoute 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 = {"disable_optimization": 0,
                    "optimize": 'Distance',
                    "route_id": response.route_id,
                    }
            response = route.resequence_route_all(**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}
    success, err := service.ResequenceRoute(`route-id`)
    if err != nil {
        // handle error
    }
    if !success {
        // something went wrong
        return
    }
    // all okay!
}
<?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");

// Resequence all addresses
$params = array(
    "route_id"              => $route_id,
    "disable_optimization"  => 0,
    "optimize"              => "Distance"
);

$resequence = $route->resequenceAllAddresses($params);

Route4me::simplePrint($resequence);
unit ResequenceAllRouteDestinationsUnit;

interface

uses SysUtils, BaseOptimizationExampleUnit, DataObjectUnit;

type
  TResequenceAllRouteDestinations = class(TBaseOptimizationExample)
  public
    procedure Execute(RouteId: String);
  end;

implementation

uses EnumsUnit;

procedure TResequenceAllRouteDestinations.Execute(RouteId: String);
var
  DisableOptimization: boolean;
  Optimize: TOptimize;
  ErrorString: String;
begin
  DisableOptimization := False;
  Optimize := TOptimize.Distance;

  Route4MeManager.Route.ResequenceAll(
    RouteId, DisableOptimization, Optimize, ErrorString);

  WriteLn('');

  if (ErrorString = EmptyStr) then
  begin
    WriteLn('ResequenceAllRouteDestinations executed successfully');
    WriteLn('');
  end
  else
    WriteLn(Format('ResequenceAllRouteDestinations 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

GET
/api.v3/route/reoptimize_2.php?api_key=...&route_id=...&disable_optimization=...&optimize=...

You can expect this API response:

{
  "status":true
}

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.RoutesRequest;
import com.route4me.sdk.services.routing.RoutingManager;

import java.util.List;

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(10));
            if (routes.size() < 2) {
                throw new RuntimeException("Not enough routes");
            }
            List<Route> 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 endpoint /actions/duplicate_route.php accepts a unique route_id which exists in the Route4Me database and duplicates the 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
route_id string Route ID
to string Redirect to page or return JSON for none.
<job id="Duplicate Route">
  <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 duplicating an existing route.

      url="https://api.route4me.com/actions/duplicate_route.php"
      apikey="11111111111111111111111111111111"
      routeid="C963990B11B6E3BB0648C0195E683EF0"

      url=url&"?api_key="&apikey
      url=url&"&route_id="&routeid
      url=url&"&to=none"

      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 string DuplicateRoute(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;
      string duplicatedRouteId = route4Me.DuplicateRoute(routeParameters, out errorString);

      Console.WriteLine("");

      if (duplicatedRouteId != null)
      {
        Console.WriteLine("DuplicateRoute executed successfully, duplicated route ID: {0}", duplicatedRouteId);
        Console.WriteLine("");
      }
      else
      {
        Console.WriteLine("DuplicateRoute error {0}", errorString);
      }

      return duplicatedRouteId;
    }
  }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes
Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        Public Function DuplicateRoute(routeId As String) 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 duplicatedRouteId As String = route4Me.DuplicateRoute(routeParameters, errorString)

            Console.WriteLine("")

            If duplicatedRouteId IsNot Nothing Then
                Console.WriteLine("DuplicateRoute executed successfully, duplicated route ID: {0}", duplicatedRouteId)
                Console.WriteLine("")
            Else
                Console.WriteLine("DuplicateRoute error {0}", errorString)
            End If

            Return duplicatedRouteId
        End Function
    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.duplicate_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)
            print 'Addresses'
            for i, address in enumerate(response.addresses):
                print '\t{0} - {1}'.format(i, 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;

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';

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 random route ID
$randomRouteID = $route->getRandomRouteId(0, 25);
assert(!is_null($randomRouteID), "Can't retrieve a random route ID");

// Duplicate the selected route
$routeDuplicate = $route->duplicateRoute($randomRouteID);

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/actions/duplicate_route.php
SET apikey=11111111111111111111111111111111
SET routeid=C963990B11B6E3BB0648C0195E683EF0

:: The example demonstrates the process of duplicating an existing route.

ECHO ON
curl -o file1.txt -g -k "%url%?api_key=%apikey%&route_id=%routeid%&to=none" 

timeout /t 30
#!/bin/bash

url=https://api.route4me.com/actions/duplicate_route.php
apikey=11111111111111111111111111111111
routeid=C963990B11B6E3BB0648C0195E683EF0
to=none

# The example demonstrates the process of duplicating an existing route.

curl -o file1.txt -g -k "$url?api_key=$apikey&route_id=$routeid&to=$to"

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

GET
/actions/duplicate_route.php?api_key=...&route_id=...&to=...

You can expect this API response:

{
  "optimization_problem_id":"672998C4269918AFF461E5A691BAB8D0",
  "success":true
}

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.
An example for this language will be added in the future. For now, please see the other languages available for reference.
An example for this language will be added in the future. For now, please see the other languages 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.


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 Field

Update 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="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 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.php"
			apikey="11111111111111111111111111111111"
			
			url=url&"?api_key="&apikey
			
			jFile="update_order_with_custom_field_data.json"
			
			Set r4m=New Route4Me
			
			r4m.outputFile="update_order_with_custom_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.php
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example demonstrates process of updating an order with a custom user field by sending HTPP PUT data.

curl -o update_order_with_custom_field_RESPONSE.json -g -k -X PUT -H "Content-Type: application/json" -d "@update_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 updating an order with a custom user field by sending HTPP PUT data.

curl -o update_order_with_custom_field_RESPONSE.json -k -g -X PUT -H "Content-Type: application/json" -d "@update_order_with_custom_field_data.json" "$url?api_key=$apikey"

echo "Finished..."

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

	var order = lsOrders[lsOrders.Count - 1];

	order.CustomUserFields = new OrderCustomField[]
	{
		new OrderCustomField()
		{
			OrderCustomFieldId = 93,
			OrderCustomFieldValue = "true"
		}
	};

	var result = route4Me.UpdateOrder(order, out string errorString);

	Assert.IsNotNull(result, "AddOrdersToRouteTest failed... " + errorString);
}
Public Sub UpdateOrderWithCustomFieldTest()
	Dim route4Me = New Route4MeManager(c_ApiKey)
	
	Dim order = lsOrders(lsOrders.Count - 1)

	order.custom_user_fields = New OrderCustomField() {New OrderCustomField() With {
	    .OrderCustomFieldId = 93,
	     .OrderCustomFieldValue = "true"
    }}
	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';

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

// The example demonstrates process of updating an order with a custom user field by sending HTPP PUT data.
// Set the api key in the Route4me class

Route4Me::setApiKey('11111111111111111111111111111111');
$orderParameters = Order::fromArray([
    'order_id'  => 65936,
    'custom_user_fields' => [
        OrderCustomField::fromArray([
            'order_custom_field_id'    => 93,
            'order_custom_field_value' => 'true'
        ])
    ]
]);

$order = new Order();
$response = $order->updateOrder($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:

{

}

***************

### Remove an Order

Removes one or more orders from a Route4Me account.

See the <a target="_blank" href="https://github.com/route4me/route4me-curl/blob/master/Windows/Orders/delete_order_data.json">sample input JSON data</a> 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|


~~~tcl
@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"
}]
}

a) Single Address

Single address geocoding refers to the process of getting a geographic address using the address name sent through HTTP GET data.

Pass the street sequential number in the pk path parameter of the endpoint.


PARAMETERS

Parameter Type Description
api_key string API key of the user
pk integer Sequential number in addresses list
<job id="GetStreetAddressSingle">
    <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://rapid.route4me.com/street_data"
            apikey="11111111111111111111111111111111"
            pk="4"
            
            url=url&"/"&pk&"/"
            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://rapid.route4me.com/street_data
SET apikey=11111111111111111111111111111111
SET pk=4

ECHO ON

:: The example refers to the process of getting single street data.
:: Parameter pk is the street sequential number in all streets list.

curl -o file1.txt -g -X GET -k "%URL%/%pk%/?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://rapid.route4me.com/street_data
apikey=11111111111111111111111111111111
pk=4

 # The example refers to the process of getting single street data.
 # Parameter pk is the street sequential number in all streets list.

curl -o file1.txt -g -X GET -k "$url/$pk/?api_key=$apikey"

echo "Finished..."

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

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Rapid Street Data Single
        /// </summary>
        public void RapidStreetDataSingle()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            GeocodingParameters geoParams = new GeocodingParameters()
            {
                Pk =4
            };
            // Run the query
            string errorString = "";
            ArrayList result = route4Me.RapidStreetData(geoParams, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("RapidStreetDataSingle executed successfully");
                foreach (Dictionary<string, string> res1 in result)
                {

                    Console.WriteLine("ZIP Code: " + res1["zipcode"]);
                    Console.WriteLine("Street name: " + res1["street_name"]);
                    Console.WriteLine("---------------------------");
                }
            }
            else
            {
                Console.WriteLine("RapidStreetDataSingle error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Rapid Street Data Single
        ''' </summary>
        Public Sub RapidStreetDataSingle()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)
            Dim geoParams As New GeocodingParameters With { _
                 .Pk = 4
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As ArrayList = route4Me.RapidStreetData(geoParams, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("RapidStreetDataSingle executed successfully")
                For Each res1 In result
                    Console.WriteLine("ZIP Code: " & res1("zipcode"))
                    Console.WriteLine("Street name: " & res1("street_name"))
                    Console.WriteLine("---------------------------")
                Next
            Else
                Console.WriteLine("RapidStreetDataSingle error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    rapid_address = route4me.rapid_address
    response = rapid_address.get_street_data(pk=33)
    print 'Street Name:\t{0}\t\tZIP Code:\t{1}'.format(
        response.get('street_name'),
        response.get('zipcode'))

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() {
    rapidService := geocoding.NewRapidService("your-api-key")
    addr, err := rapidService.GetSingleAddress(1)
    if err != nil {
        //handle error
    }
    //do something with an address
}
<?php
namespace Route4Me;

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

use Route4Me\Route4Me;
use Route4Me\Geocoding;

// The example refers to getting a single geocoding using a sequential number.

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

$gcParameters = (array)Geocoding::fromArray(array(
    "pk" => 4
));

$geocoding = new Geocoding();

$response = $geocoding->getStreetData($gcParameters);

Route4Me::simplePrint($response);
unit GetSingleGeocodingAddressUnit;

interface

uses SysUtils, BaseExampleUnit, DirectionPathPointUnit;

type
  TGetSingleGeocodingAddress = class(TBaseExample)
  public
    procedure Execute(Pk: integer);
  end;

implementation
uses GeocodingAddressUnit;
procedure TGetSingleGeocodingAddress.Execute(Pk: integer);
var
  ErrorString: String;
  Address: TGeocodingAddress;
begin
  Address := Route4MeManager.Geocoding.GetSingleAddress(Pk, ErrorString);
  try
    WriteLn('');

    if (Address <> nil) then
    begin
      WriteLn('GetSingleGeocodingAddress executed successfully');
      WriteLn(Format('StreetName: %s, Zip: %s',
        [Address.StreetName.Value, Address.ZipCode.Value]));
    end
    else
      WriteLn(Format('GetSingleGeocodingAddress error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Address);
  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);

    int seqno = 1;

    if(route.get_street_address(seqno) == 0)
    {
        cout << "Address:" << 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);
    int seqno = 1;
    if (!get_street_address(seqno))
    {
       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;
}


GET
https://rapid.route4me.com/street_data/pk/?api_key=...

You can expect this API response:

{
    "zipcode": "00601",
    "street_name": "GENERAL DELIVERY"
}

b) Get Addresses

This example refers to the process of getting all addresses.


PARAMETERS

Parameter Type Description
api_key string API key of the user
<job id="GetStreetAddressesAll">
    <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://rapid.route4me.com/street_data/"
            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://rapid.route4me.com/street_data/
SET apikey=11111111111111111111111111111111

ECHO ON

:: The example refers to the process of getting all street data.

curl -o file1.txt -g -X GET -k "%URL%?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://rapid.route4me.com/street_data/
apikey=11111111111111111111111111111111

 # The example refers to the process of getting all street data.

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

echo "Finished..."

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

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Rapid Street Data All
        /// </summary>
        public void RapidStreetDataAll()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            GeocodingParameters geoParams = new GeocodingParameters();
            // Run the query
            string errorString = "";
            ArrayList result = route4Me.RapidStreetData(geoParams, out errorString);

            Console.WriteLine("");

            if (result != null) {
                Console.WriteLine("RapidStreetDataAll executed successfully");
                foreach (Dictionary<string, string> res1 in result)
                {

                    Console.WriteLine("ZIP Code: " + res1["zipcode"]);
                    Console.WriteLine("Street name: " + res1["street_name"]);
                    Console.WriteLine("---------------------------");
                }
            } else {
                Console.WriteLine("RapidStreetDataAll error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Rapid Street Data All
        ''' </summary>
        Public Sub RapidStreetDataAll()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)
            Dim geoParams As New GeocodingParameters
            ' Run the query
            Dim errorString As String = ""
            Dim result As ArrayList = route4Me.RapidStreetData(geoParams, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("RapidStreetDataAll executed successfully")
                For Each res1 In result
                    Console.WriteLine("ZIP Code: " & res1("zipcode"))
                    Console.WriteLine("Street name: " & res1("street_name"))
                    Console.WriteLine("---------------------------")
                Next
            Else
                Console.WriteLine("RapidStreetDataAll error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    rapid_address = route4me.rapid_address
    response = rapid_address.get_street_data()
    for street in response:
        print 'Street Name:\t{0}\t\tZIP Code:\t{1}'.format(
            street.get('street_name'),
            street.get('zipcode'))

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() {
    rapidService := geocoding.NewRapidService("your-api-key")
    addrs, err := rapidService.GetAddresses()
    if err != nil {
        //handle error
    }
    //do something with an array of addresses
}
<?php
namespace Route4Me;

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

use Route4Me\Route4Me;
use Route4Me\Geocoding;

// The example refers to getting all geocodings.

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

$gcParameters = array();

$geocoding = new Geocoding();

$response = $geocoding->getStreetData($gcParameters);

foreach ($response as $gcode) {
    Route4Me::simplePrint($gcode);
    echo "<br>";
}
unit GetGeocodingAddressesUnit;

interface

uses SysUtils, BaseExampleUnit, DirectionPathPointUnit;

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

implementation
uses GeocodingAddressUnit;
procedure TGetGeocodingAddresses.Execute;
var
  ErrorString: String;
  Addresses: TGeocodingAddressList;
begin
  Addresses := Route4MeManager.Geocoding.GetAddresses(ErrorString);
  try
    WriteLn('');

    if (Addresses <> nil) then
    begin
      WriteLn('GetGeocodingAddresses executed successfully');
      WriteLn(Format('Address count: %d', [Addresses.Count]));
    end
    else
      WriteLn(Format('GetGeocodingAddresses error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Addresses);
  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_all_streets() == 0)
    {
        cout << "Address:" << 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);

    struct Limit limit = {5 , 10};
    if (!get_all_streets(&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
https://rapid.route4me.com/street_data/?api_key=...


See the sample JSON response of this method.


c) Get Limited Addresses

This example refers to the process of getting a limited number of addresses. You can customize and limit the number of records returned using the offset and limit parameters respectively.


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="GetStreetAddressesLimit">
  <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 a limited number of street data.
        ' Please take note that this endpoint doesn't work at offset=0.

        url="https://rapid.route4me.com/street_data"
        apikey="11111111111111111111111111111111"
        offset="5"
        limit="10"
        
        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>
@ECHO OFF

SET url=https://rapid.route4me.com/street_data
SET apikey=11111111111111111111111111111111
SET offset=5
SET limit=10

ECHO ON

:: The example refers to the process of getting a limited number of street data.
:: Please take note that this endpoint doesn't work at offset=0.

curl -o file1.txt -g -X GET -k "%url%/%offset%/%limit%/?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://rapid.route4me.com/street_data
apikey=11111111111111111111111111111111
offset=5
limit=10

# The example refers to the process of getting a limited number of street data.
# Please take note that this endpoint doesn't work at offset=0.

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

echo "Finished..."

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

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Rapid Street Data Limited
        /// </summary>
        public void RapidStreetDataLimited()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            GeocodingParameters geoParams = new GeocodingParameters()
            {
                Offset = 10,
                Limit = 10
            };
            // Run the query
            string errorString = "";
            ArrayList result = route4Me.RapidStreetData(geoParams, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("RapidStreetDataLimited executed successfully");
                foreach (Dictionary<string, string> res1 in result)
                {

                    Console.WriteLine("ZIP Code: " + res1["zipcode"]);
                    Console.WriteLine("Street name: " + res1["street_name"]);
                    Console.WriteLine("---------------------------");
                }
            }
            else
            {
                Console.WriteLine("RapidStreetDataLimited error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Rapid Street Data Limited
        ''' </summary>
        Public Sub RapidStreetDataLimited()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)
            Dim geoParams As New GeocodingParameters With { _
                 .Offset = 1, _
                .Limit = 10 _
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As ArrayList = route4Me.RapidStreetData(geoParams, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("RapidStreetDataLimited executed successfully")
                For Each res1 In result
                    Console.WriteLine("ZIP Code: " & res1("zipcode"))
                    Console.WriteLine("Street name: " & res1("street_name"))
                    Console.WriteLine("---------------------------")
                Next
            Else
                Console.WriteLine("RapidStreetDataLimited error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    rapid_address = route4me.rapid_address
    response = rapid_address.get_street_data(offset=10, limit=10)
    for street in response:
        print 'Street Name:\t{0}\t\tZIP Code:\t{1}'.format(
            street.get('street_name'),
            street.get('zipcode'))

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() {
    rapidService := geocoding.NewRapidService("your-api-key")
    //                                             limit, offset
    addrs, err := rapidService.GetLimitedAddresses(10,    5)
    if err != nil {
        //handle error
    }
    //do something with an array of addresses
}
<?php
namespace Route4Me;

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

use Route4Me\Route4Me;
use Route4Me\Geocoding;

// The example refers to getting a limited number of geocodings.

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

$gcParameters = (array)Geocoding::fromArray(array(
    "offset" => 0,
    "limit"  => 5
));

$geocoding = new Geocoding();

$response = $geocoding->getStreetData($gcParameters);

foreach ($response as $gcode) {
    Route4Me::simplePrint($gcode);
    echo "<br>";
}
unit GetLimitedGeocodingAddressesUnit;

interface

uses SysUtils, BaseExampleUnit, DirectionPathPointUnit;

type
  TGetLimitedGeocodingAddresses = class(TBaseExample)
  public
    procedure Execute(Limit, Offset: integer);
  end;

implementation
uses GeocodingAddressUnit;
procedure TGetLimitedGeocodingAddresses.Execute(Limit, Offset: integer);
var
  ErrorString: String;
  Addresses: TGeocodingAddressList;
begin
  Addresses := Route4MeManager.Geocoding.GetAddresses(
    Limit, Offset, ErrorString);
  try
    WriteLn('');

    if (Addresses <> nil) then
    begin
      WriteLn('GetLimitedGeocodingAddresses executed successfully');
      WriteLn(Format('Address count: %d', [Addresses.Count]));
    end
    else
      WriteLn(Format('GetLimitedGeocodingAddresses error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Addresses);
  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);

    int limit = 5, offset = 10;

    if(route.get_all_streets(limit, offset) == 0)
    {
        cout << "Address:" << 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.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
https://rapid.route4me.com/street_data/offset/limit/?api_key=...

You can expect this API response:

[{
    "street_name": "PO BOX",
    "zipcode": "00601"
},
{
    "street_name": "PO BOX",
    "zipcode": "00601"
},
{
    "street_name": "PO BOX",
    "zipcode": "00601"
},
{
    "street_name": "PO BOX",
    "zipcode": "00601"
},
{
    "street_name": "PO BOX",
    "zipcode": "00601"
},
{
    "street_name": "PO BOX",
    "zipcode": "00601"
},
{
    "street_name": "PO BOX",
    "zipcode": "00601"
},
{
    "street_name": "PO BOX",
    "zipcode": "00601"
},
{
    "street_name": "PO BOX",
    "zipcode": "00601"
},
{
    "street_name": "PO BOX",
    "zipcode": "00601"
}]

d) ZIP Code (all)

This example refers to the process of getting all addresses containing a specified ZIP Code.

Pass the ZIP Code value of the address to search for in the endpoint’s zipcode path parameter.


PARAMETERS

Parameter Type Description
api_key string API key of the user
zipcode string ZIP Code of the area
<job id="GetStreetAddressesZipAll">
    <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://rapid.route4me.com/street_data/zipcode"
            apikey="11111111111111111111111111111111"
            zipcode="00601"
            
            url=url&"/"&zipcode&"/"
            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://rapid.route4me.com/street_data/zipcode
SET apikey=11111111111111111111111111111111
SET zipcode=00601

ECHO ON

:: The example refers to the process of getting all street data filtered by a specified ZIP Code.

curl -o file1.txt -g -X GET -k "%url%/%zipcode%/?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://rapid.route4me.com/street_data/zipcode
apikey=11111111111111111111111111111111
zipcode=00601

 # The example refers to the process of getting all street data filtered by a specified ZIP Code.

curl -o file1.txt -g -X GET -k "$url/$zipcode/?api_key=$apikey"

echo "Finished..."

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

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Rapid Street Zipcode All
        /// </summary>
        public void RapidStreetZipcodeAll()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            GeocodingParameters geoParams = new GeocodingParameters()
            {
                Zipcode = "00601"
            };
            // Run the query
            string errorString = "";
            ArrayList result = route4Me.RapidStreetZipcode(geoParams, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("RapidStreetZipcodeAll executed successfully");
                foreach (Dictionary<string, string> res1 in result)
                {

                    Console.WriteLine("ZIP Code: " + res1["zipcode"]);
                    Console.WriteLine("Street name: " + res1["street_name"]);
                    Console.WriteLine("---------------------------");
                }
            }
            else
            {
                Console.WriteLine("RapidStreetZipcodeAll error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Rapid Street Zipcode All
        ''' </summary>
        Public Sub RapidStreetZipcodeAll()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)
            Dim geoParams As New GeocodingParameters With { _
                .Zipcode = "00601" _
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As ArrayList = route4Me.RapidStreetZipcode(geoParams, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("RapidStreetZipcodeAll executed successfully")
                For Each res1 In result
                    Console.WriteLine("ZIP Code: " & res1("zipcode"))
                    Console.WriteLine("Street name: " & res1("street_name"))
                    Console.WriteLine("---------------------------")
                Next
            Else
                Console.WriteLine("RapidStreetZipcodeAll error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    rapid_address = route4me.rapid_address
    response = rapid_address.get_street_data_zip(zipcode=33166)
    for street in response:
        print 'Street Name:\t{0}\t\tZIP Code:\t{1}'.format(
            street.get('street_name'),
            street.get('zipcode'))

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() {
    rapidService := geocoding.NewRapidService("your-api-key")
    addrs, err := rapidService.GetAddressesByZipcode("00601")
    if err != nil {
        //handle error
    }
    //do something with an array of addresses
}
<?php
namespace Route4Me;

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

use Route4Me\Route4Me;
use Route4Me\Geocoding;

// The example refers to getting all geocodings using a specified ZIP Code.

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

$gcParameters = (array)Geocoding::fromArray(array(
    "zipcode" => '00601'
));

$geocoding = new Geocoding();

$response = $geocoding->getZipCode($gcParameters);

foreach ($response as $gcode) {
    Route4Me::simplePrint($gcode);
    echo "<br>";
}
unit GetZipCodesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetZipCodes = class(TBaseExample)
  public
    procedure Execute(ZipCode: String);
  end;

implementation
uses GeocodingAddressUnit;
procedure TGetZipCodes.Execute(ZipCode: String);
var
  ErrorString: String;
  Addresses: TGeocodingAddressList;
begin
  Addresses := Route4MeManager.Geocoding.GetZipCodes(ZipCode, ErrorString);
  try
    WriteLn('');

    if (Addresses <> nil) then
    begin
      WriteLn('GetZipCodes executed successfully');
      WriteLn(Format('Address count: %d', [Addresses.Count]));
    end
    else
      WriteLn(Format('GetZipCodes error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Addresses);
  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
https://rapid.route4me.com/street_data/zipcode?api_key=...

You can expect this API response:

[{
    "zipcode": "00601",
    "street_name": "GENERAL DELIVERY"
},
{
    "zipcode": "00601",
    "street_name": "HC 1"
}
]

e) ZIP Code and House Number (all)

This example refers to the process of getting all addresses containing a specified ZIP Code and house number.

Pass the ZIP Code and house number values of the address to search for in the zipcode and housenumber path parameters respectively.


PARAMETERS

Parameter Type Description
api_key string API key of the user
zipcode string ZIP Code of the area
housenumber string House number
<job id="GetStreetAddressesZipHouseAll">
    <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://rapid.route4me.com/street_data/service"
            apikey="11111111111111111111111111111111"
            zipcode="00601"
            housenumber="17"
            
            url=url&"/"&zipcode
            url=url&"/"&housenumber&"/"
            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://rapid.route4me.com/street_data/service
SET apikey=11111111111111111111111111111111
SET zipcode=00601
SET housenumber=17

ECHO ON

:: The example refers to the process of getting street data filtered by specified ZIP Code and house number.

curl -o file1.txt -g -X GET -k "%url%/%zipcode%/%housenumber%/?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://rapid.route4me.com/street_data/service
apikey=11111111111111111111111111111111
zipcode=00601
housenumber=17

 # The example refers to the process of getting street data filtered by specified ZIP Code and house number.

curl -o file1.txt -g -X GET -k "$url/$zipcode/$housenumber/?api_key=$apikey"

echo "Finished..."

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

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Rapid Street Service All
        /// </summary>
        public void RapidStreetServiceAll()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            GeocodingParameters geoParams = new GeocodingParameters()
            {
                Zipcode = "00601",
                Housenumber = "17"
            };
            // Run the query
            string errorString = "";
            ArrayList result = route4Me.RapidStreetService(geoParams, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("RapidStreetServiceAll executed successfully");
                foreach (Dictionary<string, string> res1 in result)
                {

                    Console.WriteLine("ZIP Code: " + res1["zipcode"]);
                    Console.WriteLine("Street name: " + res1["street_name"]);
                    Console.WriteLine("---------------------------");
                }
            }
            else
            {
                Console.WriteLine("RapidStreetServiceAll error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Rapid Street Service All
        ''' </summary>
        Public Sub RapidStreetServiceAll()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)
            Dim geoParams As New GeocodingParameters With { _
                .Zipcode = "00601", _
                .Housenumber = "17" _
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As ArrayList = route4Me.RapidStreetService(geoParams, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("RapidStreetServiceAll executed successfully")
                For Each res1 In result
                    Console.WriteLine("ZIP Code: " & res1("zipcode"))
                    Console.WriteLine("Street name: " & res1("street_name"))
                    Console.WriteLine("---------------------------")
                Next
            Else
                Console.WriteLine("RapidStreetServiceAll error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    rapid_address = route4me.rapid_address
    response = rapid_address.get_street_data_service(housenumber=1800,
                                                     zipcode=33166)
    for street in response:
        print 'Street Name:\t{0}\t\tZIP Code:\t{1}'.format(
            street.get('street_name'),
            street.get('zipcode'))

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() {
    rapidService := geocoding.NewRapidService("your-api-key")
    addrs, err := rapidService.GetAddressesByZipcodeAndHousenumber("00601", 17)
    if err != nil {
        //handle error
    }
    //do something with an array of addresses
}
<?php
namespace Route4Me;

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

use Route4Me\Route4Me;
use Route4Me\Geocoding;

// The example refers to getting all geocodings with specified ZIP Code and house number.

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

$gcParameters = (array)Geocoding::fromArray(array(
    "zipcode"     => '00601',
    "housenumber" => 17
));

$geocoding = new Geocoding();

$response = $geocoding->getService($gcParameters);

foreach ($response as $gcode) {
    Route4Me::simplePrint($gcode);
    echo "<br>";
}
unit GetZipCodeAndHouseNumberUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetZipCodeAndHouseNumber = class(TBaseExample)
  public
    procedure Execute(ZipCode, HouseNumber: String);
  end;

implementation
uses GeocodingAddressUnit;
procedure TGetZipCodeAndHouseNumber.Execute(ZipCode, HouseNumber: String);
var
  ErrorString: String;
  Addresses: TGeocodingAddressList;
begin
  Addresses := Route4MeManager.Geocoding.GetZipCodeAndHouseNumber(
    ZipCode, HouseNumber, ErrorString);
  try
    WriteLn('');

    if (Addresses <> nil) then
    begin
      WriteLn('GetZipCodeAndHouseNumber executed successfully');
      WriteLn(Format('Address count: %d', [Addresses.Count]));
    end
    else
      WriteLn(Format('GetZipCodeAndHouseNumber error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Addresses);
  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
https://rapid.route4me.com/street_data/service/zipcode/housenumber?api_key=...

You can expect this API response:

[{
    "zipcode": "00601",
    "street_name": "ALTS DE ADJUNTAS"
},
{
    "zipcode": "00601",
    "street_name": "BDA LA OLIMPIA"
}
]

f) ZIP Code and House Number (limited)

This example refers to the process of getting a limited number of addresses containing a specified ZIP Code and house number.

Pass the ZIP Code and house number values of the address to search for in the zipcode and housenumber path parameters respectively. Then, use the offset and limit parameters to customize and limit the number of records returned.


PARAMETERS

Parameter Type Description
api_key string API key of the user
zipcode string ZIP Code of the area
housenumber string House number
offset integer Search starting position
limit integer The number of records to return.
<job id="GetStreetAddressesZipHouseLimit">
    <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://rapid.route4me.com/street_data/service"
            apikey="11111111111111111111111111111111"
            zipcode="00601"
            housenumber="17"
            offset="0"
            limit="20"
            
            url=url&"/"&zipcode
            url=url&"/"&housenumber
            url=url&"/"&offset
            url=url&"/"&limit&"/"
            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://rapid.route4me.com/street_data/service
SET apikey=11111111111111111111111111111111
SET zipcode=00601
SET housenumber=17
SET offset=0
SET limit=20

ECHO ON

:: The example refers to the process of getting a limited number of street data filtered by specified ZIP Code and house number.

curl -o file1.txt -g -X GET -k "%URL%/%zipcode%/%housenumber%/%offset%/%limit%/?api_key=%apikey%"

timeout /t 30
#!/bin/bash

url=https://rapid.route4me.com/street_data/service
apikey=11111111111111111111111111111111
zipcode=00601
housenumber=17
offset=0
limit=20

# The example refers to the process of getting a limited number of street data filtered by specified ZIP Code and house number.

curl -o file1.txt -g -X GET -k "$url/$zipcode/$housenumber/$offset/$limit/?api_key=$apikey"

echo "Finished..."

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

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Rapid Street Service Limited
        /// </summary>
        public void RapidStreetServiceLimited()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            GeocodingParameters geoParams = new GeocodingParameters()
            {
                Zipcode = "00601",
                Housenumber = "17",
                Offset = 1,
                Limit = 10
            };
            // Run the query
            string errorString = "";
            ArrayList result = route4Me.RapidStreetService(geoParams, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("RapidStreetServiceLimited executed successfully");
                foreach (Dictionary<string, string> res1 in result)
                {

                    Console.WriteLine("ZIP Code: " + res1["zipcode"]);
                    Console.WriteLine("Street name: " + res1["street_name"]);
                    Console.WriteLine("---------------------------");
                }
            }
            else
            {
                Console.WriteLine("RapidStreetServiceLimited error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Rapid Street Service Limited
        ''' </summary>
        Public Sub RapidStreetServiceLimited()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)
            Dim geoParams As New GeocodingParameters With { _
                .Zipcode = "00601", _
                .Housenumber = "17", _
                .Offset = 1, _
                .Limit = 10 _
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As ArrayList = route4Me.RapidStreetService(geoParams, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("RapidStreetServiceLimited executed successfully")
                For Each res1 In result
                    Console.WriteLine("ZIP Code: " & res1("zipcode"))
                    Console.WriteLine("Street name: " & res1("street_name"))
                    Console.WriteLine("---------------------------")
                Next
            Else
                Console.WriteLine("RapidStreetServiceLimited error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    rapid_address = route4me.rapid_address
    response = rapid_address.get_street_data_service(housenumber=1800,
                                                     zipcode=33166,
                                                     offset=10,
                                                     limit=5)
    for street in response:
        print 'Street Name:\t{0}\t\tZIP Code:\t{1}'.format(
            street.get('street_name'),
            street.get('zipcode'))

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() {
    rapidService := geocoding.NewRapidService("your-api-key")
    //                                                                       zipcode, housenumber, limit, offset
    addrs, err := rapidService.GetLimitedAddressesByZipcodeAndHousenumber("00601", 17,          0,     20);
    if err != nil {
        //handle error
    }
    //do something with an array of addresses
}
<?php
namespace Route4Me;

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

use Route4Me\Route4Me;
use Route4Me\Geocoding;

// The example refers to the process of getting a limited number of street data filtered by specified ZIP Code and house number.

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

$gcParameters = (array)Geocoding::fromArray(array(
    "zipcode"     => '00601',
    "housenumber" => 17,
    "offset"      => 0,
    "limit"       => 10
));

$geocoding = new Geocoding();

$response = $geocoding->getService($gcParameters);

foreach ($response as $gcode) {
    Route4Me::simplePrint($gcode);
    echo "<br>";
}
unit GetLimitedZipCodeAndHouseNumberUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetLimitedZipCodeAndHouseNumber = class(TBaseExample)
  public
    procedure Execute(ZipCode, HouseNumber: String; Limit, Offset: integer);
  end;

implementation
uses GeocodingAddressUnit;
procedure TGetLimitedZipCodeAndHouseNumber.Execute(
  ZipCode, HouseNumber: String; Limit, Offset: integer);
var
  ErrorString: String;
  Addresses: TGeocodingAddressList;
begin
  Addresses := Route4MeManager.Geocoding.GetZipCodeAndHouseNumber(
    ZipCode, HouseNumber, Limit, Offset, ErrorString);
  try
    WriteLn('');

    if (Addresses <> nil) then
    begin
      WriteLn('GetLimitedZipCodeAndHouseNumber executed successfully');
      WriteLn(Format('Address count: %d', [Addresses.Count]));
    end
    else
      WriteLn(Format('GetLimitedZipCodeAndHouseNumber error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Addresses);
  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);

    AddressData addr;
    addr.zipCode = "00601";
    addr.houseNumber = "17";
    int offset = 5, limit = 10;

    if(route.get_street_address(addr,offset,limit) == 0)
    {
        cout << "Address:" << 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.
An example for this language will be added in the future. For now, please see the other languages available for reference.


HTTP Request

GET
https://rapid.route4me.com/street_data/service/zc/hn/offset/limit/?api_key=...

You can expect this API response:

[{
    "zipcode": "00601",
    "street_name": "ALTS DE ADJUNTAS"
},
{
    "zipcode": "00601",
    "street_name": "BDA LA OLIMPIA"
}
]

g) ZIP Code (limited)

This example refers to the process of getting a limited number of addresses containing a specified ZIP Code.

Pass the ZIP Code value of the address to search for in the zipcode path parameter. Then, use the offset and limit parameters to customize and limit the number of records returned.


PARAMETERS

Parameter Type Description
api_key string API key of the user
zipcode string ZIP Code of the area
offset integer Search starting position
limit integer The number of records to return.
<job id="GetStreetAddressesZipLimit">
    <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://rapid.route4me.com/street_data/zipcode"
            apikey="11111111111111111111111111111111"
            zipcode="00601"
            offset="0"
            limit="20"
            
            url=url&"/"&zipcode
            url=url&"/"&offset
            url=url&"/"&limit&"/"
            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://rapid.route4me.com/street_data/zipcode
SET apikey=11111111111111111111111111111111
SET zipcode=00601
SET offset=0
SET limit=10

ECHO ON

:: The example refers to the process of getting street data filtered by ZIP Code and limited with specified parameters.

curl -o file1.txt -g -X GET -k "%URL%/%zipcode%/%offset%/%limit%/?api_key=%apikey%"

timeout /t 30
 #!/bin/bash

url=https://rapid.route4me.com/street_data/zipcode
apikey=11111111111111111111111111111111
zipcode=00601
offset=0
limit=20

 # The example refers to the process of getting street data filtered by ZIP Code and limited with specified parameters.

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

echo "Finished..."

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

namespace Route4MeSDK.Examples
{
    public sealed partial class Route4MeExamples
    {
        /// <summary>
        /// Rapid Street Zipcode Limited
        /// </summary>
        public void RapidStreetZipcodeLimited()
        {
            // Create the manager with the API key
            Route4MeManager route4Me = new Route4MeManager(c_ApiKey);

            GeocodingParameters geoParams = new GeocodingParameters()
            {
                Zipcode = "00601",
                Offset = 1,
                Limit = 10
            };
            // Run the query
            string errorString = "";
            ArrayList result = route4Me.RapidStreetZipcode(geoParams, out errorString);

            Console.WriteLine("");

            if (result != null)
            {
                Console.WriteLine("RapidStreetZipcodeLimited executed successfully");
                foreach (Dictionary<string, string> res1 in result)
                {

                    Console.WriteLine("ZIP Code: " + res1["zipcode"]);
                    Console.WriteLine("Street name: " + res1["street_name"]);
                    Console.WriteLine("---------------------------");
                }
            }
            else
            {
                Console.WriteLine("RapidStreetZipcodeLimited error: {0}", errorString);
            }
        }
    }
}
Imports Route4MeSDKLibrary.Route4MeSDK
Imports Route4MeSDKLibrary.Route4MeSDK.DataTypes
Imports Route4MeSDKLibrary.Route4MeSDK.QueryTypes

Namespace Route4MeSDKTest.Examples
    Partial Public NotInheritable Class Route4MeExamples
        ''' <summary>
        ''' Rapid Street Zipcode Limited
        ''' </summary>
        Public Sub RapidStreetZipcodeLimited()
            ' Create the manager with the API key
            Dim route4Me As New Route4MeManager(c_ApiKey)
            Dim geoParams As New GeocodingParameters With { _
                .Zipcode = "00601", _
                .Offset = 1, _
                .Limit = 10 _
            }
            ' Run the query
            Dim errorString As String = ""
            Dim result As ArrayList = route4Me.RapidStreetZipcode(geoParams, errorString)

            Console.WriteLine("")

            If result IsNot Nothing Then
                Console.WriteLine("RapidStreetZipcodeLimited executed successfully")
                For Each res1 In result
                    Console.WriteLine("ZIP Code: " & res1("zipcode"))
                    Console.WriteLine("Street name: " & res1("street_name"))
                    Console.WriteLine("---------------------------")
                Next
            Else
                Console.WriteLine("RapidStreetZipcodeLimited error: {0}", errorString)
            End If
        End Sub
    End Class
End Namespace
from route4me import Route4Me

KEY = "11111111111111111111111111111111"

def main():
    route4me = Route4Me(KEY)
    rapid_address = route4me.rapid_address
    response = rapid_address.get_street_data_zip(zipcode=33166,
                                                 offset=10,
                                                 limit=20)
    for street in response:
        print 'Street Name:\t{0}\t\tZIP Code:\t{1}'.format(
            street.get('street_name'),
            street.get('zipcode'))

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() {
    rapidService := geocoding.NewRapidService("your-api-key")
    //                                                      zipcode, limit, offset
    addrs, err := rapidService.GetLimitedAddressesByZipcode("00601", 20,   0)
    if err != nil {
        //handle error
    }
    //do something with an array of addresses
}
<?php
namespace Route4Me;

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

use Route4Me\Route4Me;
use Route4Me\Geocoding;

// The example refers to getting a limited number of geocodings with specified ZIP Code.

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

$gcParameters = (array)Geocoding::fromArray(array(
    "zipcode" => '00601',
    "offset"  => 0,
    "limit"   => 20
));

$geocoding = new Geocoding();

$response = $geocoding->getZipCode($gcParameters);

foreach ($response as $gcode) {
    Route4Me::simplePrint($gcode);
    echo "<br>";
}
unit GetLimitedZipCodesUnit;

interface

uses SysUtils, BaseExampleUnit;

type
  TGetLimitedZipCodes = class(TBaseExample)
  public
    procedure Execute(ZipCode: String; Limit, Offset: integer);
  end;

implementation
uses GeocodingAddressUnit;
procedure TGetLimitedZipCodes.Execute(ZipCode: String; Limit, Offset: integer);
var
  ErrorString: String;
  Addresses: TGeocodingAddressList;
begin
  Addresses := Route4MeManager.Geocoding.GetZipCodes(
    ZipCode, Limit, Offset, ErrorString);
  try
    WriteLn('');

    if (Addresses <> nil) then
    begin
      WriteLn('GetLimitedZipCodes executed successfully');
      WriteLn(Format('Address count: %d', [Addresses.Count]));
    end
    else
      WriteLn(Format('GetLimitedZipCodes error: "%s"', [ErrorString]));
  finally
    FreeAndNil(Addresses);
  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
https://rapid.route4me.com/street_data/zipcode/limit/?api_key=...

You can expect this API response:

[{
    "zipcode": "00601",
    "street_name": "GENERAL DELIVERY"
},
{
    "zipcode": "00601",
    "street_name": "HC 1"
}
]

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.dtd

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.dtd

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 != ni