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

The Chrome extension takes control of the new tab feature by redirecting it to a custom newtab.html

I have a website https://example.com where users can adjust their site preferences, including enabling night mode. To enhance the user experience, I developed a Chrome extension for https://example.com that transforms Chrome's new tab with a custom ne ...

Utilize React to update the state of arrays in functional components

Need help with updating the cars array in my React app. When I click on the Add button, a new object is added to the updatedCars array but the state of cars does not get updated. Even after adding a new object to the array, the initial state remains uncha ...

"webpack" compared to "webpack --watch" produces varying results in terms of output

My project is built on top of this setup: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html Running webpack compiles a bundle that functions correctly in the browser. However, running webpack --watch to recompile on file changes resul ...

Do I require two bot logins for discord.js?

Working on my discord bot, I've been trying to incorporate a script from index.js. Should I also include bot.login at the end of cmdFunctions.js? Here is the content of index.js: const Discord = require('discord.js'); const bot = new Discor ...

Where is the destination of the response in a Client-Side API Call?

I have developed an API that accepts a person's name and provides information about them in return. To simplify the usage of my API for third parties on their websites, I have decided to create a JavaScript widget that can be embedded using a script ...

Receiving multiple NodeJS Responses through AJAX for a single request

I have been working on a WebApp that involves heavy AJAX calls from the frontend and NodeJS Express at the backend. Here is a glimpse of my Frontend Code- Below is the global AJAX function I consistently use in all my projects: function _ajax(params = {}, ...

Is there a way to invoke a different function within a class from a callback function in an HTTP request?

Having an issue with my HTTP GET request function in the "CheckPrice" class. When trying to call another function within the class callback, it's showing as undefined. Any suggestions? const got = require("got") class PriceCheck { constructor() { ...

Creating a React component with a reference using TypeScript

Let's discuss a scenario with a reference: someReference; The someReference is essentially a React component structured like this: class SomeComponent<IProps> { getData = () => {}; render() { ...some content } } Now, how c ...

Navigating Paths in Real-time with Javascript - Node.js

When working with PHP, dynamic routing can be achieved by defining classes and methods like: class Route { public function homePage () { echo 'You are on the home page' } public function otherPage () { echo 'You are on so ...

A unique string containing the object element "this.variable" found in a separate file

Snippet of HTML code: <input class="jscolor" id="color-picker"> <div id="rect" class="rect"></div> <script src="jscolor.js"></script> <script src="skrypt.js"></script> Javascript snippet: function up ...

Vue 3 feature: Click the button to dynamically insert a new row into the grid

Just starting out in the world of coding, I've zero experience with Vue - it's my introduction to frameworks and arrays are currently my nemesis. In a recent exercise, I managed to display the first five elements of an array in a table after filt ...

Troubleshooting Issue with InfoWindow Display on Multiple Markers in Google Maps

I'm having trouble getting my markers to show different infowindows. No matter what I do, the markers always display the content of the last "contentString" in the loop. Despite reading through multiple posts on this issue, I haven't been able t ...

Are there any AJAX tools or packages in Node.js Express for connecting (posting/getting) with other servers and retrieving data?

Can someone please guide me on how to utilize ajax in node.js to send and receive JSON data from another server? Is there a package available that allows for this functionality, similar to jQuery's $.ajax, $.post, or $.get methods? ...

Leveraging jest.unmock for testing the functionality of a Promise

I've implemented Auth0 for managing authentication in my React App. Below is the code snippet I am trying to test: login(username: string, password: string) { return new Promise((resolve, reject) => { this.auth0.client.login({ ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...

React- The Autocomplete/Textfield component is not displaying properly because it has exceeded the maximum update depth limit

My autocomplete field is not displaying on the page even though I wrapped it with react-hook-form for form control. When I check the console, I see this error: index.js:1 Warning: Maximum update depth exceeded. This can happen when a component calls setSt ...

The IE browser consistently retrieves outdated data from its cache

I always encounter the issue of IE browser loading old data from the browser history. To ensure that I am getting the latest data, I consistently need to clear the browser history. Is there a way to consistently load new data without having to manually cl ...

Tips for triggering a keyboard event to the parent in Vue 3

In my Vue 3 project, I have components nested five levels deep. The top-level component named TopCom and the bottom-level component called MostInnerCom both contain a @keydown event handler. If MostInnerCom is in focus and a key is pressed that it cannot ...

Setting Authorization with username, password, and domain in Angular 2 HTTP Request

I am facing an issue with calling an API method hosted on another machine using Angular 2 component with Http. When accessing the API from a browser, I can connect by entering a username and password as shown below: https://i.stack.imgur.com/JJqpC.png Ho ...

What is the syntax for utilizing cookies within the `getServerSideProps` function in Next.js?

I am struggling to pass the current language to an endpoint. Despite attempting to retrieve the language from a Cookie, I keep getting undefined within the getServerSideProps function. export async function getServerSideProps(context) { const lang = aw ...