[Vuejs]-How to Integrate Leaflet with Mapbox GL In vuejs

0๐Ÿ‘

You can use following code to integrate Leaflet into MapboxGl.

<template>
  <LMap id="map" :center="center" :zoom="zoom">
    <LTileLayer
      :options="layerOptions"
      :tile-layer-class="tileLayerClass" />
  </LMap>
</template>

<script>
import { LMap, LTileLayer } from 'vue2-leaflet'
import L from 'leaflet'
import mapboxgl from 'mapbox-gl'
import 'mapbox-gl-leaflet'
import 'mapbox-gl/dist/mapbox-gl.css'
import 'leaflet/dist/leaflet.css'
window.mapboxgl = mapboxgl // mapbox-gl-leaflet expects this to be global
export default {
  components: {
    LMap,
    LTileLayer
  },
  data () {
    return {
      center: [39.9523893, -75.1636291],
      zoom: 14,
      tileLayerClass: (url, options) => L.mapboxGL(options),
      layerOptions: {
        accessToken: 'no-token',
        style: 'https://raw.githubusercontent.com/osm2vectortiles/mapbox-gl-styles/master/styles/bright-v9-cdn.json'
      }
    }
  }
}
</script>

<style>
#map {
  height: 500px;
}
</style>

0๐Ÿ‘

<template>
  <div id="map"></div>
</template>

<script>
export default {
  name: 'Map',
  mounted() {
    // Initialize Leaflet map
    this.map = L.map('map').setView([YOUR_LATITUDE, YOUR_LONGITUDE], YOUR_ZOOM_LEVEL);

    // Add Mapbox GL layer to Leaflet map
    const mapboxAccessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';
    L.mapboxGL({
      accessToken: mapboxAccessToken,
      style: 'mapbox://styles/mapbox/streets-v11', // You can use your desired Mapbox style here
    }).addTo(this.map);
  },
};
</script>

<style>
#map {
  width: 100%;
  height: 500px;
}
</style>

0๐Ÿ‘

Suppose you have to used Leaflet with Mapbox GL in Vue.js Then used following step

Step 1: Install the Leaflet packages in your project

npm install mapbox-gl
npm i -D @vue-leaflet/vue-leaflet leaflet

Step 2: Then Create the GoogleMap.vue commponet file

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

    export default {
      components: {
        LMap,
        LTileLayer,
      },
      mounted() {
        this.initMap();
      },
      methods: {
        initMap() {
          const map = L.map(this.$refs.map).setView([YOUR_INITIAL_LATITUDE, YOUR_INITIAL_LONGITUDE], YOUR_INITIAL_ZOOM_LEVEL);

          L.tileLayer(
            "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}",
            {
              maxZoom: 12,
              tileSize: 300,
              zoomOffset: -1,
              accessToken: 'here token code',
            }
          ).addTo(map);
        },
      },
    };
    </script>

    <style>
    .map {
      height: 100%;
    }
    </style>

    <template>
      <div id="map">
        <div ref="map" class="map"></div>
      </div>
    </template>

Step 3: Then Import the GoogleMap.vue component in Your main component

Leave a comment