Geolocation and Maps in TypeScript: Libraries, API, and Code Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Geolocation and Maps in TypeScript: A Complete Guide to Libraries and Tools



Modern web applications increasingly require integration with geographic data: from determining the user's location to displaying interactive maps. TypeScript, thanks to its strict typing and support for modern standards, becomes an ideal choice for developing such solutions. In this article, we will thoroughly examine libraries and tools for working with geolocation and maps in TypeScript, provide practical code examples, and give recommendations for selection.



1. Getting Geolocation: Navigator Geolocation API



The built-in browser API navigator.geolocation is the foundation for obtaining user coordinates. TypeScript provides types for this API, making the work safe and convenient.



// Typed function to get the current positionfunction getCurrentPosition(): Promise<GeolocationPosition> {    return new Promise((resolve, reject) => {        if (!navigator.geolocation) {            reject(new Error('Geolocation is not supported by the browser'));            return;        }                navigator.geolocation.getCurrentPosition(            (position: GeolocationPosition) => {                resolve(position);            },            (error: GeolocationPositionError) => {                reject(error);            },            {                enableHighAccuracy: true,                timeout: 5000,                maximumAge: 0            }        );    });}

// Usage exampleasync function showUserLocation(): Promise<void> { try { const position = await getCurrentPosition(); const { latitude, longitude } = position.coords; console.log(`Latitude: ${latitude}, Longitude: ${longitude}`); } catch (error) { console.error('Error getting geolocation:', error); }}


2. Displaying Maps: Comparison of Popular Libraries



Several powerful libraries are available for working with maps in TypeScript. Let's look at three of the most popular options.



2.1 Leaflet with TypeScript



Leaflet is a lightweight, open-source library for interactive maps. It has official types (@types/leaflet), ensuring full TypeScript support.



import L from 'leaflet';import 'leaflet/dist/leaflet.css';

// Creating a map with typingconst map: L.Map = L.map('map', { center: [55.751244, 37.618423], // Moscow zoom: 10, zoomControl: true});

// Adding OpenStreetMap tilesL.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; OpenStreetMap contributors'}).addTo(map);

// Marker with typed optionsconst marker: L.Marker = L.marker([55.751244, 37.618423], { draggable: true, title: 'Moscow'}).addTo(map);

// Event handling with typingmarker.on('dragend', (event: L.LeafletMouseEvent) => { const coords: L.LatLng = event.target.getLatLng(); console.log(`New coordinates: ${coords.lat}, ${coords.lng}`);});


2.2 Mapbox GL JS



Mapbox offers high-performance vector maps with rich styling capabilities. The TypeScript SDK is available via mapbox-gl.



import mapboxgl from 'mapbox-gl';import 'mapbox-gl/dist/mapbox-gl.css';

// Setting the access tokenmapboxgl.accessToken = 'YOUR_MAPBOX_TOKEN';

// Creating a map with typed parametersconst map: mapboxgl.Map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/dark-v11', center: [37.618423, 55.751244], zoom: 12, pitch: 45 // map tilt});

// Adding a marker with custom HTMLconst marker: mapboxgl.Marker = new mapboxgl.Marker({ color: '#FF0000', draggable: true, rotation: 45}) .setLngLat([37.618423, 5

Recommendations