ChaiM09
ChaiM09

Reputation: 21

How do I add custom image to mapbox marker?

const marker = document.createElement('div');
      marker.innerHTML = `<img src="../../assets/FuelPin.png" style="height: 56px; width: 44px" alt=""/>`;

      new mapboxgl.Marker(marker)
          .setLngLat(lngLatPopup)
          .addTo(this.map);
    },

In the above code the src from img attribute is not loading the image. I tried using :src to bind as vue component but it is being rendered as string. My relative path to the image exists as well.

Upvotes: 2

Views: 1449

Answers (1)

Kristofor Carle
Kristofor Carle

Reputation: 1425

In general changing innerHTML with JavaScript is not something frameworks like Vue or React will let you do (see https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations)

Here is the plain JS example from the Mapbox GL website:

const el = document.createElement('div');
const width = marker.properties.iconSize[0];
const height = marker.properties.iconSize[1];
el.className = 'marker';
el.style.backgroundImage = `url(https://placekitten.com/g/${width}/${height}/)`;
el.style.width = `${width}px`;
el.style.height = `${height}px`;
el.style.backgroundSize = '100%';
 
el.addEventListener('click', () => {
window.alert(marker.properties.message);
});
 
// Add markers to the map.
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(map);

From https://docs.mapbox.com/mapbox-gl-js/example/custom-marker-icons/

One pro tip, if you have lots of images to load (like thousands of markers) you will get better performance if you have MapboxGL render it in WebGL vs using the DOM, for that see: https://docs.mapbox.com/mapbox-gl-js/example/add-image/

Upvotes: 2

Related Questions