如何通过Valhalla Turn-by-Turn Route API获取完整路线的Polyline?
Great question! Let's break this down into two key parts: whether there's a direct API parameter to get a unified full-route polyline, and if not, how to merge leg polylines correctly.
Is there a built-in parameter for a full route polyline?
Valhalla's Turn-by-Turn API doesn't currently include a native parameter that returns a single, encoded polyline for the entire trip across all legs. The API is designed to split routes into legs based on your input waypoints, so each leg gets its own separate encoded shape by default.
How to merge leg polylines manually
Merging the leg shapes is a reliable workaround, and it only takes three simple steps. Here's how to do it in most programming languages:
Step 1: Decode each leg's encoded polyline
First, you'll need to convert each leg's encoded polyline string into a list of latitude/longitude coordinate pairs. There are dedicated libraries for this in almost every language:
- JavaScript: Use
@mapbox/polyline - Python: Use the
polylinePyPI package - Java/Kotlin: Use Google's
PolyUtilclass - C#: Use
NetTopologySuiteor a similar GIS library
Example Python code for decoding:
import polyline # Decode a single leg's shape leg_coordinates = polyline.decode(leg["shape"])
Step 2: Merge coordinate lists without duplicates
Each leg's first coordinate is identical to the previous leg's last coordinate (since legs connect at your waypoints). To avoid duplicate points in the full route:
- Start with the full coordinate list from the first leg
- For every subsequent leg, append all coordinates except the first one to the full list
Step 3: Re-encode the merged coordinates
Once you have a single, ordered list of coordinates for the entire route, re-encode it back into an encoded polyline string using the same library you used for decoding.
Full Python example for merging:
import polyline # Assume `legs` is the list of legs from your Valhalla API response full_route_coords = [] for index, leg in enumerate(legs): leg_coords = polyline.decode(leg["shape"]) if index == 0: # Add all coordinates from the first leg full_route_coords.extend(leg_coords) else: # Skip the first coordinate (duplicate of previous leg's last point) full_route_coords.extend(leg_coords[1:]) # Encode the merged coordinates into a single polyline full_route_polyline = polyline.encode(full_route_coords)
Pro Tips
- Ensure you use the same polyline format for decoding/encoding: Valhalla lets you specify
shape_formatin your request (valid values:polyline,polyline6,geojson). Stick with one format to avoid errors. - If you request GeoJSON shapes instead of encoded polylines, merging is even simpler: just concatenate the
coordinatesarrays of each leg'sgeometry, skipping the first coordinate of each subsequent leg.
内容的提问来源于stack exchange,提问作者Nane Petrosyan

