Distance CalculatorDistance Calculator API

OnlineCredit Usage:1 per callRefreshed 1 month ago
avg: 1023ms|p50: 931ms|p75: 1084ms|p90: 1269ms|p99: 1637ms

Distance Calculator is a simple tool for calculating the distance between two locations. It returns the distance in miles and kilometers.

The Distance Calculator API provides reliable and fast access to distance calculator data through a simple REST interface. Built for developers who need consistent, high-quality results with minimal setup time.

To use Distance Calculator, you need an API key. You can get one by creating a free account and visiting your dashboard.

GET Endpoint

URL
https://api.apiverve.com/v1/distancecalculator

Code Examples

Here are examples of how to call the Distance Calculator API in different programming languages:

cURL Request
curl -X GET \
  "https://api.apiverve.com/v1/distancecalculator?lat1=36.7783&lon1=-119.4179&lat2=34.0522&lon2=-118.2437" \
  -H "X-API-Key: your_api_key_here"
JavaScript (Fetch API)
const response = await fetch('https://api.apiverve.com/v1/distancecalculator?lat1=36.7783&lon1=-119.4179&lat2=34.0522&lon2=-118.2437', {
  method: 'GET',
  headers: {
    'X-API-Key': 'your_api_key_here',
    'Content-Type': 'application/json'
  }
});

const data = await response.json();
console.log(data);
Python (Requests)
import requests

headers = {
    'X-API-Key': 'your_api_key_here',
    'Content-Type': 'application/json'
}

response = requests.get('https://api.apiverve.com/v1/distancecalculator?lat1=36.7783&lon1=-119.4179&lat2=34.0522&lon2=-118.2437', headers=headers)

data = response.json()
print(data)
Node.js (Native HTTPS)
const https = require('https');
const url = require('url');

const options = {
  method: 'GET',
  headers: {
    'X-API-Key': 'your_api_key_here',
    'Content-Type': 'application/json'
  }
};

const req = https.request('https://api.apiverve.com/v1/distancecalculator?lat1=36.7783&lon1=-119.4179&lat2=34.0522&lon2=-118.2437', options, (res) => {
  let data = '';
  res.on('data', (chunk) => data += chunk);
  res.on('end', () => console.log(JSON.parse(data)));
});

req.end();
PHP (cURL)
<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.apiverve.com/v1/distancecalculator?lat1=36.7783&lon1=-119.4179&lat2=34.0522&lon2=-118.2437');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-API-Key: your_api_key_here',
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
print_r($data);

?>
Go (net/http)
package main

import (
    "fmt"
    "io"
    "net/http"

)

func main() {
    req, _ := http.NewRequest("GET", "https://api.apiverve.com/v1/distancecalculator?lat1=36.7783&lon1=-119.4179&lat2=34.0522&lon2=-118.2437", nil)

    req.Header.Set("X-API-Key", "your_api_key_here")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))
}
Ruby (Net::HTTP)
require 'net/http'
require 'json'

uri = URI('https://api.apiverve.com/v1/distancecalculator?lat1=36.7783&lon1=-119.4179&lat2=34.0522&lon2=-118.2437')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Get.new(uri)
request['X-API-Key'] = 'your_api_key_here'
request['Content-Type'] = 'application/json'

response = http.request(request)
puts JSON.pretty_generate(JSON.parse(response.body))
C# (HttpClient)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("X-API-Key", "your_api_key_here");

        var response = await client.GetAsync("https://api.apiverve.com/v1/distancecalculator?lat1=36.7783&lon1=-119.4179&lat2=34.0522&lon2=-118.2437");
        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}

Authentication

The Distance Calculator API requires authentication via API key. Include your API key in the request header:

Required Header
X-API-Key: your_api_key_here

Learn more about authentication →

Interactive API Playground

Test the Distance Calculator API directly in your browser with live requests and responses.

Parameters

The following parameters are available for the Distance Calculator API:

Calculate Distance

ParameterTypeRequiredDescriptionDefaultExample
lat1numberrequired
The latitude of the first location
Range: -90 - 90
-36.7783
lon1numberrequired
The longitude of the first location
Range: -180 - 180
--119.4179
lat2numberrequired
The latitude of the second location
Range: -90 - 90
-34.0522
lon2numberrequired
The longitude of the second location
Range: -180 - 180
--118.2437

Response

The Distance Calculator API returns responses in JSON, XML, YAML, and CSV formats:

Example Responses

JSON Response
200 OK
{
  "status": "ok",
  "error": null,
  "data": {
    "distanceMiles": 199.6804337234997,
    "distanceKm": 321.2535462758628,
    "location1": {
      "latitude": "36.728450",
      "longitude": "-119.53571",
      "city": "Sanger",
      "state": "California"
    },
    "location2": {
      "latitude": "34.044662",
      "longitude": "-118.24255",
      "city": "Los Angeles",
      "state": "California"
    },
    "bearing": 198,
    "direction": "South",
    "estimatedDriveTime": "5h 11m"
  }
}
XML Response
200 OK
<?xml version="1.0" encoding="UTF-8"?>
<response>
  <status>ok</status>
  <error xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
  <data>
    <distanceMiles>199.6804337234997</distanceMiles>
    <distanceKm>321.2535462758628</distanceKm>
    <location1>
      <latitude>36.728450</latitude>
      <longitude>-119.53571</longitude>
      <city>Sanger</city>
      <state>California</state>
    </location1>
    <location2>
      <latitude>34.044662</latitude>
      <longitude>-118.24255</longitude>
      <city>Los Angeles</city>
      <state>California</state>
    </location2>
    <bearing>198</bearing>
    <direction>South</direction>
    <estimatedDriveTime>5h 11m</estimatedDriveTime>
  </data>
</response>
YAML Response
200 OK
status: ok
error: null
data:
  distanceMiles: 199.6804337234997
  distanceKm: 321.2535462758628
  location1:
    latitude: '36.728450'
    longitude: '-119.53571'
    city: Sanger
    state: California
  location2:
    latitude: '34.044662'
    longitude: '-118.24255'
    city: Los Angeles
    state: California
  bearing: 198
  direction: South
  estimatedDriveTime: 5h 11m
CSV Response
200 OK
keyvalue
distanceMiles199.6804337234997
distanceKm321.2535462758628
location1{latitude:36.728450,longitude:-119.53571,city:Sanger,state:California}
location2{latitude:34.044662,longitude:-118.24255,city:Los Angeles,state:California}
bearing198
directionSouth
estimatedDriveTime5h 11m

Response Structure

All API responses follow a consistent structure with the following fields:

FieldTypeDescriptionExample
statusstringIndicates whether the request was successful ("ok") or failed ("error")ok
errorstring | nullContains error message if status is "error", otherwise nullnull
dataobject | nullContains the API response data if successful, otherwise null{...}

Learn more about response formats →

Response Data Fields

When the request is successful, the data object contains the following fields:

Response fields marked with Premium are available exclusively on paid plans.View pricing
FieldTypeSample ValueDescription
distanceMilesnumber199.6804337234997-
distanceKmnumber321.2535462758628-
location1object{...}-
â”” latitudestring"36.728450"-
â”” longitudestring"-119.53571"-
â”” citystring"Sanger"-
â”” statestring"California"-
location2object{...}-
â”” latitudestring"34.044662"-
â”” longitudestring"-118.24255"-
â”” citystring"Los Angeles"-
â”” statestring"California"-
bearingPremiumnumber198Compass bearing in degrees (0-360) from location1 to location2
directionPremiumstring"South"Cardinal direction: North, Northeast, East, Southeast, South, Southwest, West, Northwest
estimatedDriveTimePremiumstring"5h 11m"Estimated driving time (e.g., 3h 45m)

Headers

Required and optional headers for Distance Calculator API requests:

Header NameRequiredExample ValueDescription
X-API-Keyrequiredyour_api_key_hereYour APIVerve API key. Found in your dashboard under API Keys.
Acceptoptionalapplication/jsonSpecify response format: application/json (default), application/xml, or application/yaml
User-AgentoptionalMyApp/1.0Identifies your application for analytics and debugging purposes
X-Request-IDoptionalreq_123456789Custom request identifier for tracking and debugging requests
Cache-Controloptionalno-cacheControl caching behavior for the request and response

Learn more about request headers →

GraphQL AccessALPHA

Access Distance Calculator through GraphQL to combine it with other API calls in a single request. Query only the distance calculator data you need with precise field selection, and orchestrate complex data fetching workflows.

Test Distance Calculator in the GraphQL Explorer to confirm availability and experiment with queries.

Credit Cost: Each API called in your GraphQL query consumes its standard credit cost.

GraphQL Endpoint
POST https://api.apiverve.com/v1/graphql
GraphQL Query Example
query {
  distancecalculator(
    input: {
      lat1: 36.7783
      lon1: -119.4179
      lat2: 34.0522
      lon2: -118.2437
    }
  ) {
    distanceMiles
    distanceKm
    location1 {
      latitude
      longitude
      city
      state
    }
    location2 {
      latitude
      longitude
      city
      state
    }
    bearing
    direction
    estimatedDriveTime
  }
}

Note: Authentication is handled via the x-api-key header in your GraphQL request, not as a query parameter.

CORS Support

The Distance Calculator API supports Cross-Origin Resource Sharing (CORS) with wildcard configuration, allowing you to call Distance Calculator directly from browser-based applications without proxy servers.

CORS HeaderValueDescription
Access-Control-Allow-Origin*Accepts requests from any origin
Access-Control-Allow-Methods*Accepts any HTTP method
Access-Control-Allow-Headers*Accepts any request headers

Browser Usage: You can call Distance Calculator directly from JavaScript running in the browser without encountering CORS errors. No proxy server or additional configuration needed.

Learn more about CORS support →

Rate Limiting

Distance Calculator API requests are subject to rate limiting based on your subscription plan. These limits ensure fair usage and maintain service quality for all Distance Calculator users.

PlanRate LimitDescription
Free5 requests/minHard rate limit enforced - exceeding will return 429 errors
StarterNo LimitProduction ready - standard traffic priority
ProNo LimitProduction ready - preferred traffic priority
MegaNo LimitProduction ready - highest traffic priority

Learn more about rate limiting →

Rate Limit Headers

When rate limits apply, each Distance Calculator response includes headers to help you track your usage:

HeaderDescription
X-RateLimit-LimitMaximum number of requests allowed per time window
X-RateLimit-RemainingNumber of requests remaining in the current window
X-RateLimit-ResetUnix timestamp when the rate limit window resets

Handling Rate Limits

Free Plan: When you exceed your rate limit, Distance Calculator returns a 429 Too Many Requests status code. Your application should implement appropriate backoff logic to handle this gracefully.

Paid Plans: No rate limiting or throttling applied. All paid plans (Starter, Pro, Mega) are production-ready.

Best Practices for Distance Calculator:

  • Monitor the rate limit headers to track your Distance Calculator usage (Free plan only)
  • Cache distance calculator responses where appropriate to reduce API calls
  • Upgrade to Pro or Mega for guaranteed no-throttle Distance Calculator performance

Note: Distance Calculator rate limits are separate from credit consumption. You may have credits remaining but still hit rate limits when using Distance Calculator on Free tier.

Error Codes

The Distance Calculator API uses standard HTTP status codes to indicate success or failure:

CodeMessageDescriptionSolution
200OKRequest successful, data returnedNo action needed - request was successful
400Bad RequestInvalid request parameters or malformed requestCheck required parameters and ensure values match expected formats
401UnauthorizedMissing or invalid API keyInclude x-api-key header with valid API key from dashboard
403ForbiddenAPI key lacks permission or insufficient creditsCheck credit balance in dashboard or upgrade plan
429Too Many RequestsRate limit exceeded (Free: 5 req/min)Implement request throttling or upgrade to paid plan
500Internal Server ErrorServer error occurredRetry request after a few seconds, contact support if persists
503Service UnavailableAPI temporarily unavailableWait and retry, check status page for maintenance updates

Learn more about error handling →

Need help? Contact support with your X-Request-ID for assistance.

Integrate Distance Calculator with SDKs

Get started quickly with official Distance Calculator SDKs for your preferred language. Each library handles authentication, request formatting, and error handling automatically.

Available for Node.js, Python, C#/.NET, and Android/Java. All SDKs are open source and regularly updated.

Integrate Distance Calculator with No-Code API Tools

Connect the Distance Calculator API to your favorite automation platform without writing code. Build workflows that leverage distance calculator data across thousands of apps.

All platforms use your same API key to access Distance Calculator. Visit our integrations hub for step-by-step setup guides.

Frequently Asked Questions

How do I get an API key for Distance Calculator?
Sign up for a free account at dashboard.apiverve.com. Your API key will be automatically generated and available in your dashboard. The same key works for Distance Calculator and all other APIVerve APIs. The free plan includes 1,000 credits plus a 500 credit bonus.
How many credits does Distance Calculator cost?

Each successful Distance Calculator API call consumes credits based on plan tier. Check the pricing section above for the exact credit cost. Failed requests and errors don't consume credits, so you only pay for successful distance calculator lookups.

Can I use Distance Calculator in production?

The free plan is for testing and development only. For production use of Distance Calculator, upgrade to a paid plan (Starter, Pro, or Mega) which includes commercial use rights, no attribution requirements, and guaranteed uptime SLAs. All paid plans are production-ready.

Can I use Distance Calculator from a browser?
Yes! The Distance Calculator API supports CORS with wildcard configuration, so you can call it directly from browser-based JavaScript without needing a proxy server. See the CORS section above for details.
What happens if I exceed my Distance Calculator credit limit?

When you reach your monthly credit limit, Distance Calculator API requests will return an error until you upgrade your plan or wait for the next billing cycle. You'll receive notifications at 80% and 95% usage to give you time to upgrade if needed.

What's Next?

Continue your journey with these recommended resources

Was this page helpful?