osm

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 31, 2025 License: MIT Imports: 11 Imported by: 0

README

OSM Package

This package provides common utilities for working with OpenStreetMap data in the osmmcp project.

Overview

The osm package contains reusable components for interacting with OpenStreetMap services and data. It centralizes various constants, data structures, and utility functions to ensure consistency across the codebase and reduce duplication.

Components

Constants
  • NominatimBaseURL - Base URL for Nominatim geocoding service
  • OverpassBaseURL - Base URL for Overpass API to query OSM data
  • OSRMBaseURL - Base URL for OSRM routing service
  • UserAgent - User agent string to use for API requests
  • EarthRadius - Earth radius in meters for distance calculations
Functions
  • NewClient() - Returns a pre-configured HTTP client for OSM API requests with appropriate timeouts and connection pooling
  • HaversineDistance() - Calculates distances between geographic coordinates using the Haversine formula
  • NewBoundingBox() - Creates a new bounding box for geographic queries
  • BoundingBox.ExtendWithPoint() - Extends a bounding box to include a point
  • BoundingBox.Buffer() - Adds a buffer around a bounding box
  • BoundingBox.String() - Returns a formatted string representation of a bounding box for use in Overpass queries

Usage

import "github.com/NERVsystems/osmmcp/pkg/osm"

// Create an HTTP client
client := osm.NewClient()

// Calculate distance between two points
distance := osm.HaversineDistance(lat1, lon1, lat2, lon2)

// Create and use a bounding box
bbox := osm.NewBoundingBox()
bbox.ExtendWithPoint(lat1, lon1)
bbox.ExtendWithPoint(lat2, lon2)
bbox.Buffer(1000) // Add 1000 meter buffer

Design Principles

The package follows these design principles:

  1. Single Responsibility: Each component has a clear, focused purpose
  2. Reusability: Components are designed to be reused across tools
  3. Abstraction: Implementation details of OSM services are hidden behind clean interfaces
  4. Consistency: Ensures consistent behavior across different API calls
  5. Security: Properly configures timeouts and connection limits

Documentation

Overview

Package osm provides utilities for working with OpenStreetMap data.

Package osm provides utilities for working with OpenStreetMap data.

Package osm provides utilities for working with OpenStreetMap data.

Package osm provides utilities for interacting with OpenStreetMap APIs.

Package osm provides utilities for working with OpenStreetMap data.

Index

Constants

View Source
const (
	// Service names for rate limiting
	ServiceNominatim = "nominatim"
	ServiceOverpass  = "overpass"
	ServiceOSRM      = "osrm"
)
View Source
const (
	// API endpoints
	NominatimBaseURL = "https://nominatim.openstreetmap.org"
	OverpassBaseURL  = "https://overpass-api.de/api/interpreter"
	OSRMBaseURL      = "https://router.project-osrm.org"

	// User agent for API requests (required by Nominatim's usage policy)
	UserAgent = "osm-mcp-server/0.1.0"

	// Earth radius in meters (approximate) - re-exported from geo package
	EarthRadius = geo.EarthRadius
)
View Source
const (
	// DefaultUserAgent is the default User-Agent string
	DefaultUserAgent = "OSMMCP/0.1.0"
)

Variables

This section is empty.

Functions

func DecodePolyline

func DecodePolyline(encoded string) []geo.Location

DecodePolyline decodes an encoded polyline string to a slice of locations. This implements Google's Polyline Algorithm Format (Polyline5) which is used by OSRM. The algorithm uses 5 decimal places of precision (1e-5) for coordinates. See https://developers.google.com/maps/documentation/utilities/polylinealgorithm

func DoRequest

func DoRequest(ctx context.Context, req *http.Request) (*http.Response, error)

DoRequest performs an HTTP request with rate limiting

func EncodePolyline

func EncodePolyline(points []geo.Location) string

EncodePolyline encodes a slice of locations into a polyline string. This implements Google's Polyline Algorithm Format (Polyline5) which is used by OSRM. The algorithm uses 5 decimal places of precision (1e-5) for coordinates. See https://developers.google.com/maps/documentation/utilities/polylinealgorithm

func GetClient

func GetClient(ctx context.Context) *http.Client

GetClient returns the global HTTP client

func GetUserAgent

func GetUserAgent() string

GetUserAgent returns the current User-Agent string

func HaversineDistance

func HaversineDistance(lat1, lon1, lat2, lon2 float64) float64

HaversineDistance calculates the great-circle distance between two points Deprecated: Use geo.HaversineDistance instead

func NewBoundingBox

func NewBoundingBox() *geo.BoundingBox

NewBoundingBox creates a new empty bounding box Deprecated: Use geo.NewBoundingBox instead

func NewClient

func NewClient() *http.Client

NewClient returns an HTTP client configured for OSM API requests Deprecated: Use GetClient(ctx) instead for connection pooling

func NewRequestWithUserAgent

func NewRequestWithUserAgent(ctx context.Context, method, url string, body interface{}) (*http.Request, error)

NewRequestWithUserAgent creates a new HTTP request with proper User-Agent header This simplifies creating requests with the correct header throughout the codebase

func SetUserAgent

func SetUserAgent(ua string)

SetUserAgent sets the User-Agent string

func UpdateNominatimRateLimits

func UpdateNominatimRateLimits(rps float64, burst int)

UpdateNominatimRateLimits updates the Nominatim rate limiter

func UpdateOSRMRateLimits

func UpdateOSRMRateLimits(rps float64, burst int)

UpdateOSRMRateLimits updates the OSRM rate limiter

func UpdateOverpassRateLimits

func UpdateOverpassRateLimits(rps float64, burst int)

UpdateOverpassRateLimits updates the Overpass rate limiter

func ValidateCoords

func ValidateCoords(lat, lon float64) error

ValidateCoords validates latitude and longitude values Returns an error if the coordinates are invalid

func WaitForService

func WaitForService(ctx context.Context, service string) error

WaitForService is a convenience function to wait for a service's rate limit using the global rate limiter

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents an OSM API client

func NewOSMClient

func NewOSMClient() *Client

NewOSMClient creates a new OSM API client

func (*Client) SetLogger

func (c *Client) SetLogger(logger *slog.Logger)

SetLogger sets the logger for the client

type OverpassElement added in v0.1.1

type OverpassElement struct {
	ID     int     `json:"id"`
	Type   string  `json:"type"`
	Lat    float64 `json:"lat,omitempty"`
	Lon    float64 `json:"lon,omitempty"`
	Center *struct {
		Lat float64 `json:"lat"`
		Lon float64 `json:"lon"`
	} `json:"center,omitempty"`
	Tags    map[string]string `json:"tags,omitempty"`
	Nodes   []int64           `json:"nodes,omitempty"` // For ways, list of node IDs
	Members []struct {
		Type string `json:"type"`
		Ref  int64  `json:"ref"`
		Role string `json:"role"`
	} `json:"members,omitempty"` // For relations
}

OverpassElement represents an element returned from the Overpass API

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter manages rate limiting for different OpenStreetMap API services

func GetRateLimiter

func GetRateLimiter() *RateLimiter

GetRateLimiter returns the global rate limiter instance

func (*RateLimiter) Wait

func (rl *RateLimiter) Wait(ctx context.Context, service string) error

Wait blocks until the rate limit for the specified service allows an event or the context is canceled.

type TTLCache

type TTLCache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

TTLCache is a generic thread-safe cache with TTL support

func NewTTLCache

func NewTTLCache[K comparable, V any](ttl time.Duration) *TTLCache[K, V]

NewTTLCache creates a new TTL cache with the specified TTL duration

func (*TTLCache[K, V]) Cleanup

func (c *TTLCache[K, V]) Cleanup()

Cleanup removes expired items from the cache

func (*TTLCache[K, V]) Clear

func (c *TTLCache[K, V]) Clear()

Clear removes all items from the cache

func (*TTLCache[K, V]) Delete

func (c *TTLCache[K, V]) Delete(key K)

Delete removes a value from the cache

func (*TTLCache[K, V]) Get

func (c *TTLCache[K, V]) Get(key K) (V, bool)

Get retrieves a value from the cache if it exists and hasn't expired

func (*TTLCache[K, V]) Set

func (c *TTLCache[K, V]) Set(key K, value V)

Set adds a value to the cache with the configured TTL

func (*TTLCache[K, V]) Size

func (c *TTLCache[K, V]) Size() int

Size returns the number of items in the cache

Directories

Path Synopsis
Package queries provides utilities for building OpenStreetMap API queries.
Package queries provides utilities for building OpenStreetMap API queries.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL