Efficient methods for setting up Leaflet in Nuxt/Vue

I am attempting to integrate leaflet into my Nuxt 3 project without relying on wrappers like @nuxtjs/leaflet. However, I encountered an issue where it says 'Could not find a declaration file for module 'leaflet', despite having installed the leaflet package from npm.

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

//script
<script setup lang="ts">
import * as L from "leaflet";

onMounted(() => {
    const map = L.map("map").setView([34.299074, -118.45949], 13);
    L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 19,
        attribution:
            '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    }).addTo(map);
    L.marker([34.299074, -118.45949]).addTo(map);
});
</script>

Afterwards, I included a css file in nuxt.config.ts:

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

Currently, all I see is an empty map with zoom buttons and the label 'Leaflet | © OpenStreetMap' in the bottom-right corner.

You can view the problem here: https://stackblitz.com/edit/nuxt-starter-jcj5xn?file=app%2Fpages%2Findex.vue,app%2Fapp.vue,app%2Fpages%2Fevents.vue. Clicking 'Go to Events' displays an empty map. When reloading the page, I encounter the error 'window' is not defined. In my actual project, I cannot interact with the map or see any markers. Additionally, I receive the message 'Attempted to load an infinite number of tiles', even though https://tile.openstreetmap.org/{z}/{x}/{y}.png is a valid tileLayer, according to the official documentation at leafletjs.com/examples/quick-start.

Seeking a potential solution.

Answer №1

Typically, when popular packages are missing TypeScript types, they are usually paired with corresponding packages from the @types scope. For example, installing @types/leaflet along with leaflet is a common practice.

The issue of an error occurring on page reload specifically pertains to the Nuxt server. The leaflet module is designed for client-side use and improperly accesses the window global variable. Whether the module is loaded on the server side or not depends on Nuxt's build tool discretion. To prevent this issue, the module should not be imported on the server side:

onMounted(async () => {
  const L = await import('leaflet');
  ...

The problem of map tiles not displaying properly is specific to a particular sandbox. In the browser devtools, it can be observed that while the map is rendered, the requests for map tiles are flagged as "blocked":

...

The root cause is explained in the request details and the "issues" tab:

not-set Cross-Origin-Resource-Policy:

Due to your site having the Cross-Origin Embedder Policy (COEP) active, each resource must specify a suitable Cross-Origin Resource Policy (CORP). This requirement restricts the loading of cross-origin resources that do not explicitly allow permission to be loaded.

To address this, include the following in the resource’s response header:

Cross-Origin-Resource-Policy: same-site if the resource and your site are hosted on the same domain.

Cross-Origin-Resource-Policy: cross-origin if the resource is served from a different location than your website. ⚠️By setting this header, any website can embed this resource.

This issue arises because the demo is running within a preview box, imposing cross-origin restrictions on an iframe. This can be resolved by opening the preview in a separate window, which may have varying success on Stackblitz, or by running Nuxt locally.

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

Problem with opening the keyboard feature in an Ionic app

Hello everyone, I'm relatively new to Ionic development and I've been trying to integrate a keyboard plugin into my application that opens from the footer and focuses on input fields for entering values. Here is the link to the plugin I used: ht ...

What is the best way to trigger a function in the parent component using an event from the child component?

I'm currently immersed in learning React and am tackling the challenge of creating a game where the cards shuffle with each attempt. The card array and shuffle function are located in a parent component (using map to display the cards), while the retr ...

No reply from Axios after using async await

Here's a simple method that utilizes Axios to make a call to an API. Interestingly, when the method is called, it doesn't display any output, no logs or error messages. async deActivate(product: Product): Promise<void> { try { ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...

Obtaining the content within a <script> tag with Selenium

Currently, I am developing a web scraper, and the website I am scraping contains a script element that looks like this: <script type="text/javascript"> jQuery(window).load(function($) { Morris.Line({ ...

Is it true that Safari restricts AJAX Requests following a form submission?

I've developed a JavaScript-based upload progress meter that utilizes the standard multipart submit method instead of submitting files in an iframe. The process involves sending AJAX requests during submission to retrieve the percentage complete of th ...

issues with passing values on second click using ajax and jquery

Just starting out with JavaScript, jQuery, and AJAX and running into issues with a basic script to load more data from a database upon button clicks. The first load more button click works fine. But subsequent clicks do not pass values and do not execute. ...

Developing a table with JavaScript by parsing JSON data

Starting off, I am relatively new to working with JavaScript. Recently, I attempted to generate a table using data from a JSON file. After researching and following some tutorials, I successfully displayed the table on a web browser. However, I noticed tha ...

Utilizing Bootstrap combobox to easily select values by typing them in

I recently started utilizing the bootstrap combobox plugin on my website. Strangely, I've noticed that when selecting from the options in the dropdown list, choosing NewYork works smoothly. However, if I type "New" and attempt to select "New York" fr ...

A Python program that creates an HTML webpage

I am currently working on a Python script that, when launched on localhost with Apache, will generate an HTML page. Here is the script (test.py): #!/usr/bin/python # -*- coding: utf-8 -*- import cgitb cgitb.enable() import cgi form = cgi.FieldStorage() ...

trigger the eventHub within a Vuex store

I'm trying to figure out how I can utilize this.$eventHub.$emit('something'); within vuex. The reason I need this is because I'm using a plugin called vuex-persist-indexeddb, which has a method called rehydrated that fires when the data ...

Utilizing JQuery for parsing information

I am working on a project that involves displaying Google Maps API on one tab and images on another within a container. The goal is to have the image in the second tab change when a location is selected from the list. To achieve this, I have set up a hidd ...

Error message encountered in PHP due to an undefined index

My goal is to add items from a form to a table named products. The form layout can be seen here: https://i.stack.imgur.com/f9e08.png The "Add more suppliers: +" link adds a new row to the form when clicked. The corresponding script for this action is as ...

What is the solution to fixing the error message "SyntaxError: missing ) after argument list" in JavaScript?

I wrote some code in HTML/JavaScript/PHP, and in the 3rd echo statement, I added a button that calls the deleteAttribute() function when clicked. However, I encountered an error at the 3rd echo statement with (type = "button"): "Uncaug ...

Tips on transferring a selected value from a dropdown menu to a getJSON URL

I am working on a dropdown menu containing the names of Surahs from the Quran. How can I pass the value of the selected item in the dropdown to a function? $.getJSON("http://api.globalquran.com/surah/2/quran-simple?key=api_key&jsoncallback=?", { ... ...

How should the nonce be properly set in the csp policy?

I've been attempting to incorporate a nonce into the csp policy but it's not functioning as anticipated. Here's the code snippet I'm currently using for testing purposes: server.js express.use(function(req, res, next) { res.set( ...

JavaScript Password Form Submission - Enter your password in the form

I need assistance with setting up a password for a form. Users should be able to enter a password into a specified field, click submit, and if the password is correct, they will be redirected to buybutton.php in the same window. If the password is incorr ...

I am looking to save the data entered in an HTML form directly into a JSON file within the webpage

I am currently storing the value in an array on the server, but I would like to store it only on the client side within the webpage. I want to write the form data from the HTML form into a JSON file that remains on the page itself and is not sent to the ...

Display a placeholder page during the processing of an asynchronous task by Express JS

Perhaps this issue is either too simple to be overlooked or too complex to tackle, but despite my efforts of over 3 hours searching for a solution, I am unable to find one. It seems like it should be a common problem and I am just too inexperienced to loca ...

Adding animation to a div that is being appended can be done by using JavaScript functions and

I am looking to incorporate animation into my title div. Below is the HTML code I have so far: <div class="particles" id="tittle"> <!-- Displaying title from Firestore using JavaScript --> </div> Here is the CSS cod ...