Geolocation and Maps in TypeScript: A Complete Overview of Tools
Modern web applications increasingly require the integration of geographic data and interactive maps. TypeScript, as a strictly typed extension of JavaScript, provides excellent capabilities for working with geolocation thanks to static typing and support for modern standards. In this article, we will review the key libraries and tools for working with maps and geodata in TypeScript, their features, and usage examples.
1. Built-in Geolocation API
The browser Geolocation API is a basic tool for obtaining user coordinates. TypeScript adds type safety when working with this API.
// Typed function for getting geolocationinterface PositionOptions { enableHighAccuracy?: boolean; timeout?: number; maximumAge?: number;}
async function getCurrentPosition( options?: PositionOptions): Promise<GeolocationPosition> { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( resolve, reject, options ); });}
// Usage(async () => { try { const position = await getCurrentPosition({ timeout: 5000 }); const { latitude, longitude } = position.coords; console.log(`Coordinates: ${latitude}, ${longitude}`); } catch (error) { console.error('Error getting position:', error); }})();2. Leaflet — Lightweight Mapping Library
Leaflet is one of the most popular open-source libraries for interactive maps. It has excellent TypeScript support through the @types/leaflet package.
Installation and Setup
npm install leafletnpm install --save-dev @types/leafletBasic Map Example
import L from 'leaflet';import 'leaflet/dist/leaflet.css';
class MapManager { private map: L.Map;
constructor(containerId: string, center: [number, number]) { this.map = L.map(containerId).setView(center, 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(this.map); }
addMarker(lat: number, lng: number, title?: string): void { const marker = L.marker([lat, lng]).addTo(this.map); if (title) { marker.bindPopup(`<b>${title}</b>`).openPopup(); } }
setView(center: [number, number], zoom?: number): void { this.map.setView(center, zoom || 13); }}
// Usageconst map = new MapManager('map', [55.751244, 37.618423]);map.addMarker(55.751244, 37.618423, 'Moscow');3. Mapbox GL JS — Professional Solution
Mapbox offers a powerful platform with vector tiles and advanced styling. The TypeScript SDK is available through the mapbox-gl package.
import mapboxgl from 'mapbox-gl';import 'mapbox-gl/dist/mapbox-gl.css';
// Typing for configurationinterface MapConfig { container: string; style: string; center: [number, number]; zoom: number; accessToken: string;}
class MapboxMap { private map: mapboxgl.Map;
constructor(config: MapConfig) { mapboxgl.accessToken = config.accessToken; this.map = new mapboxgl.Map(config); }
addGeoJSONLayer(data: GeoJSON.FeatureCollection): void { this.map.addSource('geojson-data', { type: 'geojson', data });
this.map.addLayer({ id: 'geojson-layer', type: 'circle', source: 'geojson-data', paint: { 'circle-radius': 6, 'circle-color': '#007cbf' } }); }}
// Usage exampleconst mapboxMap = new MapboxMap({ container: 'map', style: 'mapbox://styles/mapbox/streets-v12', center: [37.618423, 55.751244], zoom: 10, accessToken: process.env.MAPBOX_TOKEN || ''});