Utilizing Mapbox-gl within a Vue.js single file component with Quasar-Framework integration

I'm attempting to incorporate a Mapbox-gl-js Map into a single file Vue component within the Quasar Framework, but I'm struggling to make it work. I've come across examples of Googlemaps with Vue and Mapbox with React, and I'm trying to merge them to achieve my desired outcome. While I can display the map successfully in index.html using the map initialization parameters below (with mapzen tiles), I want it to be within the component.

I'm following this guide [ url) and adapting it for Mapbox:

<template>
    <quasar-layout>
      <h3>Map</h3>
      <div id='map'></div>
    </quasar-layout>
  </template>

  <script>
  import mapboxgl from '../app'

  export default {
    data () {
      return {}
    },
    create () {
      this.createMap()
    },
    methods: {
      createMap: function () {
        mapboxgl.accessToken = '{{yourmapboxaccestokenkey}}'
        var simple = {
          'version': 8,
          'sources': {
            'osm': {
              'type': 'vector',
              'tiles': ['https://vector.mapzen.com/osm/all/{z}/{x}/{y}.mvt?api_key=vector-tiles-{{yourmapzenapikey}}']
            }
          },
          'layers': [{
            'id': 'background',
            'type': 'background',
            'paint': {
              'background-color': '#adddd2'
            }
          }, {
            'id': 'majorroad',
            'source': 'osm',
            'source-layer': 'roads',
            'type': 'line'
          }, {
            'id': 'buildings',
            'type': 'fill',
            'source': 'osm',
            'source-layer': 'buildings'
          }]
        }

        // initialize the map
        this.map = new mapboxgl.Map({
          container: 'map',
          style: simple,
          center: [-1.83, -78.183],
          zoom: 5.5
        })
      }
    }
  }
  </script>

  <style>
  </style>

For Mapbox with webpack, specific loaders are required, as detailed here: [ url) I believe I have the necessary setup since I worked with Mapbox and Webpack previously (without Vue), and there are no errors showing up in the browser console (although the map itself is not visible).

In the app.js file, I'm unsure how to handle the suggested code (which may not be necessary for Mapbox or Mapzen, unlike Googlemaps that requires a callback):

var App = window.App = new Vue ({
//code
})

While Quasar initialization is done like this:

Quasar.start(() => {
  Router.start(Vue.extend({}), '#quasar-app')
})

This part is a bit confusing to me...

If you have any suggestions on how to get this working, please feel free to share!

Answer №1

My recent discovery shows:

<template>
  <quasar-layout>
  <h3>Map</h3>
  <div id='map'></div>
  </quasar-layout>
</template>

<script>
import mapboxgl from 'mapbox-gl'
console.dir(mapboxgl)

export default {
  data () {
    return {}
  },
  ready () {
    this.createMap()
  },
  methods: {
    createMap: function () {
      mapboxgl.accessToken = '{{yourmapboxaccestokenkey}}'
      var simple = {
        'version': 8,
        'sources': {
          'osm': {
            'type': 'vector',
            'tiles': ['https://vector.mapzen.com/osm/all/{z}/{x}/{y}.mvt?api_key=vector-tiles-{{yourmapzenapikey}}']
          }
        },
        'layers': [{
          'id': 'background',
          'type': 'background',
          'paint': {
            'background-color': '#bbccd2'
          }
        },
          {
            'id': 'majorroad',
            'source': 'osm',
            'source-layer': 'roads',
            'type': 'line'
          },
          {
            'id': 'buildings',
            'type': 'fill',
            'source': 'osm',
            'source-layer': 'buildings'
          }]
      }

      // init the map
      this.map = new mapboxgl.Map({
        container: 'map',
        style: simple,
        minzoom: 1.3,
        center: [-74.0073, 40.7124], // Manhattan
        zoom: 16
      })

      this.map.addControl(new mapboxgl.Navigation())
    }
  }
}
</script>

<style>
</style>

No alterations to my Vue initialization have been made.

Answer №2

<template>
  <div class="hello">
    <div id='map'></div>
  </div>
</template>

<script>
import mapboxgl from 'mapbox-gl';

require('../node_modules/mapbox-gl/dist/mapbox-gl.css');

export default {
  name: 'HelloWorld',
  data() {
    return {
      apiKey: YOUR_API_KEY,
    };
  },
  mounted() {
    this.createMap();
  },
  methods: {
    createMap() {
      mapboxgl.accessToken = this.apiKey;
      // initialize the map
      this.map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v9',
        minzoom: 1.3,
        center: [-74.0073, 40.7124], // Manhattan
        zoom: 16,
      });

      this.map.addControl(new mapboxgl.Navigation());
    },
  },
};
</script>

This code snippet may come in handy!

Answer №3

One observation I made is that the map is being initialized before the DOM is injected into the document. Consider using the 'ready()' method instead of the 'created()' method in this case.

Answer №4

Quasar utilizes the Vue2 version as its foundation. The ready method has been deprecated, so it is recommended to use the mounted method instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing text content into objects in Protractor

I am facing an issue with a span tag that contains JSON text, which I need to convert into an object in Protractor for testing purposes. {"type":"msax-cc-error","value":[{"Code":22104,"Message":"Card holder is required"},{"Code":22058,"Message":"Card numb ...

Discovering whether an image contains a caption with the help of JavaScript

There are various websites that display captions on images in paragraphs, h1 tags, or contained within a div along with the image. I am interested in learning how to determine if an image has an associated caption using JavaScript, especially when the cap ...

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

HTML5 enables users to pick their preferred font style

In my JavaScript and HTML5 course, I am working on developing a website where users can choose the background color and decide between using SANS SERIF or SANS fonts. The background color selection feature is already functioning successfully -- var inputC ...

Difficulty understanding JavaScript sum calculations

I am currently working on a website project. Seeking assistance to enable an increment of one when clicked. Also need guidance on calculating the total price of items collected in a designated section under "number of items selected". Goal is to display ...

Utilizing Angular 11's HostListener to capture click events and retrieve the value of an object

Using the HostListener directive, I am listening for the click event on elements of the DOM. @HostListener('click', ['$event.target']) onClick(e) { console.log("event", e) } Upon clicking a button tag, the "e" object contains the fol ...

What is the best method to retrieve the value of a button that has been selected from a collection of buttons?

Within a functional component, there is an issue where the choose function keeps printing 'undefined'. I have utilized const [chosen, setchosen] = useState([]) within this code snippet. The full code has been correctly imported and the purpose of ...

WebStorm raises an error saying "SyntaxError: Plugin '@typescript-eslint' failed to load as declared in '.eslintrc.cjs' » '@vue/eslint-config-typescript'."

Encountering an issue in WebStorm where every ts file in the project displays the error message: SyntaxError: Failed to load plugin '@typescript-eslint' declared in '.eslintrc.cjs » @vue/eslint-config-typescript': Unexpected token &a ...

Select from a variety of backgrounds using the dropdown menu on the site

I seem to be struggling with javascript and php, but I know that in order to make this function properly, I need to utilize both languages. My goal is to set up a "select box" featuring 4 different images. There will be a default image displayed, but user ...

Challenges with passing array values between Vue3 components

Having an issue with arrays in vue3 that is puzzling me. Upon loading components, an initial array is passed. These values are then watched for changes within the components which works seamlessly. The scenario involves a little game where the user maneuv ...

Unlocking Discord Account Information through OAuth2

Currently, I am in the process of developing a moderation bot for Discord. I am working on implementing a paid plan and as part of that, I require users to log in with their Discord account using OAuth2. This allows me to retrieve user data and identify wh ...

Tips for displaying filtered items on the MongoDB terminal

I have objects categorized by cost and date of addition, each user having such categories. My goal is to display all categories for the month "08" in the console. How can I achieve this? Currently, my code retrieves the entire object with the user informat ...

Expanding Bootstrap 5 navbar-nav to occupy entire screen space in collapsed state

Hello everyone, I hope you are doing well! I am currently working on a website project using Bootstrap 5 and have encountered an issue with the navbar toggler. While the toggler is functioning properly, I am having trouble making it fill the full width o ...

Ways to duplicate the content of a div to the clipboard without the use of flash

Simple question! I have a div identified as #toCopy, along with a button identified as #copy. Can you suggest the most efficient method to copy the content of #toCopy to the clipboard upon clicking #copy? ...

Utilizing Javascript to initiate an AJAX call to the server

I am creating an application similar to JSbin / JS fiddle. My goal is to update my database by making an ajax request to the server when the user clicks on the save code button and submits the values entered in the textarea. However, I seem to be encount ...

Recommendation: 3 options for radio buttons on the registration form

My form includes a section where users need to choose if they want to sign up for a session that occurs 3 times daily. The catch is, only 5 applicants can enroll in each session (AM, Mid-day, PM). It's a competition to secure a spot. Here is the form ...

The extent of utilizing the click handler in ECMA script 6

In ES6 arrow functions, the scope of this becomes available. However, there are instances where I cannot access this in an arrow function while it works with a normal anonymous function. For example: Sample 1 $(document).ready(function() { $(' ...

What is the best way to load the nested array attributes in an HTML table dynamically with AngularJS?

I attempted the following code, but I am only able to access values for cardno and cardtype. Why can't I access the others? Any suggestions? <tr ng-repeat="data in myData17.layouts"> <td ng-show="$index==1">{{data.name}}</td> &l ...

Adding a class to an element in AngularJS

I have a question about entering empty values in an input field and highlighting its boundary. I added a new class 'warning' for this purpose and created the following code. HTML: `<body ng-app="TestPage"> <form ng-controller="TestFor ...

Webpack 4 issue - Unexpected character '@' causing module parsing to fail

I encountered an issue while trying to develop a react app. The webpack error message states: 'ERROR in ./src/App.css 1:0 Module parse failed: Unexpected character '@' (1:0) You may need an appropriate loader to handle this file type, curren ...