How can you extract path information from an SVG file and utilize it as a marker on Google Maps?

I want to implement a custom SVG icon as a marker on Google Maps.

I have obtained this SVG file:

<svg  xmlns="http://www.w3.org/2000/svg" width="510px" height="510px" viewBox="0 0 510 510">
    <g
        stroke="black"
        stroke-width="10"
        fill="white"
    >
        <path d="M497.25,357v-51l-204-127.5V38.25C293.25,17.85,275.4,0,255,0c-20.4,0-38.25,17.85-38.25,38.25V178.5L12.75,306v51
        l204-63.75V433.5l-51,38.25V510L255,484.5l89.25,25.5v-38.25l-51-38.25V293.25L497.25,357z"/>
    </g>
</svg>

Although I am not very familiar with SVGs, I was able to use the path attribute d from the SVG file as a string successfully:

mounted() {
    new google.maps.Marker({
         position: this.flight.position,
         flight: this.flight,
         map: this.map,
         icon: {
             path: "M497.25,357v-51l-204-the-string-goes-on-and-on",
             scale: .04,
             fillColor: '#FFFFFF',
             fillOpacity: 1,
             strokeWeight: 1,
             rotation: this.flight.trueTrack,
             anchor: new google.maps.Point(250, 400)
         }
    })
 }

However, I would like to avoid using a long string for path. Is it possible, for instance, to import the SVG file from the asset folder and reference its path attribute d as a variable?

Pseudocode (I may be completely off):

import svgFile from '../assets/file.svg';

const path = document.querySelector("path");
const d = path.getAttribute("d");

(...)

mounted() {
    new google.maps.Marker({
         position: this.flight.position,
         flight: this.flight,
         map: this.map,
         icon: {
             path: d,
             (...)
         }
    })
 }

Or perhaps there is another, more efficient way to eliminate hardcoded strings in path? Any help would be greatly appreciated!

Answer №1

Alright, I finally figured it out.

First and foremost, the file needs to be imported as text:

import svgPlane from '!raw-loader!../assets/airplane.svg';

In order to accomplish this, I had to install raw-loader:

npm install raw-loader --save-dev

Next, I had to utilize DOMParser to parse it and reference the data similar to a DOM element:

  mounted() {
    const parser = new DOMParser();
    const svgPath = parser
      .parseFromString(svgPlane, "image/svg+xml")
      .querySelector('path')
      .getAttribute('d')

    new this.google.maps.Marker({
      position: this.flight.position,
      flight: this.flight,
      map: this.map,
      icon: {
        path: svgPath,
        (...)
      }
    })
  }

No more magic numbers involved! This is the solution I've been searching for.

Answer №2

Give this a shot.

let pathToIcon = '../assets/file.svg'; 
console.log(pathToIcon);//Ensure URL is accurate.

mounted() {
    new this.google.maps.Marker({
     position: this.flight.position,
     flight: this.flight,
     map: this.map,
     icon: pathToIcon,
 })  }

Answer №3

When working with vanilla JavaScript, you can easily incorporate the values from the marker's icon property like this:

  const path = document.querySelector("path");
  const d = path.getAttribute("d");

  var marker = new google.maps.Marker({
    position: {lat: -25.344, lng: 131.036},
    map: map,
    icon: {
      path: d
    }
  });

Vue should support a similar approach by utilizing an import method.

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

Enlarge the div with a click

I was looking for a solution on how to make a div expand when clicked using jQuery I came across a tutorial that seemed simple and perfect, but I couldn't get it to work when I tried to replicate the code. Do you know if this code is still valid wit ...

What steps are necessary to configure .eslintrc to identify the use of 'require'?

I recently started using ESLint and successfully integrated it with IntelliJ. Initially, ESLint did not recognize node out of the box. After consulting the documentation, I created a configuration file named .eslintrc at the project's root folder, sp ...

Operating Laravel-Mix 8 while executing the watch command

How can I successfully load a Vue Component in the Public file using npm run watch? Node.js v14.15.0. npm 6.14.8 Laravel Installer 4.1.0 When running npm run watch in my project directory, I encountered the following error ...

Enhancing the functionality of ng-click within ng-repeat

I am seeking a solution to enhance the functionality of the ngClickDirective by implementing a custom listener. The provided code successfully works with ng-click elements that are not nested within ng-repeat: $provide.decorator('ngClickDirective&apo ...

Onload, capture page elements, delete them, and then access the original content

I am encountering two DIV elements on my page that I need to capture upon loading the page and preserve their contents until the page is refreshed. The nested DIV element is contained within the other one. After locating these elements initially, I want t ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

Manipulating Objects and Arrays

When I retrieve data from a database query in Node.js using Postgres with Knex, I get an array of objects structured like this: (condensed version) [ { tvshow: 'house', airdate: 2017-02-01T00:00:00.000Z }, { tvshow: ' ...

Incorporating conditional Components into Vuejs templates

I have a compilation of various events that are being brought in as logTypes export default { LOGIN: "login", LOGOUT: "logout", } Also, I have two distinct components for each of these occurrences. <LogTypeLogin :item="item ...

Generate a unique ID each time the page is loaded or refreshed

I'm currently working on a function that will display a unique ID or a different video each time the page is loaded or refreshed. My main objective is to design a splash intro popup that features a <section> with a full-screen YouTube video bac ...

Is there a way to prevent the background color from filling the entire container?

In the visual representation provided below, there is a header element consisting of a back arrow and a name. The arrow container has been assigned flex: 1, while the arrow and name containers have been set to flex-start and flex-end respectively. This co ...

"Looking for a way to automatically close the <li> tag in Vuejs when clicked outside

clickOutside: 0, methods: { outside: function(e) { this.clickOutside += 1 // eslint-disable-next-line console.log('clicked outside!') }, directives: { 'click-outside': { ...

Can an onload function be triggered within the location.href command?

Can a function be called onload in the location.href using jQuery? location.href = getContextPath() + "/home/returnSeachResult?search=" + $('#id-search-text-box').val() + "&category=" + $('#search_concept').text() + "onload='j ...

Iterate through the JSON data values using a loop and showcase each one by presenting them in individual cards

I'm having trouble determining which type of loop to use in this situation because I am still learning jQuery and JS. On the result page, I have set up cards to separate each piece of data from the JSON file, but I am unsure how to actually display th ...

Disabling the "Master Detail" feature in MUI

Exploring the functionality of MUI's Master Detail feature raised a question about CSV exporting from a Data Grid. When trying to export to CSV with the Master Detail implementation, the export functionality seemed to break (as expected). It technical ...

"Utilize Ajax to load PHP content and dynamically refresh a specific div

I have implemented an image uploading system, but now I want to incorporate a feature that allows users to rotate the uploaded images using Ajax. The challenge I'm facing is that if the session variable is lost during a full page update, I need to ens ...

Exploring Autocomplete Functionality with SQLite Integration in Flask

I have been searching for a solution to my problem without any success. My SQLite database contains electronic products, and I have a search box that allows users to search for products by typing in their name. However, I want to enhance the user experienc ...

The process of assigning a function to an object in JavaScript is currently not functioning properly

After updating a Vue2 project to Vue3, I ran into an issue with Javascript. It seems that the language now prevents me from assigning a function to an object. In the code below, I define a function "bar" within a loop. While I can successfully call the fu ...

Is it feasible to convert a Google Drive spreadsheet into JSON format without needing the consent screen?

I'm working on incorporating a JSON feed directly from a private spreadsheet (accessible only via link) onto my website. In order to do this, I must create a new auth token using OAuth 2.0, which is not an issue. However, the Google Sheets API v4 mand ...

How can I incorporate a counter into my ng-repeat loop in Angular?

Do you know where I can find documentation on adding a numbered count to each item returned by an ng-repeat in Angular? This is not like assigning an Id, but more like, if 4 items are returned, each JSON object could include a number before the data. Her ...

At what specific instances can keys be advantageous in Vue?

It seems that the concept of keys is still a bit unclear to me even after going through the documentation. My understanding so far is that keys are used to ensure that each item is unique. Typically, I've been adding a key only when using a v-for, and ...