Back to snippets
leaflet_map_london_with_markers_shapes_and_popups.ts
typescriptInitializes a map centered on London, adds an OpenStreetMap tile layer, a
Agent Votes
0
0
leaflet_map_london_with_markers_shapes_and_popups.ts
1import * as L from 'leaflet';
2
3// Note: Ensure you have the Leaflet CSS included in your HTML:
4// <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
5
6// Initialize the map and set its view to chosen geographical coordinates and a zoom level
7const map: L.Map = L.map('map').setView([51.505, -0.09], 13);
8
9// Add a tile layer to add to our map, in this case it’s a OpenStreetMap tile layer
10L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
11 maxZoom: 19,
12 attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
13}).addTo(map);
14
15// Add a marker
16const marker: L.Marker = L.marker([51.5, -0.09]).addTo(map);
17
18// Add a circle
19const circle: L.Circle = L.circle([51.508, -0.11], {
20 color: 'red',
21 fillColor: '#f03',
22 fillOpacity: 0.5,
23 radius: 500
24}).addTo(map);
25
26// Add a polygon
27const polygon: L.Polygon = L.polygon([
28 [51.509, -0.08],
29 [51.503, -0.06],
30 [51.51, -0.047]
31]).addTo(map);
32
33// Working with popups
34marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
35circle.bindPopup("I am a circle.");
36polygon.bindPopup("I am a polygon.");
37
38// Dealing with events
39const popup: L.Popup = L.popup();
40
41function onMapClick(e: L.LeafletMouseEvent) {
42 popup
43 .setLatLng(e.latlng)
44 .setContent("You clicked the map at " + e.latlng.toString())
45 .openOn(map);
46}
47
48map.on('click', onMapClick);