Class PolylineEncoding
- Namespace
- PolylineAlgorithm
- Assembly
- PolylineAlgorithm.dll
Provides methods for encoding and decoding polyline data, as well as utilities for normalizing and de-normalizing geographic coordinate values.
public static class PolylineEncodingInheritance
Inherited Members
Remarks
The PolylineAlgorithm.PolylineEncoding class includes functionality for working with encoded polyline data, such as reading and writing encoded values, as well as methods for normalizing and de-normalizing geographic coordinates. It also provides validation utilities to ensure values conform to expected ranges for latitude and longitude.
Methods
Denormalize(int, uint)
Converts a normalized integer coordinate value back to its floating-point representation based on the specified precision.
public static double Denormalize(int value, uint precision = 5)Parameters
valueint-
The integer value to denormalize. Typically produced by the PolylineAlgorithm.PolylineEncoding.Normalize(System.Double,System.UInt32) method.
precisionuint-
The number of decimal places used during normalization. Default is 5, matching standard polyline encoding precision.
Returns
- double
-
The denormalized floating-point coordinate value.
Remarks
This method reverses the normalization performed by PolylineAlgorithm.PolylineEncoding.Normalize(System.Double,System.UInt32). It takes an integer value and converts it
to a double by dividing it by 10 raised to the power of the specified precision. If precision is 0,
the value is returned as a double without division.
The calculation is performed inside a checked block to ensure that any arithmetic overflow is detected and an OverflowException is thrown.
For example, with a precision of 5:
- A value of 3778903 becomes 37.78903
- A value of -12241230 becomes -122.4123
If the input value is 0, the method returns 0.0 immediately.
Exceptions
- OverflowException
-
Thrown if the arithmetic operation overflows during conversion.
GetRequiredBufferSize(int)
Calculates the number of characters required to encode a delta value in polyline format.
public static int GetRequiredBufferSize(int delta)Parameters
deltaint-
The integer delta value to calculate the encoded size for. This value typically represents the difference between consecutive coordinate values in polyline encoding.
Returns
- int
-
The number of characters required to encode the specified delta value. The minimum return value is 1.
Remarks
This method determines how many characters will be needed to represent an integer delta value when encoded using the polyline encoding algorithm. It performs the same zigzag encoding transformation as PolylineAlgorithm.PolylineEncoding.TryWriteValue(System.Int32,System.Span{System.Char},System.Int32@) but only calculates the required buffer size without actually writing any data.
The calculation process:
- Applies zigzag encoding: left-shifts the value by 1 bit, then inverts all bits if the original value was negative
- Counts how many 5-bit chunks are needed to represent the encoded value
- Each chunk requires one character, with a minimum of 1 character for any value
This method is useful for pre-allocating buffers of the correct size before encoding polyline data, helping to avoid buffer overflow checks during the actual encoding process.
The method uses a long internally to prevent overflow during the left-shift operation on large negative values.
See Also
Normalize(double, uint)
Normalizes a geographic coordinate value to an integer representation based on the specified precision.
public static int Normalize(double value, uint precision = 5)Parameters
valuedouble-
The numeric value to normalize. Must be a finite number (not NaN or infinity).
precisionuint-
The number of decimal places of precision to preserve in the normalized value. The value is multiplied by 10^
precisionbefore rounding. Default is 5, which is standard for polyline encoding.
Returns
- int
-
An integer representing the normalized value. Returns
0if the inputvalueis0.0.
Remarks
This method converts a floating-point coordinate value into a normalized integer by multiplying it by 10 raised to the power of the specified precision, then truncating the result to an integer.
For example, with the default precision of 5:
- A value of 37.78903 becomes 3778903
- A value of -122.4123 becomes -12241230
The method validates that the input value is finite (not NaN or infinity) before performing normalization. If the precision is 0, the value is rounded without multiplication.
Exceptions
- ArgumentOutOfRangeException
-
Thrown when
valueis not a finite number (NaN or infinity). - OverflowException
-
Thrown when the normalized result exceeds the range of a 32-bit signed integer during the conversion from double to int.
TryReadValue(ref int, ReadOnlyMemory<char>, ref int)
Attempts to read an encoded integer value from a polyline buffer, updating the specified delta and position.
public static bool TryReadValue(ref int delta, ReadOnlyMemory<char> buffer, ref int position)Parameters
deltaint-
Reference to the integer accumulator that will be updated with the decoded value.
bufferReadOnlyMemory<char>-
The buffer containing polyline-encoded characters.
positionint-
Reference to the current position in the buffer. This value is updated as characters are read.
Returns
- bool
-
true if a value was successfully read and decoded; false if the buffer ended before a complete value was read.
Remarks
This method decodes a value from a polyline-encoded character buffer, starting at the given position. It reads
characters sequentially, applying the polyline decoding algorithm, and updates the delta with
the decoded value. The position is advanced as characters are processed.
The decoding process continues until a character with a value less than the algorithm's space constant is encountered, which signals the end of the encoded value. If the buffer is exhausted before a complete value is read, the method returns false.
The decoded value is added to delta using zigzag decoding, which handles both positive and negative values.
TryWriteValue(int, Span<char>, ref int)
Attempts to write an encoded integer value to a polyline buffer, updating the specified position.
public static bool TryWriteValue(int delta, Span<char> buffer, ref int position)Parameters
deltaint-
The integer value to encode and write to the buffer. This value typically represents the difference between consecutive coordinate values in polyline encoding.
bufferSpan<char>-
The destination buffer where the encoded characters will be written. Must have sufficient capacity to hold the encoded value.
positionint-
Reference to the current position in the buffer. This value is updated as characters are written to reflect the new position after encoding is complete.
Returns
- bool
-
true if the value was successfully encoded and written to the buffer; false if the buffer does not have sufficient remaining capacity to hold the encoded value.
Remarks
This method encodes an integer delta value into a polyline-encoded format and writes it to the provided character buffer, starting at the given position. It applies zigzag encoding followed by the polyline encoding algorithm to represent both positive and negative values efficiently.
The encoding process first converts the value using zigzag encoding (left shift by 1, with bitwise inversion for negative values), then writes it as a sequence of characters. Each character encodes 5 bits of data, with continuation bits indicating whether more characters follow. The position is advanced as characters are written.
Before writing, the method validates that sufficient space is available in the buffer by calling PolylineAlgorithm.PolylineEncoding.GetRequiredBufferSize(System.Int32). If the buffer does not have enough remaining capacity, the method returns false without modifying the buffer or position.
This method is the inverse of PolylineAlgorithm.PolylineEncoding.TryReadValue(System.Int32@,System.ReadOnlyMemory{System.Char},System.Int32@) and can be used to encode coordinate deltas for polyline serialization.
ValidateBlockLength(ReadOnlySpan<char>)
Validates the block structure of a polyline segment, ensuring each encoded value does not exceed 7 characters and the polyline ends correctly.
public static void ValidateBlockLength(ReadOnlySpan<char> polyline)Parameters
polylineReadOnlySpan<char>-
A span representing the polyline segment to validate.
Remarks
Iterates through the polyline, counting the length of each block (a sequence of characters representing an encoded value). Throws an ArgumentException if any block exceeds 7 characters or if the polyline does not end with a valid block terminator.
Exceptions
- ArgumentException
-
Thrown when a block exceeds 7 characters or the polyline does not end with a valid block terminator.
ValidateCharRange(ReadOnlySpan<char>)
Validates that all characters in the polyline segment are within the allowed ASCII range for polyline encoding.
public static void ValidateCharRange(ReadOnlySpan<char> polyline)Parameters
polylineReadOnlySpan<char>-
A span representing the polyline segment to validate.
Remarks
Uses SIMD vectorization for efficient validation of large spans. Falls back to scalar checks for any block where an invalid character is detected.
The valid range is from '?' (63) to '_' (95), inclusive. If an invalid character is found, an ArgumentException is thrown.
Exceptions
- ArgumentException
-
Thrown when an invalid character is found in the polyline segment.
ValidateFormat(ReadOnlySpan<char>)
Validates the format of a polyline segment, ensuring all characters are valid and block structure is correct.
public static void ValidateFormat(ReadOnlySpan<char> polyline)Parameters
polylineReadOnlySpan<char>-
A span representing the polyline segment to validate.
Remarks
This method performs two levels of validation on the provided polyline segment:
- Character Range Validation: Checks that every character in the polyline is within the valid ASCII range for polyline encoding ('?' [63] to '_' [95], inclusive). Uses SIMD acceleration for efficient validation of large segments.
- Block Structure Validation: Ensures that each encoded value (block) does not exceed 7 characters and that the polyline ends with a valid block terminator.
If an invalid character or block structure is detected, an ArgumentException is thrown with details about the error.
Exceptions
- ArgumentException
-
Thrown when an invalid character is found or the block structure is invalid.