Tips for effectively showcasing a leaflet map within a NuxtJS project

I've encountered an issue with my map while working on a project using NuxtJS and the library . The map is not displaying correctly. Below is my code snippet and a screenshot of the problem:

map.vue :

<template>
  <div id="map-wrap" style="height: 100vh">
    <no-ssr>
      <l-map :zoom="13" :center="[55.9464418, 8.1277591]">
        <l-tile-layer
          url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
        ></l-tile-layer>
        <l-marker :lat-lng="[55.9464418, 8.1277591]"></l-marker>
      </l-map>
    </no-ssr>
  </div>
</template>

nuxt-leaflet.js :

import Vue from 'vue';
import { LMap, LTileLayer, LMarker } from 'vue2-leaflet';

Vue.component('l-map', LMap);
Vue.component('l-tile-layer', LTileLayer);
Vue.component('l-marker', LMarker);

nuxt.config.js :

  plugins: [
    {
      src: '~/plugins/nuxt-leaflet',
      mode: 'client',
    },

    {
      src: '~/plugins/vue-my-photos',
      mode: 'client',
    },
  ],

See the screenshot of the result here: https://i.sstatic.net/7kUhI.png

Answer №1

After some investigation, I discovered that including the css from leaflet was necessary :

  head() {
    return {
      link: [
        {
          rel: 'stylesheet',
          href: 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="670b0206010b0213275649514957">[email protected]</a>/dist/leaflet.css',
        },
      ],
    }
  },

Answer №2

I have successfully implemented Vue Leaflet and it's functioning perfectly. Consider updating the center props from an array to an object.

<l-map :zoom="13" :center="{
        lat: -7.280976,
        lng: 112.796844,
      }">

full code

<div style="height: 350px; width: 100%">
      <client-only>
        <l-map
          ref="myMap"
          :zoom="zoom"
          :center="center"
          @update:center="centerUpdated"
          @click="handleClick"
        >
          <l-marker :lat-lng="regionCenter">
            <l-popup>Outlet Location</l-popup>
          </l-marker>
          <l-polyline
            :lat-lngs="polyline.latlngs"
            :color="polyline.color"
          ></l-polyline>
          <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
        </l-map>
      </client-only>
    </div>
data () {
  return {
      url: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
      attribution:
        '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
      zoom: 15,
      center: {
        lat: -7.280976,
        lng: 112.796844,
      },
      bounds: null,
      regionCenter: [-7.280976, 112.794944],
      address: {
        long: '',
        display: '',
      },
      polyline: {
        color: 'red',
        latlngs: [],
      },

  }
}

Answer №3

Sometimes in a Nuxt.js project, the CSS may not load entirely, causing issues with the Leaflet map's width and height. In order to address this issue, it is recommended to initially hide the map and then show it once the CSS and DOM have fully loaded.

<div v-if="map">
    <client-only>
      <l-map :zoom="13" :center="[selectedAddress.lat, selectedAddress.lng]">
        <l-tile-layer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png" />
      </l-map>
    </client-only>
</div>

data

data () {
  return {
    map: false
  }
}

mounted

mounted () {
  this.$nextTick(() => {
    setTimeout(() => {
      this.map = true
    }, 200)
  });
},

Answer №4

Include leaflet css globally in nuxt.config.js:

css: ['leaflet/dist/leaflet.css'],

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

Creating a translucent casing

Imagine I'm visualizing Wonder Woman maneuvering her Invisible Jet. The jet consists of various meshes and is predominantly transparent. When the transparent meshes overlap, they become less see-through. I aim to eliminate this overlap so that the tra ...

Please input a number that falls within a specified range

I need help with two text inputs that are connected v-model to a ref object. I also have two other refs, minimum (100) and maximum(1000). My goal is to allow users to input values within the range of the minimum and maximum values provided. If the value en ...

How can we use fetch to grab some data?

I put together an Express application quickly, here's how it looks: const express = require("express"); const app = express(); const port = 3000; app.get("/content/1/", (req, res) => res.send("Thinking about taking out a new loan? Call us today. ...

The functionality of Next.JS Cpanel Deployment Server.js appears to be malfunctioning

Trying to deploy my website on cpanel, I am utilizing a node.js application with cpanel. Here is the configuration: https://i.sstatic.net/AXap3.png However, when I start my server, it displays "503 service unavailable." https://i.sstatic.net/17JAu.png ...

Real-time functionality in React component and Apollo Client is not functioning as expected

I am struggling to develop a user system as it is not working in real-time, causing confusion for me. To illustrate my problem and code, I have set up a sample Sandbox. Please note that this example does not include any validation features and is solely f ...

Unable to reset input in a functional component using React JS

I have a component named TextInput that is responsible for rendering an input element: function TextInput({ type = "text", label, name, required = false }) { const [value, setValue] = useState(""); function handleChange(e) { se ...

Can Jquery use .hover to add a class or Child:hover to impact its parent element?

I have been searching for a solution tailored to my specific needs, and I am encountering difficulties in getting a seemingly simple jQuery code to function as expected. Here is the link to my basic fiddle: http://jsfiddle.net/LBHxc/ (I apologize for the ...

Why aren't my properties being reflected in the state after making changes?

Here is my Component Container code: import React, { Component } from 'react'; import { connect } from 'react-redux'; import Example from '../components/example.jsx'; class ExampleContainer extends Component { render() { ...

`'download as' feature using JavaScript and PHP`

I have implemented a JavaScript function on my website that, with the help of a PHP function, creates a file locally on the server in the same directory as the website files. The file name is only known to these JavaScript and PHP functions. Now, I am look ...

Tips for clicking the OK button in an alert box with Protractor

When working with AngularJS, I encounter the need to delete a link which triggers an alert box for confirmation. While attempting e2e testing using protractor, how can I confirm actions within an alert box? I attempted the following code snippet: browse ...

The payload is properly returned by the Reducer, however, the component is receiving it as

In my current project, I am developing an application that involves fetching data from a firebase database. This particular database does not require authentication, and I have already adjusted the access rules to allow for public access. One of the actio ...

In three.js, it is important to understand that Vertex and Vector3 are not simply

When I started using three.js revision 48, I created vertices connected by lines without any issues. However, upon updating to revision 65 from 48, an error message appeared stating that Vertix is deprecated and should be replaced by Vector3. Unfortunately ...

Using jQuery and JSON data to dynamically populate a second dropdown menu with filtered options

I am working on a form with two drop-down menus and a text box. The first drop-down contains static values, while the second drop-down is populated dynamically from a JSON array. My goal is to filter the options in the second drop-down based on the selecti ...

"Using VueJS slots in combination with a v-for loop may result in incorrect elements being displayed

I'm currently working on developing a component that is designed to exhibit a subset of items that are provided to it. At this point, I have a 'sublist' component with named slots set up in the following manner: ... data: () => ({ ...

Utilizing the same id in JavaScript for dual purposes while integrating Skycons

I'm currently using Skycons and it's working perfectly fine. However, I've run into an issue where if I have 2 canvas IDs, it will render the first one but leave the second one blank. In my JavaScript code: var icons = new Skycons({ ...

Attempting to design a universal form field component

While working on a web app with Vue, I found myself in need of creating multiple forms. To make this process easier, I started developing a generic input component that can be reused throughout the application. The plan was to be able to specify the number ...

remove website tracking data by using developer tools console

In JavaScript, we have the ability to delete local storage or session storage items using the clear() method: localStorage.clear(); sessionStorage.clear() However, is there an equivalent method like cookies.clear() to clear cookies? If so, how can it be ...

Clicking on the search box will remove the item that is currently displayed

Currently, I am working on creating a dropdown menu that includes a text box. The goal is for the items to appear when the text box is clicked, and for the selected item to turn green once clicked and then display in the text box. I'm interested in fi ...

What is the method for obtaining a unique id that changes dynamically?

Having trouble accessing the dynamically generated ID in jQuery? It seems to work fine in JavaScript but not in jQuery. Here's an example of the issue: My jQuery code: var img = $("#MAP"+current_img_height); $("#map").css({'height': img.h ...

Ways to retrieve a property that is dynamically generated within a React component

In the code snippet below, I have registered the TextField name as M1.${index}.M13-M14 and it is marked as required. However, I am unable to locate the property accessor using errors[`M1.${index}.M13-M14`]?.type, which prevents the error from being gener ...