GET Vehicle Location

GET Location within the Real-time Aggregated Data API is the most commonly used method within the REVEAL API product suite. Integrated users use this method to retrieve regular vehicle location details throughout the day to provide context to other business systems. We recommend that the user does not pull a vehicle’s location data more frequently than every 3 to 5 minutes.

Before attempting to retrieve vehicle location information it is important to know if the REVEAL account has been updated with valid VEHICLE NUMBERS for each vehicle to be pulled via the API. The VEHICLE NUMBER and VEHICLE NAME fields are different fields within REVEAL and the VEHICLE NUMBER field is not automatically populated upon account creation.

<?php
   $token = 'TOKEN_STRING';
   $vehicle_number = 'VEHICLE_NUMBER';
   $FIM_app_id = 'APP_ID';
   $FIM_endpoint = 'https://fim.api.us.fleetmatics.com/rad/v1/vehicles/%s/location';

   //Call method and set variable to location string   
   $location = get_vehicle_location($vehicle_number, $FIM_endpoint, $FIM_app_id, $token);

   echo $location;

   function get_vehicle_location($vehicle_number, $endpoint, $app_id, $token)
   {
      //Inserts vehicle_number into '%s" space in endpoint     
      $url = sprintf($endpoint, $vehicle_number);  

      //Get necessary headers for REST call     	  
      $headers = get_call_headers($app_id, $token);
    
      $session = curl_init($url);                                 //Initialize transfer with URL   
      curl_setopt($session, CURLOPT_HEADER, false);               //Exclude header info in response      
      curl_setopt($session, CURLOPT_RETURNTRANSFER, true);        //Return transfer as a string of the return value of curl_exec()      
      curl_setopt($session, CURLOPT_HTTPHEADER, $headers);        //Pass in headers      

      //Execute transfer of $session     	  
      $response = curl_exec($session); 
    
       //Get http code outcome of the #session transfer	     
      $http_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
    
      //Measure false response/error     
      if($response === false)
      {
         echo 'Error: '. curl_error($session);
      }
    
      //ALWAYS close transfer connection      
      curl_close($session);
    
      //Evaluate variable for non 200(OK) http code     
      if($http_code !== 200)
      {
         echo 'Error: Http Status Code returned '.$http_code;
      }
    
      return $response;    
   }

   function get_call_headers($app_id, $token)
   {
      //Inserts app_id and token into respective '%s' spaces in the auth header       
      $auth_header = sprintf('Authorization: Atmosphere atmosphere_app_id=%s, Bearer %s', $app_id, $token);
    
      //Create necessary headers for REST call      
      $headers = array();
      $headers[] = $auth_header;  
      $headers[] = 'Accept: application/json';                      //alternatively 'Accept: application/xml'     
    
      return $headers;
   }
?>

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.

GET Location within the Real-time Aggregated Data API is the most commonly used method within the REVEAL API product suite. Integrated users use this method to retrieve regular vehicle location details throughout the day to provide context to other business systems. We recommend that the user does not pull a vehicle’s location data more frequently than every 3 to 5 minutes.

Before attempting to retrieve vehicle location information it is important to know if the REVEAL account has been updated with valid VEHICLE NUMBERS for each vehicle to be pulled via the API. The VEHICLE NUMBER and VEHICLE NAME fields are different fields within REVEAL and the VEHICLE NUMBER field is not automatically populated upon account creation.

Main Method
public class Program{
  public static void main(String[] args){
    
    // Token call goes here, see TokenGenerator example 
    
    // App Id from Fleetmatics Integration Manager (FIM) 
    String appId = "companyname-p-us-4654sdf4fa351af65dsf1d";        
        
    // Vehicle Number for vehicle you wish to get the location for
    String vehicleNumber = "6789";

    // Insert vehicle number into URI	
    String getVehicleLocationUri = String.format("https://fim.api.us.fleetmatics.com/rad/v1/vehicles/%s/location", vehicleNumber);  
	
    // Call method to GET vehicle location
    String location = new GET_Vehicle_Location().GetVehicleLocation(/* token auth string passed here */, getVehicleLocationUri, appId);
	
    // Display results
    System.out.println(location);
  }  
}
GET_Vehicle_Location Class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.net.ssl.HttpsURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class GET_Vehicle_Location
{
  public String GetVehicleLocation(String authString, String getVehicleLocationUri, String appId)
  {  
    String location = "";

    try
    {
      // Construct authentication header for FIM   
      String authHeader = String.format("Atmosphere atmosphere_app_id=%s, Bearer %s", appId, authString);             
 
      URL url = new URL(_getTokenUri);                                       // Construct a url with the earlier supplied GetToken URI
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();   // Open a new Https connection for transmission
      conn.setRequestMethod("GET");                                          // Set request type to GET
      conn.setRequestProperty("Authorization", authHeader);                  // Set Authorization Header
      conn.setRequestProperty("Accept", "text/plain");                       // Denote type of response expected
      conn.setDoOutput(false);                                               // Do not send request body

      // Execute request, read response. If we do not receive a 200 OK, throw exception		
      if (conn.getResponseCode() != HttpsURLConnection.HTTP_OK) {
        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
      }

      // Reads text from a character-input stream
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    
      location = br.readLine();              // Read the buffer into the location variable, not including any line-termination characters
        
      conn.disconnect();                     // End connection to free resources
                
    } catch (MalformedURLException e) {      // Required Exception
        e.printStackTrace(); 
    } catch (IOException e) {                // Required Exception
        e.printStackTrace(); 
    }
    return location;
  } 
}

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.

GET Location within the Real-time Aggregated Data API is the most commonly used method within the REVEAL API product suite. Integrated users use this method to retrieve regular vehicle location details throughout the day to provide context to other business systems. We recommend that the user does not pull a vehicle’s location data more frequently than every 3 to 5 minutes.

Before attempting to retrieve vehicle location information it is important to know if the REVEAL account has been updated with valid VEHICLE NUMBERS for each vehicle to be pulled via the API. The VEHICLE NUMBER and VEHICLE NAME fields are different fields within REVEAL and the VEHICLE NUMBER field is not automatically populated upon account creation.

Main Method
namespace Rest_Get_Vehicle_Location_Example
{
    class Program
    {
        static void Main()
        {
            // Token call goes here, see Rest_Token_Example

            // App Id from Fleetmatics Integration Manager (FIM)
            string appId = "companyname-p-us-4654sdf4fa351af65dsf1d";

            // Vehicle Number for vehicle you wish to get the location for
            string vehicleNumber = "998007";

            // Insert vehicle number into URI
            string getVehicleLocationUri = string.Format("https://fim.api.us.fleetmatics.com/rad/v1/vehicles/{0}/location", vehicleNumber);

            // Call method to get vehicle location
            var location = new GET_VehicleLocation().GetVehicleLocation(/* token object or auth string passed in here */, getVehicleLocationUri, appId);
        }
    }
}
GET_VehicleLocation Class
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Rest_Get_Vehicle_Location_Example
{
    public class GET_VehicleLocation
    {
         public string GetVehicleLocation(/* token object or auth string passed in here */, string getVehicleLocationUri, string appId)
         {
            // Construct authentication header for FIM
            string authHeader = string.Format("Atmosphere atmosphere_app_id={0}, Bearer {1}", appId, /* token authentication string goes here */);

            // Begin new HttpClient. Use "using" to ensure the resource is released
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));          // Set expected result type (application/json or application/xml)
                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authHeader);                        // Pass in FIM auth header

                // Get the response from the REST API call, passing in the endpoint to the method
                using(HttpResponseMessage response = client.GetAsync(getVehicleLocationUri).Result)
                {
                    // Get the result from the response
                    var result = response.Content.ReadAsStringAsync().Result;

                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);     // Logging

                    // True if HttpStatusCode was in the Successful range (200-299); otherwise false
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine(result);     // Logging
                        return result;                 // Return Vehicle Location to parse through
                    }

                    // If this is reached, the call has failed
                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.NotFound:
                            //Vehicle not found
                            return "";
                        case HttpStatusCode.Unauthorized:
                            //optional token renewal here, see Rest_Token_Example
                            return "";
                            /*
                              ... other cases here
                            */
                        default:
                            //take another action
                            return "";
                    }
                }
            }
        }
    }
}

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.

Microsoft Visual Studio

To open and use the zipped Visual Studio projects, you will need a copy of Microsoft Visual Studio. Unzip the file and click on the Visual Studio solution file to begin, after the above requirements have been met.

Xamarin Interactive Workbooks

Xamarin Workbooks provide a blend of documentation and code that is perfect for experimentation, learning, and creating code. To be able to view the interactive workbooks provided by Fleetmatics, please check the specific requirements for your OS and install Xamarin Workbooks, here.