Search code examples
javascriptvue.jsleafletvuejs3vue-options-api

Insert context menu in Leaflet map


I want to ask about Vue 3, how to insert a custom context menu in a Leaflet map? I'm using leaflet@1.9.4, @vue-leaflet/vue-leaflet@0.10.1 and trying to use leaflet-contextmenu@1.4.0. My code looks like this:

<template>
    <div class="map">
        <l-map ref="map" v-model:zoom="zoom" :center="[49.2265592, 16.5957531]">
            <l-tile-layer
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                layer-type="base"
                name="OpenStreetMap"
            ></l-tile-layer>
        </l-map>
    </div>
</template>

<script>
import "leaflet/dist/leaflet.css";
import { LMap, LTileLayer } from "@vue-leaflet/vue-leaflet";
// import L from 'leaflet';
// import "leaflet-contextmenu";

export default {
    components: {
        LMap,
        LTileLayer,
    },
    data() {
        return {
            zoom: 13,
        };
    },
};
</script>

What I would like to do is something like:

L.map.contextmenu = true;
L.map.contextmenuItems = [{
    text: 'Show coordinates',
}];

However, I can't figure out how and where to write this. Any feedback would be appreciated.


Solution

  • I have figured out how to use leaflet-contextmenu@1.4.0 in @vue-leaflet/vue-leaflet@0.10.1. The key is passing options (:options="mapOptions") to the leaflet map constructor, which can be done declaratively. The code is like:

    <template>
        <div class="map">
            <l-map ref="map" v-model:zoom="zoom" :center="[49.2265592, 16.5957531]" :options="mapOptions">
                <l-tile-layer
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    layer-type="base"
                    name="OpenStreetMap"
                ></l-tile-layer>
            </l-map>
        </div>
    </template>
    
    <script>
    import "leaflet/dist/leaflet.css";
    import { LMap, LTileLayer } from "@vue-leaflet/vue-leaflet";
    import 'leaflet-contextmenu';
    import 'leaflet-contextmenu/dist/leaflet.contextmenu.min.css';
    
    export default {
        components: {
            LMap,
            LTileLayer,
        },
        data() {
            return {
                zoom: 13,
                mapOptions: {
                    contextmenu: true,
                    contextmenuWidth: 140,
                    contextmenuItems: [
                    {
                        text: 'Show coordinates',
                        callback: ()=> alert('Coordinates callback')
                    }
                    ]
                },
            };
        },
    };
    </script>
    

    I hope this helps someone else.