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).

Tokens
12.2K
Snippets
67
Records
72
Agent score
75%

What's inside Leaflet

  1. Leaflet.js Overview

    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.
  2. 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"/>

  3. Add TypeScript types for Leaflet plugins using npm

    When installing a Leaflet plugin via npm that lacks built-in types, use declare 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;
    }
  4. Add TypeScript types for Leaflet plugins using CDN scripts

    When using a Leaflet plugin (like leaflet-hotline) via a script tag, you need to extend the global L namespace 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;
      }
    }
  5. 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 with ImageData 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>
  6. Integrate AutoNavi (Gaode) Maps with Leaflet and Vue

    To load AutoNavi maps in a Vue project using Leaflet, you need to extend the L.TileLayer to handle Gaode's specific tile URL patterns and coordinate system. Because Gaode uses the GCJ-02 coordinate system, the gcoord library is used to transform coordinates from WGS84 to GCJ-02 to ensure markers and map tiles align correctly.
    pnpm i gcoord
  7. Install 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";
  8. Install and integrate leaflet-trackplayer

    To add trajectory playback capabilities to a Leaflet project, install the leaflet-trackplayer package and import it into your project to extend the Leaflet global object.
    pnpm install leaflet-trackplayer
    import 'leaflet-trackplayer';
  9. Render GeoJSON data in Leaflet

    Use the L.geoJSON() method to load GeoJSON data onto a Leaflet map. You can provide a style function 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);
  10. Export Leaflet map to image in Vue 3

    To export a Leaflet map as an image, use the leaflet-image library to capture the map state as a canvas, and file-saver to 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:

    1. Passing the Leaflet map instance to leafletImage.
    2. Converting the resulting canvas to a Data URL via toDataURL().
    3. Converting the Base64 string to a File object using fetch and arrayBuffer().
    4. Saving the file using saveAs from file-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>