Write, Run & Share Leaflet code online using OneCompiler's Leaflet online editor for free. It's one of the robust, feature-rich online editors for Leaflet. Getting started with the OneCompiler's Leaflet online editor is really simple and pretty fast. The editor shows sample boilerplate code when you choose language as 'Leaflet' and start writing code to learn and test online without worrying about tedious process of installation.
Leaflet is a library for interactive maps. You point it at a tile provider for the base map, then add markers, popups, and shapes on top. It's small, works on mobile, and leaves the choice of map data (OpenStreetMap and others) up to you.
Leaflet needs both its stylesheet and its script. Give the map a container with a height, or it won't show.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/leaflet.css" />
<div id="map" style="height: 100vh;"></div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/leaflet.js"></script>
Create the map, center it with setView([lat, lng], zoom), then add a tile layer for the base imagery.
const map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap contributors',
}).addTo(map);
Drop a marker at a coordinate and attach a popup that opens on click (or right away with openPopup).
L.marker([51.505, -0.09])
.addTo(map)
.bindPopup('A point of interest')
.openPopup();
Draw circles, polygons, and lines directly on the map with their own styles.
L.circle([51.508, -0.11], { radius: 500, color: '#5c6ac4' }).addTo(map);
L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047],
]).addTo(map);
Render GeoJSON features in one call. Use the style and onEachFeature options to customize them.
L.geoJSON(myFeatureCollection, {
style: { color: '#5c6ac4', weight: 2 },
onEachFeature: (feature, layer) => layer.bindPopup(feature.properties.name),
}).addTo(map);
Listen for map events such as clicks. The event object carries the clicked coordinate in latlng.
map.on('click', (e) => {
L.marker(e.latlng).addTo(map);
});