Search code examples
nuxt.jsmapbox-gl-jsmapbox-marker

new mapboxgl.NavigationControl() doesn’t work


I´ve been trying in many ways how to add the navigation control to my map, the window does not appear, and when i see my console it doesn’t throw any error. This is my code, is from the Mapbox GL JS documentation:

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

</template>

<script>
/* eslint-disable */
export default {
  computed: {
    location () {
      // eslint-disable-next-line no-console
      console.log(this.$store.state.location)
      return location
    }
  },
  mounted () {
    this.createMap()
    // document.querySelector('.mapboxgl-ctrl-geocoder input').focus()
  },
  methods: {
    createMap () {
      const mapboxgl = require('mapbox-gl')
      const MapboxGeocoder = require('@mapbox/mapbox-gl-geocoder')

      mapboxgl.accessToken = 'pk.eyJ1IjoicGlucGFydGRldiIsImEiOiJjajBqOXh0anAwMDFkMzNwbW5qMzVuZGo0In0.ltvQzboVtprxfeFAVOw1GA'

      // init the map
      var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/ximenabc/ck44uqzs21gk71cmtma66htry',
        center: [-96.707, 17.065], // starting position [lng(-180, 180), lat(-90, 90)]
        zoom: 15,
        pitch: 0,
        minZoom: 2,
        maxZoom: 20,
        attributionControl: false,
        showCompass: true
      })

      map.addControl(new mapboxgl.NavigationControl())

      this.MapboxGeocoder = new MapboxGeocoder({
        accessToken: [MY-ACCESS-TOKEN],
        marker: true
      })
      // mapboxgl.addLayer({
      //   id: 'points'
      //   type: 'circle'
      // })
    //   var marker = new mapboxgl.Marker({
    //     draggable: true
    //   })
    //   .setLngLat([-96.707, 17.065])
    //   .addTo(map);
    //   marker.on('dragend', onDragEnd);
     },
  }
}
</script>

<style>
  #map {
    max-height: 20cm;
    min-height: 15cm;
  }
</style>

As you can see, i also tried to add some points, but it didn’t work. I´m working with Nuxt btw


Solution

  • Ok, the issue is that you have not included Mapbox's CSS. The navigator control is present but it is invisible.

    You can add this at the bottom, just above </script>

    import 'mapbox-gl/dist/mapbox-gl.css';

    If that doesn't work, add this to your index.html:

    <link href="https://api.mapbox.com/mapbox-gl-js/v1.6.1/mapbox-gl.css" rel="stylesheet" />

    Or in the nuxt.config.js, as described here.