Polyline Length Calculator API: The Complete Guide

Need to calculate the total distance of a route or path? This guide covers everything about polyline length calculation via API, including the distance formulas, encoding formats, and implementation examples.

What is a Polyline?

A polyline is a series of connected line segments defined by a sequence of coordinates. It's commonly used to represent routes, paths, trails, or any linear geographic feature.

Polylines can be represented as an array of coordinates or as an encoded string (Google Encoded Polyline format) for compact transmission.

Distance Calculation Method

The total polyline length is calculated by summing the distances between consecutive points:

Haversine Formula

Each segment distance is calculated using the Haversine formula, which accounts for Earth's curvature:

Total Length = sum of haversine_distance(point[i], point[i+1])
Precision: The Haversine formula provides accuracy within 0.5% for most practical purposes. For sub-meter precision, Vincenty's formula is available.

Using the Polyline Length API

TinyFn provides endpoints to calculate polyline length:

API Request
POST https://api.tinyfn.io/v1/geo/polyline-length
Headers: X-API-Key: your-api-key
Content-Type: application/json

{
  "points": [
    {"lat": 40.7128, "lng": -74.0060},
    {"lat": 40.7580, "lng": -73.9855},
    {"lat": 40.7484, "lng": -73.9857}
  ]
}
Response
{
  "length": {
    "km": 5.234,
    "mi": 3.252,
    "m": 5234,
    "nm": 2.826
  },
  "segments": [
    {"from": 0, "to": 1, "distance_km": 3.456},
    {"from": 1, "to": 2, "distance_km": 1.778}
  ],
  "point_count": 3
}

Parameters

Parameter Type Description
points array Array of coordinates with lat/lng (option 1)
encoded string Google Encoded Polyline string (option 2)
unit string Primary unit for response: "km", "mi", "m", "nm" (default: "km")
include_segments boolean Include individual segment distances (default: false)

Code Examples

JavaScript / Node.js

const response = await fetch(
  'https://api.tinyfn.io/v1/geo/polyline-length',
  {
    method: 'POST',
    headers: {
      'X-API-Key': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      points: [
        { lat: 40.7128, lng: -74.0060 },
        { lat: 40.7580, lng: -73.9855 },
        { lat: 40.7484, lng: -73.9857 }
      ]
    })
  }
);
const { length } = await response.json();
console.log(`Total distance: ${length.km} km`);

Python

import requests

response = requests.post(
    'https://api.tinyfn.io/v1/geo/polyline-length',
    headers={'X-API-Key': 'your-api-key'},
    json={
        'points': [
            {'lat': 40.7128, 'lng': -74.0060},
            {'lat': 40.7580, 'lng': -73.9855},
            {'lat': 40.7484, 'lng': -73.9857}
        ]
    }
)
length = response.json()['length']
print(f"Total distance: {length['km']} km")

cURL

curl -X POST "https://api.tinyfn.io/v1/geo/polyline-length" \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "points": [
      {"lat": 40.7128, "lng": -74.0060},
      {"lat": 40.7580, "lng": -73.9855},
      {"lat": 40.7484, "lng": -73.9857}
    ]
  }'

Common Use Cases

  • Route Distance: Calculate total driving, walking, or cycling route distance
  • Trail Mapping: Measure hiking or running trail lengths
  • Delivery Logistics: Calculate delivery route distances for cost estimation
  • GPS Tracking: Compute total distance traveled from GPS data
  • Sports Analytics: Analyze athlete movement patterns and distances

Best Practices

  1. Use encoded polylines: For large routes, use Google Encoded Polyline format to reduce payload size
  2. Simplify if needed: For display purposes, simplify the polyline to reduce point count
  3. Choose appropriate units: Use km for long distances, meters for short routes
  4. Consider segment analysis: Enable segment distances to identify the longest portions

Use via MCP

Your AI agent can call this tool directly via Model Context Protocol — no HTTP code needed. Add TinyFn to Claude Desktop, Cursor, or any MCP client:

{
  "mcpServers": {
    "tinyfn-geo": {
      "url": "https://api.tinyfn.io/mcp/geo/",
      "headers": {
        "X-API-Key": "your-api-key"
      }
    }
  }
}

See all geolocation tools available via MCP in our Geolocation MCP Tools for AI Agents guide.

Try the Polyline Length API

Get your free API key and start calculating route distances in seconds.

Get Free API Key

Ready to try TinyFn?

Get your free API key and start building in minutes.

Get Free API Key