Tugboat Near a Port

Tugboat Near a Port

You’re building a tug operations view near a port: find every tugboat in range, monitor live AIS positions, know what’s inbound, and push real ETAs to dispatch. By the end of this post you’ll query live AIS for a tug “near a port,” combine it with current port activity, and wire it into a minimal dashboard using the Vessels API.

Why tugboats near a port are a perfect fit for the Vessels API

Tug work happens in tight windows and tighter water. Dispatchers need a clean answer to: Which tugs are closest to the berth or channel right now? Which ships are arriving next, from where, and when? The Vessels API exposes exactly that signal via a small set of endpoints you can stand up in minutes:

Illustration: Tugboat Near a Port
  • vessels/nearby — query all traffic within N nautical miles of a port centroid, optionally filtering by ship type.
  • vessels/track — live position, short history, route, and last port visits for a specific tug.
  • port/activity — event feed of arrivals/departures for coordination with pilots and yards.
  • ports/data — snapshot vessel counts inside the port for quick capacity context.
  • (Optionally) vessels/fleet — batch multiple tug MMSIs in one request for a fleet board.

Every response shares a consistent JSON envelope {status, success, message, data}, is authenticated with a single X-API-Key header, and returns globally normalized AIS: positions in decimal degrees, speed in knots, distance in nautical miles, timestamps in UTC ISO 8601.

Core flow: find tugs near a port, then drill down

Start from the area of interest, then enrich the selected tugs with deeper track data.

Step 1 — Query vessels near the port

Use GET /vessels/nearby with the port’s latitude/longitude and a radius. You can include ship_type to narrow to tugboats (e.g., ship_type=Tug if that’s how your system keys vessel categories) and set a limit if your view is constrained.

curl -H "X-API-Key: YOUR_API_KEY" "https://vessels-api.com/api/V1/vessels/track?mmsi=258785000&hours=48"

Sample response shape (truncated for clarity):

{
    "status": 200,
    "success": true,
    "message": "OK",
    "data": {
        "vessel": {
            "imo": "9122556",
            "mmsi": "258785000",
            "name": null
        },
        "current_position": {
            "latitude": 53.33708,
            "longitude": 7.17993,
            "position_precision": "precise",
            "position_accuracy_nm": null,
            "speed_knots": 0,
            "course_degrees": 212,
            "heading_degrees": null,
            "navigational_status": 5,
            "timestamp_utc": "2017-01-24T04:07:04+00:00",
            "age_minutes": 5160921,
            "destination": null,
            "eta": null
        },
        "predicted_eta": null,
        "position_history": [],
        "route": {
            "departure_port": "HERACLIO",
            "departure_time": "2026-04-27T21:35:36+00:00",
            "destination_port": "HERACLIO",
            "eta": null,
            "distance_nm": null,
            "avg_speed_knots": 17.1
        },
        "last_port_visits": [
            {
                "port_id": "156",
                "port_name": "EMDEN",
                "arrival_time": "2026-07-30T13:00:10+00:00",
                "departure_time": null,
                "duration_hours": null
            },
            {
                "port_id": "10",
                "port_name": "HERACLIO",
                "arrival_time": "2026-04-20T12:00:00+00:00",
                "departure_time": "2026-04-23T08:00:00+00:00",
                "duration_hours": 68
            }
        ],
        "weather": null
    }
}

Key fields you’ll actually render on a map or list:

  • data.vessels[].position.latitude/longitude for plotting.
  • data.vessels[].distance_nm to sort by “closest tug.”
  • data.vessels[].speed_knots and course_degrees to understand whether a tug is inbound or idle.
  • data.vessels[].name or MMSI as the primary label/selectable item.

Tip: Cache this list for 10–15 seconds in your backend if you’re running a wallboard to avoid spamming the API and to keep the UI smooth on refresh.

Step 2 — Get live track + route for a selected tug

Once a dispatcher clicks a specific tug, use GET /vessels/track to fetch its current position, optional route, and last port visits.

The following is the official, copy-pasteable example for a documented MMSI (use it as your implementation reference):

Official JSON response (unchanged):

What to use here:

  • data.current_position.latitude/longitude, speed_knots, and course_degrees power your live dot and vector.
  • data.route.* (if available) gives you context if the tug is on a specific move.
  • data.last_port_visits[] is useful to verify a tug’s recent operating area.

The hours parameter controls the lookback for position_history (up to 168). Keep it light (24–48) for fast UI loads; expand for analytics views when needed.

Port-side context: who’s arriving and how busy is the harbor?

For dispatch and berth planning, pair tug proximity with port event context. Two endpoints cover the essentials.

Expected and recent port traffic

Use GET /port/activity to build an event tape of arrivals and departures. This is the quickest way to flag that a deep-draft vessel is inbound and may need one or more tugs within the next hour.

Key fields:

  • data.arrivals[].arrival_time (UTC ISO 8601) to schedule windows.
  • data.arrivals[].from_port and data.departures[].to_port for routing context.
  • data.arrivals[].mmsi/name for correlation to tug assignments or pilotage requirements.

Alternatively, GET /port/expected-arrivals focuses on what’s inbound with ETAs and origin. Use this for your “Next 6 Hours” panel.

Instant port snapshot

Use GET /ports/data for a lightweight count of vessels currently in port and those expected, plus identifiers and timezone. This is handy for top-of-screen KPIs.

You’ll use data.vessels_in_port, data.vessels_expected, and the port’s timezone if you want to render local timestamps alongside the canonical UTC in the API.

Going from one tug to a fleet

If you dispatch multiple tugs across several terminals or anchorages, POST /vessels/fleet lets you query positions and routes in one round trip. This saves latency and simplifies polling.

Select mmsi or imo per vessel. The response packs overall fleet counts and per-vessel position/route objects you can map straight into cards on your dashboard.

Python and JavaScript examples you can paste

Below are minimal client calls for tug live track that mirror the official example MMSI and show how to extract the fields you’ll render.

Python (requests)

import os
import requests

API_KEY = os.getenv("VESSELS_API_KEY", "YOUR_API_KEY")
BASE = "https://vessels-api.com/api/V1"

def get_tug_track(mmsi: str, hours: int = 48):
url = f"{BASE}/vessels/track"
params = {"mmsi": mmsi, "hours": hours}
headers = {"X-API-Key": API_KEY}
r = requests.get(url, headers=headers, params=params, timeout=20)
r.raise_for_status()
payload = r.json()
if not payload.get("success"):
raise RuntimeError(payload.get("message", "Unknown error"))
d = payload["data"]
pos = d.get("current_position", {}) or {}
return {
"mmsi": d.get("vessel", {}).get("mmsi"),
"lat": pos.get("latitude"),
"lon": pos.get("longitude"),
"speed_kn": pos.get("speed_knots"),
"course_deg": pos.get("course_degrees"),
"ts_utc": pos.get("timestamp_utc"),
"route": d.get("route"),
"last_ports": d.get("last_port_visits", []),
}

if __name__ == "__main__":
data = get_tug_track("258785000", 48)
print(f"Tug {data['mmsi']} @ {data['lat']},{data['lon']} speed {data['speed_kn']} kn course {data['course_deg']}")

JavaScript (Node, fetch)

import fetch from "node-fetch";

const API_KEY = process.env.VESSELS_API_KEY || "YOUR_API_KEY";
const BASE = "https://vessels-api.com/api/V1";

async function getTugTrack(mmsi, hours = 48) {
const url = new URL(`${BASE}/vessels/track`);
url.searchParams.set("mmsi", mmsi);
url.searchParams.set("hours", String(hours));
const res = await fetch(url.toString(), {
headers: { "X-API-Key": API_KEY }
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const payload = await res.json();
if (!payload.success) {
throw new Error(payload.message || "API error");
}
const d = payload.data;
const pos = d.current_position || {};
return {
mmsi: d.vessel?.mmsi,
lat: pos.latitude,
lon: pos.longitude,
speedKn: pos.speed_knots,
courseDeg: pos.course_degrees,
tsUtc: pos.timestamp_utc,
route: d.route,
lastPorts: d.last_port_visits || []
};
}

getTugTrack("258785000", 48)
.then((t) => console.log(`Tug ${t.mmsi} at ${t.lat},${t.lon} ${t.speedKn} kn`))
.catch(console.error);

Search and filter: when you don’t know the MMSI

If your integration starts with a tugboat name or you’re reconciling a paper schedule, use GET /vessels/search. Fuzzy match on name or filter by type and flag. You’ll get pagination metadata to iterate through results.

Use data.vessels[].mmsi or imo from the results as inputs to /vessels/track or /vessels/fleet. Per_page caps at 100; carry forward pagination.current_page and last_page to navigate.

Operational patterns that save time in tug scenarios

  • Near real-time refresh: keep your vessels/nearby poll small (radius 10–20 NM, limit 50) and use incremental map updates. AIS age can vary; rely on timestamp_utc.
  • Sort by distance then speed: in most tug ops, “closest and moving” beats simply “closest.” Use distance_nm and speed_knots from /vessels/nearby.
  • UTC for logic, local for display: API timestamps are UTC ISO 8601. Convert to the port’s timezone (available from /ports or /ports/data) for on-site teams.
  • One API key, one auth path: always send X-API-Key. There’s no OAuth or per-endpoint auth differences to juggle.
  • Consistent envelope: your error handler can read status/success/message the same way on every endpoint.

Compliance and sustainability notes for harbor craft

Harbor tugs increasingly fall under ESG reporting programs. If you need efficiency scoring, GET /vessels/green returns an IMO CII view (A–E) over selectable periods. While tugboats have distinct operational profiles, this endpoint helps standardize reporting across mixed fleets that include tugs and line-haul vessels.

Use data.cii.rating and data.estimated_emissions fields in your ESG export alongside daily ops.

End-to-end tugboard: minimal data model

With the above endpoints, you can ship a single-page “tug near a port” board:

  1. GET /ports/data to populate header: port name, timezone, vessels_in_port, vessels_expected.
  2. GET /vessels/nearby (radius 10–15 NM, ship_type=Tug) to list available tugs.
  3. On select, GET /vessels/track to render live position and path.
  4. Side panel GET /port/activity to show inbound/outbound events for coordination.
  5. (Optional) If multiple tugs must be tracked, POST /vessels/fleet at a lower cadence (e.g., 15–30s) to refresh positions server-side and push to clients via websockets.

All requests share the same base URL: https://vessels-api.com/api/V1. If you’re building server-to-server, centralize the X-API-Key header and add a default timeout (~15–20 seconds) with sane retries on 500/429. Use backoff to stay well within plan quotas.

What sets this integration up for production

  • 18 REST endpoints cover the full surface area you need: search, live tracking, fleet ops, port intelligence, ESG/CII, and a premium real-time AIS feed.
  • Seven-day free trial on all plans lets you wire the board before you commit. It scales from a single tug yard tool to enterprise fleets.
  • Consistent JSON structures simplify your parsing and error handling.
  • Global AIS coverage and near real-time refresh rates allow you to extend from one port to many with the same code path.

FAQ

How often should I poll for a “near a port” display?
For wallboard UIs, 10–30 seconds for /vessels/nearby and 30–60 seconds for /port/activity is a practical starting point. Reduce the interval during peak windows or when the map view is idle.

What units are used for distances and speeds?
Distances are nautical miles (nm), speeds are knots, and coordinates are decimal degrees. Timestamps are UTC ISO 8601 strings.

Can I filter to only tugboats?
Yes. Pass ship_type in /vessels/nearby or /vessels/search when your taxonomy tags tugs as “Tug.” You can also filter client-side by vessel_type if returned.

How do I get multiple tugs in one response?
Use POST /vessels/fleet with a JSON body listing their imo or mmsi values. You can include_positions and include_routes to keep payloads compact or rich.

What does the response envelope look like if something goes wrong?
{status, success, message, data}. For example, a 401 returns success=false with a message explaining the invalid or missing X-API-Key. Handle 422 for parameter range issues (e.g., radius too large).

If you’re ready to build the “tugboat near a port” board, grab an API key and start with the track and nearby examples above. The quickest path is the official docs and interactive tools: Register, read the Documentation, or explore workflows in the MCP. Build the map, wire the events, and ship the ops view your harbor team actually uses.

Ready to get started?

Get your API key and start tracking vessels in minutes.

Get API Key