Is there a way to directly load an SVG for a leaflet divIcon without having to import it through a js file?

There is a sample Vue 2 project available at this GitHub repository

I am looking to integrate an SVG into a leaflet divIcon.

      const cloudIcon = L.divIcon({
        html: thecloud, // this.cloudSvg, // thecloud,
        className: 'my-custom-icons',
        iconSize: [size, size],
        iconAnchor: [size/2, size/2]
      })

In addition, I may need to make some modifications to the SVG, so having the actual SVG source is necessary.

I found that placing the SVG inside of a javascript file and importing it using:

import {thecloud} from './TheCloud';

yields the desired result:

https://i.sstatic.net/Ne9iM.png

I attempted the following approach as well:

  data() {
    return{
      cloudSvg: require('./TheCloud.svg')
    }
  },

However, this did not work as expected and produced this result instead:

https://i.sstatic.net/r1ZYD.png

Is there another way to achieve this without having to place the SVG source inside javascript files? It seems like there should be a simpler solution.

Answer №1

In my opinion, the most efficient approach is to utilize what I like to refer to as the fetch-method.

I have implemented the following changes:

  1. relocated TheCloud.svg to the public/ directory.
  2. utilized the fetch function to retrieve the svg source.
const response = await fetch( "/TheCloud.svg");
const source = await response.text();

While embedding SVGs within the code works satisfactorily for a limited number of SVGs, this method shines when there are numerous SVGs involved.

The repository has been updated with the implementation of the fetch-method.

Answer №2

After some trial and error, I have managed to find a solution that works for me. However, I believe there is still room for improvement.

If you're interested in the changes I made, they can be found on the raw-loader branch of the project.

  1. yarn add raw-loader
  2. To configure the raw-loader, I created a vue.config.js file at the project's root with the following contents:
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('raw-loader')
      .test(/\.txt$/i)
      .use('raw-loader')
        .loader('raw-loader')
        .end()
  }
}
  1. I updated my data() method as follows:
  data() {
    return{
      center: [37.781814, -122.404740],
      cloudSvg: require('./TheCloud.svg'),
      cloudSrc: require('./TheCloud.txt')
    }
  },

The addition of

cloudSrc: require('./TheCloud.txt')
was necessary to make it work correctly.

TheCloud.txt serves as a duplicate of TheCloud.svg, but with a different extension to ensure processing by the raw-loader.

  1. I changed the implementation of divIcon to this:
      const cloudIcon = L.divIcon({
        html: this.cloudSrc.default,
        className: 'my-custom-icons',
        iconSize: [size, size],
        iconAnchor: [size/2, size/2]
      })

Although some parts of the process remain unclear to me, such as the need for .default and aspects of webpack configuration, the overall functionality has been successfully achieved.

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

Firefox not rendering responsive YouTube embed properly

This method of embedding seems to be functioning well on all browsers except for Firefox; I took advantage of a free trial at crossbrowsertesting.com to verify. I’m not using a direct iFrame embed, and all the solutions I’ve come across are related to ...

AngularJS continues to display an "Invalid Request" message whenever the requested resource is unavailable

When I try to fetch a group of images through AJAX and exhibit them on the page using ng-repeat, an issue arises with the image source tags. These tags send incorrect requests to the server before the collection is retrieved, leading to error messages in t ...

Top strategy for monitoring a user's advancement in reading different text segments

If you are familiar with zyBooks, I am looking to implement a similar feature where users can track the sections they have read and mark them as completed with a button. However, I am struggling conceptually with determining how best to structure my mongo ...

How can we stop Vuetify from overwriting Bootstrap3's classes when using treeshaking?

I am currently in the process of transitioning an app from jQuery/Bootstrap3 to Vue/Vuetify. My approach is to tackle one small task at a time, such as converting the Navbar into its own Vue component and then gradually updating other widgets. Since the n ...

When invoking a function using ng-init within ng-repeat, only the final item in the iteration yields a result

My goal is to update the content of a progress bar for each row in a table using ng-init within ng-repeat. Here is my code snippet: The code snippet for the view section is as follows: <tr ng-repeat-start="p in projetsListe" ng-init={{progressBar($in ...

Tips for Utilizing Both getElementByID and getElementByTagName Functions in JavaScript

Hi! I'm a beginner in JavaScript and I've managed to retrieve some data using getElementById. Now, I want to extract a specific part using getElementsByTagName. document.getElementById('titleUserReviewsTeaser').innerHTML; " < ...

The jssor slider cannot be initialized when it is loaded through ajax requests

Incorporating jQuery's .load() function, my website dynamically loads the HTML code for the jssor slider. To verify the functionality of my code, I have developed a duplicate page which already includes the necessary slider code without utilizing an a ...

Combining Arrays in AngularJS with an owl-carousel Setting

My goal is to implement an endless scrolling carousel in AngularJS using owl-carousel. The idea is to load new items every time the carousel is fully scrolled and seamlessly merge queried elements with the existing list. However, I've encountered a pr ...

Canvas with a button placed on top

I am working with a canvas and trying to position an HTML element over it using CSS. My goal is for the button to remain in place on the canvas even when resizing the entire page. Here is the code I am currently using. https://jsfiddle.net/z4fhrhLc/ #but ...

Encountering difficulty inserting ajax response into a specific div element

What could be the issue? I've included the getElementById and I am receiving a response, as confirmed by Firebug. The response is correct, but for some reason it's not populating my div area. <script> $(document).ready(function () { $( ...

Looking for a Communication Manager specifically designed for Vue components?

While working on a Vue.js project, I found myself creating and utilizing numerous components. But soon enough, I encountered the challenge of managing multiple eventemitters and props. To better illustrate this issue, let's consider an example scenar ...

Create a specific part of a webpage that can be scrolled through

In a unique way, I have designed a page where the only way to navigate is by simply clicking. To achieve this, I have implemented the following custom CSS: body{ overflow:hidden; } However, I have encountered a problem where I am unable to scroll to ...

Using an array.map inside a stateless component with React.createElement: the type provided is invalid

There is a component called BasicDetail in my code with the following structure: import React from "react"; import { Grid, Form } from "semantic-ui-react"; const BasicDetail = ({DetailData}) => { return( <div> <Grid.Ro ...

How can the total price for a shopping cart be computed in React/Redux?

After extensive searches on Google and SO, I'm still coming up empty-handed when it comes to calculating the total price of items in a cart. Many tutorials stop at basic cart functionalities like "Add item to cart" or "increase/decrease quantity", but ...

What are some effective strategies for enhancing the performance of React user interfaces?

I'm currently dealing with a performance challenge in one of my React applications. What are some best practices to enhance the responsiveness of the User Interface? One approach could be to minimize the usage of conditional expressions like { carIsR ...

Error in clientWidth measurement providing inaccurate width

I recently adjusted the width of an image (img tag) to be 1150px * { margin: 0; padding: 0; box-sizing: border-box; user-select: none; } #background-image-myos { border: 2px solid black; border-radius: 5px; width: 1150px; } Sur ...

React scroll not triggering class changes

In the function handleScroll, I am attempting to add a class of red when scrolling down to a specific limit, otherwise applying a class of blue. However, it seems that it is only entering the else statement and also logging undefined for e.target.scrollTop ...

Placing a component within a .jsx file instead of utilizing a .css file for positioning

Seeking a way to position a component within a .jsx-file, rather than a .css-file, to accommodate multiple instances of the same component performing various tasks on different parts of the page. Avoiding duplication of files with minor CSS class changes, ...

What are the best practices for managing promises effectively?

Currently, in my Angular application, I am utilizing $odataresource for handling data retrieval and updates. The code snippet I am working with is as follows: var measure = $odataresource("http://windows-10:8888/ChangeMeasure/"); var myMeasure = measure ...

Struggling to accurately convert the string into a date object

I have an array of objects structured like this: const days = [ { _id: 12312323, date : '30/12/2021', dateStatus : 'presence' }, ... ] I am looking to convert the date property from a string to a Date object using the follo ...