Home > Net >  Marker custom dynamic icon text is blank
Marker custom dynamic icon text is blank

Time:12-29

Working on a project that will have live pricing across a map that needs to be updated dynamically.

I have created a custom icon like below and need to be able to dynamically update the text on the icon

var myIcon = L.divIcon({className: 'my-div-icon', html: '<div  id="test"></div>'}); 

L.marker([51.5, -0.09], {icon: myIcon}).addTo(map);

document.getElementById("test").innerHTML = 11;

The icon displays on the map but is blank, the number doesn't appear and no errors in the console

Still quite new to javascript and leaflet so would appreciate if someone can point me in the right direction here

CodePudding user response:

Update:

Ive just figured out its because html element IDs have to be unique and I was reusing the same div ID within a loop for multiple markers.

CodePudding user response:

Cannot reproduce. https://codepen.io/SioGabx/pen/BaPjqow

// Initialize the map and assign it to a variable for later use
// there's a few ways to declare a VARIABLE in javascript.
// you might also see people declaring variables using `const` and `let`
var map = L.map('map', {
    // Set latitude and longitude of the map center (required)
    center: [51.5, -0.09],
    // Set the initial zoom level, values 0-18, where 0 is most zoomed-out (required)
    zoom: 11
});
 

// Create a Tile Layer and add it to the map
var tiles = new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  minZoom: '1'}).addTo(map);


var myIcon = L.divIcon({className: 'my-div-icon', html: '<div  id="test"></div>'}); 
L.marker([51.5, -0.09], {icon: myIcon}).addTo(map);
document.getElementById("test").innerHTML = 11;
#map { 
  height: 100vh;
}

.leaflet-popup-content-wrapper {
  width: 100%;
}

#test{
  background-color:red;
  color:white;
  transform:scale(2)
}
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<div id="map"></div> 

  • Related