maps project: design, survey, mock app, and route-aware planning backend
- DESIGN.md: full design incl. driving-trip requirements (R1-R4), stays model, focus mode, mobile, provenance rules - SURVEY.md: open-source landscape - mock/: interaction mock (Florence itinerary, focus mode, stays, region stops, mobile layout) - router/: Go module (stdlib-only) with Router interface (Valhalla + OSRM backends), stop_cost, optimize_stops, corridor, routectl CLI, bench (5 real NE-corridor tasks, 26 checks passing), integration tests, and setup-osrm.sh for the self-hosted router - osm/: NH+MA+CT+NY PBFs (gitignored) + setup artifacts
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"maps/router/internal/geo"
|
||||
)
|
||||
|
||||
// OSRM is a client for a local OSRM backend (osrm-routed), e.g.
|
||||
// http://localhost:5000. Returns full route geometry.
|
||||
type OSRM struct {
|
||||
BaseURL string
|
||||
HTTP *http.Client
|
||||
profile string
|
||||
name string
|
||||
}
|
||||
|
||||
func NewOSRM(baseURL string) *OSRM {
|
||||
return &OSRM{
|
||||
BaseURL: baseURL,
|
||||
HTTP: &http.Client{Timeout: 60 * time.Second},
|
||||
profile: "driving",
|
||||
name: "osrm(" + baseURL + ")",
|
||||
}
|
||||
}
|
||||
|
||||
func (o *OSRM) Name() string { return o.name }
|
||||
|
||||
func (o *OSRM) osrmProfile(p Profile) string {
|
||||
if p == ProfileWalk {
|
||||
return "walking"
|
||||
}
|
||||
return "driving"
|
||||
}
|
||||
|
||||
type osrmRoute struct {
|
||||
Code string `json:"code"`
|
||||
Distance float64 `json:"distance"`
|
||||
Duration float64 `json:"duration"`
|
||||
Legs []struct {
|
||||
Distance float64 `json:"distance"`
|
||||
Duration float64 `json:"duration"`
|
||||
} `json:"legs"`
|
||||
Geometry string `json:"geometry"`
|
||||
}
|
||||
|
||||
func (o *OSRM) Route(ctx context.Context, profile Profile, pts []geo.Point) (*Route, error) {
|
||||
if len(pts) < 2 {
|
||||
return nil, fmt.Errorf("osrm: need >= 2 points, got %d", len(pts))
|
||||
}
|
||||
var coords []string
|
||||
for _, p := range pts {
|
||||
coords = append(coords, fmt.Sprintf("%.6f,%.6f", p.Lon, p.Lat))
|
||||
}
|
||||
u := fmt.Sprintf("%s/route/v1/%s/%s?overview=false&alternatives=false&geometries=geojson",
|
||||
o.BaseURL, o.osrmProfile(profile), strings.Join(coords, ";"))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := o.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var or osrmRoute
|
||||
if err := json.NewDecoder(resp.Body).Decode(&or); err != nil {
|
||||
return nil, fmt.Errorf("osrm: bad response: %w", err)
|
||||
}
|
||||
if or.Code != "Ok" {
|
||||
return nil, fmt.Errorf("osrm: %s", or.Code)
|
||||
}
|
||||
out := &Route{Duration: or.Duration, Distance: or.Distance}
|
||||
for _, l := range or.Legs {
|
||||
out.Legs = append(out.Legs, Leg{Duration: l.Duration, Distance: l.Distance})
|
||||
}
|
||||
// OSRM geometries=geojson returns a GeoJSON LineString.
|
||||
var gj struct {
|
||||
Geometry struct {
|
||||
Coords [][]float64 `json:"coordinates"`
|
||||
} `json:"geometry"`
|
||||
}
|
||||
if or.Geometry != "" && json.Unmarshal([]byte(or.Geometry), &gj) == nil {
|
||||
for _, c := range gj.Geometry.Coords {
|
||||
out.Geometry = append(out.Geometry, geo.Point{Lat: c[1], Lon: c[0]})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// OSRMTable builds a matrix via the OSRM table service (one call) when
|
||||
// available; the generic BuildMatrix (pairwise) works on any backend.
|
||||
func (o *OSRM) Table(ctx context.Context, profile Profile, pts []geo.Point) (Matrix, error) {
|
||||
var coords []string
|
||||
for _, p := range pts {
|
||||
coords = append(coords, fmt.Sprintf("%.6f,%.6f", p.Lon, p.Lat))
|
||||
}
|
||||
u := fmt.Sprintf("%s/table/v1/%s/%s?annotations=duration",
|
||||
o.BaseURL, o.osrmProfile(profile), strings.Join(coords, ";"))
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
resp, err := o.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var tr struct {
|
||||
Code string `json:"code"`
|
||||
Durations [][]float64 `json:"durations"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&tr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tr.Code != "Ok" {
|
||||
return nil, fmt.Errorf("osrm table: %s", tr.Code)
|
||||
}
|
||||
m := make(Matrix, len(pts))
|
||||
for i := range m {
|
||||
m[i] = make([]float64, len(pts))
|
||||
for j := range m[i] {
|
||||
if tr.Durations[i][j] > 0 {
|
||||
m[i][j] = tr.Durations[i][j]
|
||||
} else {
|
||||
m[i][j] = -1
|
||||
}
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
var _ = url.Values{} // keep net/url import for future query building
|
||||
@@ -0,0 +1,126 @@
|
||||
// Package route defines the Router interface and the two backends:
|
||||
// a hosted Valhalla (works today, no geometry) and local OSRM
|
||||
// (full geometry, self-hosted — see scripts/setup-osrm.sh).
|
||||
//
|
||||
// Design rule (DESIGN.md R1/R4): the route is computed, never narrated.
|
||||
// Every Duration/Distance value returned here is `computed` provenance.
|
||||
package route
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"maps/router/internal/geo"
|
||||
)
|
||||
|
||||
// Profile is the routing profile.
|
||||
type Profile string
|
||||
|
||||
const (
|
||||
ProfileDrive Profile = "drive"
|
||||
ProfileWalk Profile = "walk"
|
||||
)
|
||||
|
||||
// Route is the result of routing through an ordered set of points.
|
||||
type Route struct {
|
||||
// Duration is total travel time in seconds (computed by the router).
|
||||
Duration float64
|
||||
// Distance is total path length in meters.
|
||||
Distance float64
|
||||
// BBox is the bounding box of the routed path (from the router's
|
||||
// summary). Zero values if the backend doesn't provide one.
|
||||
BBox BBox
|
||||
// Geometry is the routed polyline. May be nil for backends that
|
||||
// don't return it (hosted Valhalla) — callers must degrade
|
||||
// gracefully (chord corridor, flagged low-confidence).
|
||||
Geometry []geo.Point
|
||||
// Legs holds per-segment durations for multi-point routes.
|
||||
// len(Legs) == len(points)-1 when present.
|
||||
Legs []Leg
|
||||
}
|
||||
|
||||
// Leg is one segment between consecutive waypoints.
|
||||
type Leg struct {
|
||||
Duration float64 // seconds
|
||||
Distance float64 // meters
|
||||
}
|
||||
|
||||
// BBox is a latitude/longitude bounding box in degrees.
|
||||
type BBox struct {
|
||||
MinLat, MaxLat, MinLon, MaxLon float64
|
||||
}
|
||||
|
||||
// Empty reports whether the box is unset.
|
||||
func (b BBox) Empty() bool { return b == BBox{} }
|
||||
|
||||
// DistMeters is the minimum distance from p to the box (0 if inside).
|
||||
func (b BBox) DistMeters(p geo.Point) float64 {
|
||||
dLat, dLon := 0.0, 0.0
|
||||
if p.Lat < b.MinLat {
|
||||
dLat = b.MinLat - p.Lat
|
||||
} else if p.Lat > b.MaxLat {
|
||||
dLat = p.Lat - b.MaxLat
|
||||
}
|
||||
if p.Lon < b.MinLon {
|
||||
dLon = b.MinLon - p.Lon
|
||||
} else if p.Lon > b.MaxLon {
|
||||
dLon = p.Lon - b.MaxLon
|
||||
}
|
||||
if dLat == 0 && dLon == 0 {
|
||||
return 0
|
||||
}
|
||||
mLat := dLat * 111190.0
|
||||
mLon := dLon * 111190.0 * math.Cos(rad(p.Lat))
|
||||
return math.Hypot(mLat, mLon)
|
||||
}
|
||||
|
||||
func rad(d float64) float64 { return d * math.Pi / 180 }
|
||||
|
||||
// Router is the backend interface.
|
||||
type Router interface {
|
||||
// Route routes through pts in order and returns the combined trip.
|
||||
Route(ctx context.Context, profile Profile, pts []geo.Point) (*Route, error)
|
||||
// Name identifies the backend in reports ("valhalla-hosted", "osrm-local").
|
||||
Name() string
|
||||
}
|
||||
|
||||
// Matrix builds a full origin-destination matrix over pts using the
|
||||
// router. m[i][j] is seconds; -1 means unroutable. Built with pairwise
|
||||
// two-point Route calls — the single code path that works on both
|
||||
// backends (Valhalla's sources_to_targets is capped at 150 km).
|
||||
type Matrix [][]float64
|
||||
|
||||
func (m Matrix) From(i, j int) float64 { return m[i][j] }
|
||||
|
||||
// BuildMatrix computes the matrix with a small politeness delay between
|
||||
// calls when polite > 0 (hosted endpoints).
|
||||
func BuildMatrix(ctx context.Context, r Router, profile Profile, pts []geo.Point, polite time.Duration) (Matrix, error) {
|
||||
n := len(pts)
|
||||
m := make(Matrix, n)
|
||||
for i := range m {
|
||||
m[i] = make([]float64, n)
|
||||
m[i][i] = 0
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
for j := 0; j < n; j++ {
|
||||
if i == j {
|
||||
continue
|
||||
}
|
||||
if polite > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(polite):
|
||||
}
|
||||
}
|
||||
rr, err := r.Route(ctx, profile, []geo.Point{pts[i], pts[j]})
|
||||
if err != nil {
|
||||
m[i][j] = -1
|
||||
continue
|
||||
}
|
||||
m[i][j] = rr.Duration
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"maps/router/internal/geo"
|
||||
)
|
||||
|
||||
// Valhalla is a client for a Valhalla routing API
|
||||
// (e.g. the hosted https://valhalla1.openstreetmap.de or a self-hosted
|
||||
// valhalla instance). Note: hosted instances strip route geometry, so
|
||||
// Route.Geometry will be nil.
|
||||
type Valhalla struct {
|
||||
BaseURL string
|
||||
HTTP *http.Client
|
||||
name string
|
||||
}
|
||||
|
||||
func NewValhalla(baseURL string) *Valhalla {
|
||||
return &Valhalla{
|
||||
BaseURL: baseURL,
|
||||
HTTP: &http.Client{Timeout: 60 * time.Second},
|
||||
name: "valhalla(" + baseURL + ")",
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Valhalla) Name() string { return v.name }
|
||||
|
||||
func (v *Valhalla) costing(p Profile) string {
|
||||
if p == ProfileWalk {
|
||||
return "pedestrian"
|
||||
}
|
||||
return "auto"
|
||||
}
|
||||
|
||||
type vLocation struct {
|
||||
Lat float64 `json:"lat"`
|
||||
Lon float64 `json:"lon"`
|
||||
}
|
||||
|
||||
type vRouteReq struct {
|
||||
Locations []vLocation `json:"locations"`
|
||||
Costing string `json:"costing"`
|
||||
Polyline bool `json:"polyline"`
|
||||
}
|
||||
|
||||
type vLeg struct {
|
||||
Summary struct {
|
||||
Time float64 `json:"time"`
|
||||
Length float64 `json:"length"` // km
|
||||
} `json:"summary"`
|
||||
}
|
||||
|
||||
type vTrip struct {
|
||||
Summary struct {
|
||||
Time float64 `json:"time"`
|
||||
Length float64 `json:"length"` // km
|
||||
MinLat float64 `json:"min_lat"`
|
||||
MaxLat float64 `json:"max_lat"`
|
||||
MinLon float64 `json:"min_lon"`
|
||||
MaxLon float64 `json:"max_lon"`
|
||||
} `json:"summary"`
|
||||
Legs []vLeg `json:"legs"`
|
||||
}
|
||||
|
||||
type vResp struct {
|
||||
Trip vTrip `json:"trip"`
|
||||
Message string `json:"message"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func (v *Valhalla) Route(ctx context.Context, profile Profile, pts []geo.Point) (*Route, error) {
|
||||
if len(pts) < 2 {
|
||||
return nil, fmt.Errorf("route: need >= 2 points, got %d", len(pts))
|
||||
}
|
||||
req := vRouteReq{Costing: v.costing(profile), Polyline: true}
|
||||
for _, p := range pts {
|
||||
req.Locations = append(req.Locations, vLocation{p.Lat, p.Lon})
|
||||
}
|
||||
body, _ := json.Marshal(req)
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, v.BaseURL+"/route", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
resp, err := v.HTTP.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 20<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var vr vResp
|
||||
if err := json.Unmarshal(raw, &vr); err != nil {
|
||||
return nil, fmt.Errorf("valhalla: bad response (%s): %q", resp.Status, string(raw[:min(len(raw), 200)]))
|
||||
}
|
||||
if vr.Message != "" {
|
||||
return nil, fmt.Errorf("valhalla: %s", vr.Message)
|
||||
}
|
||||
if vr.Error != "" {
|
||||
return nil, fmt.Errorf("valhalla: %s", vr.Error)
|
||||
}
|
||||
out := &Route{
|
||||
Duration: vr.Trip.Summary.Time,
|
||||
Distance: vr.Trip.Summary.Length * 1000,
|
||||
BBox: BBox{
|
||||
MinLat: vr.Trip.Summary.MinLat, MaxLat: vr.Trip.Summary.MaxLat,
|
||||
MinLon: vr.Trip.Summary.MinLon, MaxLon: vr.Trip.Summary.MaxLon,
|
||||
},
|
||||
}
|
||||
for _, l := range vr.Trip.Legs {
|
||||
out.Legs = append(out.Legs, Leg{Duration: l.Summary.Time, Distance: l.Summary.Length * 1000})
|
||||
}
|
||||
// Geometry: decode encoded polyline if the instance returns it.
|
||||
if pl, ok := decodePolylineField(raw); ok {
|
||||
out.Geometry = pl
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// decodePolylineField checks for trip.polyline (encoded polyline v0) —
|
||||
// hosted instances omit it; self-hosted valhalla with "polyline":true
|
||||
// returns it.
|
||||
func decodePolylineField(raw []byte) ([]geo.Point, bool) {
|
||||
var probe struct {
|
||||
Trip struct {
|
||||
Polyline string `json:"polyline"`
|
||||
} `json:"trip"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &probe); err != nil || probe.Trip.Polyline == "" {
|
||||
return nil, false
|
||||
}
|
||||
return decodePolyline(probe.Trip.Polyline), true
|
||||
}
|
||||
|
||||
// decodePolyline decodes a Google encoded polyline (precision 1e-5 or 1e-6).
|
||||
func decodePolyline(s string) []geo.Point {
|
||||
var pts []geo.Point
|
||||
lat, lon := 0, 0
|
||||
i := 0
|
||||
for i < len(s) {
|
||||
var dlat, dlon int
|
||||
shift := 0
|
||||
for {
|
||||
b := int(s[i]) - 63
|
||||
i++
|
||||
dlat |= (b & 0x1f) << shift
|
||||
if b&0x20 == 0 {
|
||||
break
|
||||
}
|
||||
shift += 5
|
||||
}
|
||||
shift = 0
|
||||
for {
|
||||
b := int(s[i]) - 63
|
||||
i++
|
||||
dlon |= (b & 0x1f) << shift
|
||||
if b&0x20 == 0 {
|
||||
break
|
||||
}
|
||||
shift += 5
|
||||
}
|
||||
lat += dlat&1 ^ dlat>>1
|
||||
lon += dlon&1 ^ dlon>>1
|
||||
pts = append(pts, geo.Point{Lat: float64(lat) / 1e5, Lon: float64(lon) / 1e5})
|
||||
}
|
||||
return pts
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
Reference in New Issue
Block a user