How To Use Mapbox In Vue.js

In this article, we will learn how to use the mapbox in vue.js.

Step 1: Create a mapbox account and get the mapbox accesstoken:

Step 2: Create a new Vue project:

vue create mapbox-demo

Step 3: Install require packages:

npm i mapbox-gl

Step 4: Open index.html file and add the following in it:

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <link
      href="https://api.tiles.mapbox.com/mapbox-gl-js/v2.6.0/mapbox-gl.css"
      rel="stylesheet"
      />
    <title><%= htmlWebpackPlugin.options.title %></title>
    </head>
    <body>
      <noscript>
        <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't
            work properly without JavaScript enabled. Please enable it to
            continue.</strong>
        </noscript>
        <div id="app"></div>
        <!-- built files will be auto injected -->
      </body>
    </html>

Step 5: Open main.js file and add the following in it:

import Vue from 'vue'
import App from './App.vue'
import Mapbox from "mapbox-gl";

Vue.use({ mapboxgl: Mapbox });

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

Step 6: Open App.vue file and add following in it:

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

<script>
import mapboxgl from "mapbox-gl";
export default {
  name: "App",
  data() {
    return {
      accessToken:
        "pk.eyJ1IjoiaGVlbWFwYXRlbCIsImEiOiJja3Z3OXJnNnUwNjYzMm5xYnNzejNiamRtIn0.W6Xz7JZaeUW0V3XAz8Df9A", // mapbox key
    };
  },
  mounted() {
    mapboxgl.accessToken = this.accessToken;
    var map = new mapboxgl.Map({
      container: "map",
      style: "mapbox://styles/mapbox/light-v10",
      center: [103.811279, 1.345399],
      zoom: 12,
      maxBounds: [
        [103.6, 1.1704753],
        [104.1, 1.4754753],
      ],
    });
    const nav = new mapboxgl.NavigationControl();
    map.addControl(nav, "top-right");
    new mapboxgl.Marker()
      .setLngLat([103.811279, 1.345399])
      .addTo(map);
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
#map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}
</style>

Code in Action:

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories