Geolocation and Maps in TypeScript: Tool Overview and Code Examples
Modern web applications increasingly require working with geographic data: from simply displaying a user's location to complex routing and clustering. TypeScript, with its strict typing, makes developing such features more reliable and convenient. In this article, we will review popular libraries for working with maps and geolocation, show examples of integration with TypeScript, and provide practical tips.
1. Basics of Browser Geolocation
Before connecting maps, you need to get the user's coordinates. The built-in geolocation API (navigator.geolocation) is well-typed in TypeScript.
interface Position { latitude: number; longitude: number; accuracy?: number;}
function getCurrentPosition(): Promise<Position> { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( (pos) => { resolve({ latitude: pos.coords.latitude, longitude: pos.coords.longitude, accuracy: pos.coords.accuracy }); }, (error) => reject(error) ); });}
// UsagegetCurrentPosition() .then((pos) => console.log(`Latitude: ${pos.latitude}, Longitude: ${pos.longitude}`)) .catch((err) => console.error('Geolocation error:', err));2. Leaflet — Lightweight and Popular Library
Leaflet is one of the simplest and fastest libraries for displaying maps. For TypeScript, there is the @types/leaflet package.
Installation
npm install leafletnpm install --save-dev @types/leafletExample: Map with a Marker
import L from 'leaflet';import 'leaflet/dist/leaflet.css';
// Typed initialization functionfunction initMap(containerId: string, coords: [number, number]): L.Map { const map = L.map(containerId).setView(coords, 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map);
L.marker(coords) .addTo(map) .bindPopup('You are here!');
return map;}
// Usageconst map = initMap('map', [55.7558, 37.6173]); // MoscowAdvanced Event Typing
map.on('click', (e: L.LeafletMouseEvent) => { const { lat, lng } = e.latlng; console.log(`Click: ${lat}, ${lng}`);});3. OpenLayers — Powerful Tool for Complex Tasks
OpenLayers supports a large number of formats (GeoJSON, KML, WMS) and is suitable for professional geographic information systems. Types are included with the package.
Installation
npm install olExample: Map with a Marker and Popup
import Map from 'ol/Map';import View from 'ol/View';import TileLayer from 'ol/layer/Tile';import OSM from 'ol/source/OSM';import { fromLonLat } from 'ol/proj';import Feature from 'ol/Feature';import Point from 'ol/geom/Point';import VectorLayer from 'ol/layer/Vector';import VectorSource from 'ol/source/Vector';import Style from 'ol/style/Style';import Icon from 'ol/style/Icon';import Overlay from 'ol/Overlay';
function createMap(containerId: string, lon: number, lat: number): void { const container = document.getElementById(containerId) as HTMLElement;
// Create marker const marker = new Feature({ geometry: new Point(fromLonLat([lon, lat])) });
marker.setStyle(new Style({ image: new Icon({ anchor: [0.5, 1], src: 'https://openlayers.org/en/latest/examples/data/icon.png' }) }));
// Vector layer const vectorLayer = new VectorLayer({ source: new VectorSource({ features: [marker] }) });
// Map const map = new Map({ target: container, layers: [ Also in library
Working with Excel in PHP: PhpSpreadsheet, PhpOffice Libraries and XLSX Generation
JSON Processing in Node.js: A Complete Guide
Working with Images in Go (Golang): Libraries and Examples
Sending SMS in JavaScript (Node.js): API Libraries and Code Examples
Working with XML in Java: DOM, SAX, StAX, and JAXB