Linear Referencing in ArcGIS with Python: Routes, Measures, Events and the LRS REST API

This post covers linear referencing in ArcGIS from a developer's side: the concepts you need (routes, measures, calibration points, events, time and networks), Python that calls the LRS REST operations with requests, and ArcPy that builds routes and places events. It also says which parts need the paid extension and which are in every ArcGIS Pro license.

First, the product names

Older articles and forum posts mention ArcGIS Roads and Highways and ArcGIS Pipeline Referencing. These were two industry versions of one engine, ArcGIS Location Referencing. The ArcGIS Pro 3.8 "What's new" page says the two were merged into one extension named ArcGIS Linear Referencing. At 3.8 the Location Referencing tab on the ribbon became the Linear Referencing tab, and the tools in the Location Referencing toolbox moved into the Linear Referencing toolbox.

For scripts, that move changes the namespace. Before 3.8 the extension tools were called as arcpy.locref.AppendEvents, arcpy.locref.GenerateRoutes and so on. From 3.8 the tool reference lists them as arcpy.lr.AppendEvents, arcpy.lr.GenerateRoutes, next to tools like arcpy.lr.CreateRoutes that have been part of core ArcGIS Pro for many years. As a result, the namespace no longer tells you whether a tool needs the extension. Each tool page has a Licensing section, and it is the only reliable guide. This post uses the 3.8 names. On 3.7 or earlier, use arcpy.locref for the extension tools.

The concepts

Route I90 (routeId), measures in miles Line event: pavement, fromMeasure 2.0 to toMeasure 5.5 012345678910 CP 0CP 4.2CP 10 Point event: crash, measure 6.3, offset 15 m Black line: route polyline with M values. Green triangles: calibration points (known measures). Events store routeId + measure(s); their geometry is derived from the route.

A route measured 0 to 10 miles, with calibration points, a point event at 6.3 and a line event from 2.0 to 5.5.

Routes and measures

A route is a polyline with an ID, such as I90, whose vertices carry an M value (a measure) as well as X and Y. The measure is a distance along the route in whatever unit the business uses: miles from the state line, kilometre posts, or engineering stationing on a pipe. Linear referencing then lets you say "route I90, measure 25.0" instead of giving a coordinate.

Calibration points

Digitised geometry rarely matches posted mileage exactly. Calibration points are points with a route ID and a known measure, for example surveyed mileposts. Measures on the route are adjusted to agree with them, and values between points are interpolated. In the diagram the route is pinned at 0.0, 4.2 and 10.0.

Events

An event is a business record located by route and measure, not by geometry. A point event has one measure (a crash at 6.3). A line event has a from and to measure (pavement condition from 2.0 to 5.5). The geometry is derived from the route when needed, so if the route is recalibrated the events move with it. Events can also carry an offset, the perpendicular distance from the centerline.

Time-aware LRS

In an LRS managed with the extension, routes, calibration points and events have FromDate and ToDate fields. Edits do not overwrite history. When a route is recalibrated, the old version is retired on the edit date and a new time slice begins. A null ToDate means the record is still current. Queries take a temporal view date, so you can ask where measure 25 on I90 was on 1 January 2020. Configurable event behaviours (Stay Put, Move, Retire and others) decide what happens to events when the route under them is edited.

Networks

An LRS network is a set of routes measured with one linear referencing method. The same road can be on a county-milepost network and on a statewide network at once. The documentation also describes line networks, where several routes make up one line, and derived networks, built from a line network so that each line becomes one continuously measured route. A measure on one network can be translated to the matching location on another. The REST translate operation below does exactly that.

Calling the LRS REST service from Python

When an LRS is published from ArcGIS Pro to ArcGIS Enterprise with linear referencing enabled, the map service gets an LRServer extension at .../MapServer/exts/LRServer. Each network is a resource under networkLayers/<id>. The REST reference says the ArcGIS Linear Referencing license is required for this resource. It documents three conversion operations on a network layer:

  • measureToGeometry: locations as a JSON array of {"routeId", "measure"} or {"routeId", "fromMeasure", "toMeasure"}, plus optional temporalViewDate, outSR and gdbVersion.
  • geometryToMeasure: locations as {"geometry": {"x", "y"}} with an optional routeId, plus tolerance (in map units, ignored when a route ID is given), inSR, outSR and temporalViewDate.
  • translate: locations as above and targetNetworkLayerIds, a JSON array of network IDs.

All three are GET requests, and temporalViewDate is epoch milliseconds in UTC:

import json
import os
from datetime import datetime, timezone

import requests

# Map service with the LRServer extension enabled
LRS_URL = os.environ.get(
    "LRS_URL",
    "https://gis.example.com/server/rest/services/MyLRS/MapServer/exts/LRServer",
)
TOKEN = os.environ.get("ARCGIS_TOKEN")  # None for an unsecured service


class LrsError(Exception):
    pass


def to_epoch_ms(dt):
    """temporalViewDate is milliseconds since the epoch, UTC."""
    return int(dt.astimezone(timezone.utc).timestamp() * 1000)


def lrs_call(network_id, operation, **params):
    url = f"{LRS_URL}/networkLayers/{network_id}/{operation}"
    query = {"f": "json"}
    for key, value in params.items():
        if value is None:
            continue
        # lists and dicts go over the wire as JSON text
        query[key] = json.dumps(value) if isinstance(value, (list, dict)) else value
    if TOKEN:
        query["token"] = TOKEN
    resp = requests.get(url, params=query, timeout=30)
    resp.raise_for_status()
    body = resp.json()
    # ArcGIS REST reports most failures as HTTP 200 with an "error" object
    if "error" in body:
        err = body["error"]
        raise LrsError(f"{operation}: {err.get('code')} {err.get('message')} {err.get('details')}")
    return body


def measure_to_geometry(network_id, locations, view_date=None, out_sr=None):
    return lrs_call(
        network_id,
        "measureToGeometry",
        locations=locations,
        temporalViewDate=to_epoch_ms(view_date) if view_date else None,
        outSR=out_sr,
    )


def geometry_to_measure(network_id, points, tolerance, in_sr, view_date=None):
    locations = [{"geometry": {"x": x, "y": y}} for x, y in points]
    return lrs_call(
        network_id,
        "geometryToMeasure",
        locations=locations,
        tolerance=tolerance,
        inSR=in_sr,
        temporalViewDate=to_epoch_ms(view_date) if view_date else None,
    )


def translate(network_id, locations, target_ids, view_date=None):
    return lrs_call(
        network_id,
        "translate",
        locations=locations,
        targetNetworkLayerIds=target_ids,
        temporalViewDate=to_epoch_ms(view_date) if view_date else None,
    )


if __name__ == "__main__":
    view = datetime(2026, 1, 1, tzinfo=timezone.utc)

    # 1. Route + measure -> point and line geometry
    r = measure_to_geometry(
        0,
        [
            {"routeId": "I90", "measure": 25},
            {"routeId": "I90", "fromMeasure": 25.1, "toMeasure": 26.8},
        ],
        view_date=view,
        out_sr=102100,
    )
    for loc in r["locations"]:
        print(loc["routeId"], loc["status"], loc["geometryType"])

    # 2. Coordinates -> route + measure (each input point can match several routes)
    r = geometry_to_measure(0, [(-8479115, 5326520)], tolerance=50, in_sr=102100)
    for loc in r["locations"]:
        if loc["status"] != "esriLocatingOK":
            print("not located:", loc["status"])
            continue
        for hit in loc["results"]:
            print(hit["routeId"], round(hit["measure"], 3), "offset", hit["distance"])

    # 3. Measure on one network -> measure on other networks
    r = translate(0, [{"routeId": "I90", "measure": 25}], target_ids=[4, 7])
    for loc in r["locations"]:
        for t in loc["translatedLocations"]:
            print("network", t["networkLayerId"], t["routeId"], t.get("measure"))

Things to notice:

  • JSON in query strings. locations and targetNetworkLayerIds are JSON text inside a query parameter, so the helper runs lists and dicts through json.dumps and lets requests URL-encode the result. None parameters are dropped so the server defaults apply.
  • Errors come back as HTTP 200. ArcGIS REST endpoints usually report a failed operation as a normal 200 response whose body is {"error": {"code": ..., "message": ..., "details": [...]}}. raise_for_status() will not catch that, so the helper checks for the error key itself.
  • Per-location status. A request can succeed while individual locations fail. Each entry has a status such as esriLocatingOK, esriLocatingCannotFindRoute or esriLocatingCannotFindLocation. Check it before reading the geometry or measure.
  • Response shapes differ. measureToGeometry puts geometry directly on each location (x/y for points, paths for lines). geometryToMeasure nests a results array inside each location, because a point near an interchange can match several routes. Each result carries routeId, measure and distance, the offset from the route. translate returns translatedLocations with one entry per target network and route.
  • Token. The token comes from an environment variable, so it is never hard-coded.

I ran this client against a standard-library mock server that returns the response shapes from the REST reference examples, including one HTTP 200 error body.

Core linear referencing with ArcPy

You do not need the extension to work with measured routes. The Linear Referencing toolbox has been in ArcGIS Pro at every license level for a long time. The tool pages for CreateRoutes, CalibrateRoutes, LocateFeaturesAlongRoutes and MakeRouteEventLayer all list Basic: Yes. They work on ordinary feature classes and tables, with no time awareness or LRS management.

from collections import Counter

import arcpy

arcpy.env.workspace = r"C:\gis\lrs_demo\roads.gdb"
arcpy.env.overwriteOutput = True

# 1. Build measured routes from centerline pieces that carry from/to mileage
arcpy.lr.CreateRoutes(
    in_line_features="centerlines",
    route_id_field="ROUTE_ID",
    out_feature_class="routes",
    measure_source="TWO_FIELDS",
    from_measure_field="FROM_MI",
    to_measure_field="TO_MI",
)

# 2. Adjust route measures to surveyed milepost points (calibration points)
arcpy.lr.CalibrateRoutes(
    in_route_features="routes",
    route_id_field="ROUTE_ID",
    in_point_features="mileposts",
    point_id_field="ROUTE_ID",
    measure_field="MILEPOST",
    out_feature_class="routes_cal",
    calibrate_method="DISTANCE",
    search_radius="10 Meters",
    interpolate_between="BETWEEN",
    extrapolate_before="BEFORE",
    extrapolate_after="AFTER",
)

# 3. Crash points with only x/y -> event table with ROUTE_ID and MEAS
arcpy.lr.LocateFeaturesAlongRoutes(
    in_features="crashes",
    in_routes="routes_cal",
    route_id_field="ROUTE_ID",
    radius_or_tolerance="15 Meters",
    out_table="crash_events",
    out_event_properties="ROUTE_ID POINT MEAS",
    route_locations="FIRST",
    distance_field="DISTANCE",
)

# 4. A pavement table that only has route + from/to measures -> drawable lines
arcpy.lr.MakeRouteEventLayer(
    in_routes="routes_cal",
    route_id_field="ROUTE_ID",
    in_table="pavement_condition",
    in_event_properties="ROUTE_ID LINE FROM_MI TO_MI",
    out_layer="pavement_lyr",
    add_error_field="ERROR_FIELD",
)

# Tally the LOC_ERROR values so failed placements are visible before export
with arcpy.da.SearchCursor("pavement_lyr", ["LOC_ERROR"]) as cur:
    print(Counter(row[0] for row in cur))

arcpy.management.CopyFeatures("pavement_lyr", "pavement_segments")

The steps:

  1. CreateRoutes merges centerline pieces that share ROUTE_ID into one M-aware polyline. TWO_FIELDS takes measures from the from/to fields. LENGTH would use the geometry length, and ONE_FIELD a single length field.
  2. CalibrateRoutes adjusts the measures to the milepost points within the search radius. BETWEEN, BEFORE and AFTER control interpolation and extrapolation outside the first and last point.
  3. LocateFeaturesAlongRoutes goes from geometry to measure. The output event properties string "ROUTE_ID POINT MEAS" names the route ID field, the event type and the measure field. It is the batch, desktop counterpart of geometryToMeasure.
  4. MakeRouteEventLayer goes from measure to geometry. It builds a temporary layer from a table with route IDs and from/to measures. ERROR_FIELD adds LOC_ERROR, which records why a row could not be placed. The script tallies those values before copying the layer out.

LRS editing with the Linear Referencing extension

Managing a time-aware LRS needs the extension. That covers registered networks and events, conflict prevention, event behaviours on route edits, and the REST service above. The tool pages for AppendEvents, GenerateRoutes and AppendCalibrationPoints list "Requires ArcGIS Linear Referencing" at every license level. A typical scripted job loads a batch of event records from a staging table and then regenerates routes after edits:

import arcpy

# Requires the ArcGIS Linear Referencing extension (ArcGIS Pro 3.8+).
# On Pro 3.7 and earlier the same tools are arcpy.locref.* and need the
# Location Referencing license (Roads and Highways or Pipeline Referencing).

LRS_GDB = r"C:\gis\lrs_demo\lrs.gdb"
target_event = LRS_GDB + r"\LRSE_SpeedLimit"   # registered LRS line event
network = LRS_GDB + r"\LRSN_Route"             # LRS network
source = r"C:\gis\lrs_demo\staging.gdb\speed_limit_updates"

# Target event field -> staging table field (use your event's registered names)
mapping = {
    "RouteId": "ROUTE_ID",
    "FromMeasure": "BEGIN_MI",
    "ToMeasure": "END_MI",
    "FromDate": "EFFECTIVE",
    "SpeedLimit": "MPH",
}

fms = arcpy.FieldMappings()
for target_field, source_field in mapping.items():
    fm = arcpy.FieldMap()
    fm.addInputField(source, source_field)
    out = fm.outputField
    out.name = target_field
    fm.outputField = out
    fms.addFieldMap(fm)

try:
    # RETIRE_OVERLAPS (line events only): existing target records that the new
    # ones overlap are retired; records fully eclipsed by a new one are deleted
    arcpy.lr.AppendEvents(
        in_dataset=source,
        in_target_event=target_event,
        field_mapping=fms,
        load_type="RETIRE_OVERLAPS",
        generate_event_ids="GENERATE_EVENT_IDS",
    )
    # After centerline/calibration edits, rebuild route shapes and measures
    arcpy.lr.GenerateRoutes(in_route_features=network)
except arcpy.ExecuteError:
    print(arcpy.GetMessages(2))
    raise
  • Field mapping. The target event's schema is fixed, so the mapping only says which source field feeds which target field. The field names here are placeholders; use the ones your event was registered with.
  • Load type. ADD appends without touching existing records. RETIRE_OVERLAPS (line events only) retires target records that overlap the new ones, and the tool page says target records fully eclipsed by a new one are deleted. There are also RETIRE_BY_EVENT_ID and REPLACE_BY_EVENT_ID.
  • Dates. If neither date is mapped, the event takes the start date of the route's active time slice. Mapping ToDate without FromDate is an error.
  • GenerateRoutes rebuilds route shapes and measures after centerline or calibration point edits. The tool page shows it running against a feature service as well, after arcpy.SignInToPortal. It recommends working in a branch version and posting to default.

The ArcPy geoprocessing post covers running scripts with propy.bat and handling arcpy.ExecuteError.

Which piece to use

Core arcpy.lr tools suit analysis and mapping of measure tables. The extension suits an LRS that is the system of record, with history and several editors. The REST operations suit other systems, such as web apps or ETL jobs, that need coordinate-to-measure conversion without ArcGIS Pro.

Summary

  • At ArcGIS Pro 3.8, Roads and Highways and Pipeline Referencing became the ArcGIS Linear Referencing extension, and its tools moved from arcpy.locref to arcpy.lr. Check each tool's Licensing section, not the namespace.
  • Routes carry measures. Calibration points tie measures to known positions. Events are records addressed by route and measure. A managed LRS adds dates, a temporal view date and several networks.
  • The LRServer operations measureToGeometry, geometryToMeasure and translate are GET calls with JSON parameters. Check the error body and each location's status.
  • Route building and event placement tools are core at Basic. LRS management tools such as AppendEvents and GenerateRoutes need the extension.

Comments

Popular posts from this blog

My Cloud Notes

My CSharp Notes