Leaflet.js Examples
website·Indexed 30 days ago
https://leafletjs-example.netlify.app/A collection of practical examples and implementation guides for using Leaflet.js with Vue and TypeScript. Covers map initialization, GeoJSON, markers, polygons, and various plugin integrations including leaflet-geoman for drawing/editing, leaflet-ruler for distance measurement, leaflet-trackplayer for trajectory playback, and multiple heatmap implementations (webGL, leaflet.heat, and heatmapjs).
What's inside Leaflet
- Leaflet.js is an open-source JavaScript library used to create interactive maps and geographic information applications. It provides a lightweight API for integrating maps, markers, layers, polygons, and polylines into web pages. It is often compared to OpenLayers as another frontend library for map display and GIS processing.
Import leaflet-geoman-free into a project
Import both the JavaScript logic and the required CSS styles to enable the Geoman drawing tools.import "@geoman-io/leaflet-geoman-free"; import "@geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css";<!-- Or via HTML --> <script src="https://unpkg.com/@geoman-io/leaflet-geoman-free@latest/dist/leaflet-geoman.min.js"></script> <link rel="stylesheet" href="https://unpkg.com/@geoman-io/leaflet-geoman-free@latest/dist/leaflet-geoman.css"/>
Add TypeScript types for Leaflet plugins using npm
When installing a Leaflet plugin via npm that lacks built-in types, usedeclare module 'leaflet'in your declaration file to augment the Leaflet module with the plugin's specific types and functions.pnpm install leaflet-hotline// types/global.d.ts import * as L from 'leaflet'; declare module 'leaflet' { namespace Hotline { interface HotlineOptions extends L.PathOptions { weight?: number; outlineWidth?: number; outlineColor?: string; palette?: Record<number, string>; min?: number; max?: number; } interface Hotline extends L.Layer { setLatLngs(latlngs: L.LatLngExpression[]): this; getLatLngs(): L.LatLng[]; } } function hotline(latlngs: L.LatLngExpression[], options?: Hotline.HotlineOptions): Hotline.Hotline; }Add TypeScript types for Leaflet plugins using CDN scripts
When using a Leaflet plugin (likeleaflet-hotline) via a script tag, you need to extend the globalLnamespace in your declaration file to define the plugin's options, interfaces, and factory functions.<script src="https://cdn.jsdelivr.net/npm/leaflet-hotline@0.4.0/dist/leaflet.hotline.min.js"></script>// types/global.d.ts import * as L from 'leaflet'; declare global { namespace L { namespace Hotline { interface HotlineOptions extends L.PathOptions { weight?: number; outlineWidth?: number; outlineColor?: string; palette?: Record<number, string>; min?: number; max?: number; } interface Hotline extends L.Layer { setLatLngs(latlngs: L.LatLngExpression[]): this; getLatLngs(): L.LatLng[]; } } function hotline( latlngs: L.LatLngExpression[], options?: Hotline.HotlineOptions ): Hotline.Hotline; } }Install heatmap.js for Leaflet in Webpack or Vite
Depending on your build tool, use one of the following methods to install the heatmap dependencies. Note that the official repository may have issues withImageData data assignment in Strict Mode, so a modified version is recommended.# For Webpack (npm/pnpm) pnpm install leaflet-heatmap @mars3d/heatmap.js<!-- For Vite: Download heatmap.js and leaflet-heatmap.js and include them in index.html -->
<script src="./heatmap.js"></script> <script src="./leaflet-heatmap.js"></script>Integrate AutoNavi (Gaode) Maps with Leaflet and Vue
To load AutoNavi maps in a Vue project using Leaflet, you need to extend theL.TileLayerto handle Gaode's specific tile URL patterns and coordinate system. Because Gaode uses the GCJ-02 coordinate system, thegcoordlibrary is used to transform coordinates from WGS84 to GCJ-02 to ensure markers and map tiles align correctly.pnpm i gcoordInstall Leaflet.js via npm for Vue projects
Install the Leaflet library using npm. When using npm, you must import the Leaflet CSS file in your entry file (e.g.,main.js) to prevent rendering issues such as incomplete tile loading.npm install leaflet// main.js import "leaflet/dist/leaflet.css";Install leaflet-webgl-heatmap
To add WebGL heatmap capabilities to a Leaflet map, install theleaflet-webgl-heatmappackage.pnpm install leaflet-webgl-heatmapInstall leaflet-ruler for distance measurement
To add distance measurement capabilities to a Leaflet map, install theleaflet-rulerpackage.pnpm i leaflet-rulerInstall and integrate leaflet-trackplayer
To add trajectory playback capabilities to a Leaflet project, install theleaflet-trackplayerpackage and import it into your project to extend the Leaflet global object.pnpm install leaflet-trackplayerimport 'leaflet-trackplayer';Render GeoJSON data in Leaflet
Use theL.geoJSON()method to load GeoJSON data onto a Leaflet map. You can provide astylefunction to dynamically set the appearance of features based on their properties and use.bindPopup()to attach information to the layers.L.geoJSON(data, { style: function (feature) { // Use a property from the GeoJSON 'properties' object to set the color return { color: feature.properties.color ?? 'green' }; } }) .bindPopup(function (layer) { // Bind a popup showing the 'name' property of the feature return layer.feature.properties.name; }) .addTo(map);Export Leaflet map to image in Vue 3
To export a Leaflet map as an image, use the
leaflet-imagelibrary to capture the map state as a canvas, andfile-saverto trigger the browser download. Because the export process can take some time, it is recommended to implement a loading state in the UI.The process involves:
- Passing the Leaflet map instance to
leafletImage. - Converting the resulting canvas to a Data URL via
toDataURL(). - Converting the Base64 string to a File object using
fetchandarrayBuffer(). - Saving the file using
saveAsfromfile-saver.
pnpm install leaflet-image file-saver<script setup> import leafletImage from 'leaflet-image'; import { saveAs } from 'file-saver'; const mapObj = ref(); // Reference to the Leaflet map instance /** * Converts base64 string to a File object */ const base64ToFile = (url, filename, mimeType) => { return fetch(url) .then(res => res.arrayBuffer()) .then(buf => new File([buf], filename, { type: mimeType })); }; // Function to export the map as an image const exportPicture = () => { leafletImage(mapObj.value, async (err, canvas) => { if (err) { console.error(err); return; } const fileBase64 = canvas.toDataURL(); const file = await base64ToFile(fileBase64, 'map-export', 'png'); saveAs(file, `map-export.png`); }); }; const mapLoad = (map) => { mapObj.value = map; }; </script> <template> <init-map @map-load="mapLoad"></init-map> <button @click="exportPicture">Export Image</button> </template>- Passing the Leaflet map instance to