0

The title is not the best explanation. I'm creating a beer flavour graph (no map tiles involved) that uses a custom icon of each beer bottle for each marker. So far so good.

screenshot of the current build

I've got a div outside the map, where I want to display the same bottle png used for the icon (but larger) when each marker is clicked...

for (var i=0; i < markers.length; ++i )
{
var IconVar = L.icon({
  iconUrl: markers[i].bottleurl,
  shadowUrl: 'images/beer-shadow.png',
  iconSize: [36, 120],
  shadowSize:  [74, 50],
  iconAnchor: [16, 60],
  shadowAnchor: [35, -26],
  popupAnchor: [0, -65]
})        

var bigbottleUrl = markers[i].bottleurl;

 L.marker( [markers[i].lat, markers[i].lng], {icon: IconVar}, )
  .bindPopup( 'Text and some custom content bla bla', customOptions )
  .on('click', function(e){document.getElementById("bigbottle").src = bigbottleUrl;}).addTo( beermap ); 
}

Which works to a point, but defaults to the last marker that is set from a json file. Maybe I can't call different variables from inside the loop, or I haven't set up my loop right.

I've looked through lots of questions here, and tried making it more specific using e.popup._source and this.option and making it specific using _leaflet_id but I'm pushing well beyond my understanding of javascript!

Any ideas?

Cmeet
  • 1
  • 1
  • Like the colours! :-) – ghybs Nov 25 '17 at 11:40
  • That is a classic JavaScript beginner's mistake. Look for closure, callback and binding value. – ghybs Nov 25 '17 at 11:41
  • I was hoping to avoid that and do something simpler! The image I want to load is the marker, this is close... [onclick](https://stackoverflow.com/questions/10270937/how-to-get-image-source-path-on-onclick-event-of-that-image-clicked) – Cmeet Dec 12 '17 at 09:40

1 Answers1

0

After going down a few dead ends this was the solution.

var imgUrl;

document.addEventListener('DOMContentLoaded', function() {
   document.addEventListener('click', function(event) {
      if (event.target.className == 'leaflet-marker-icon leaflet-zoom-animated leaflet-interactive') {
      var imgSrc = event.target.src; 
      var imgFile = imgSrc.substring(imgSrc.lastIndexOf('/')+1); 
      imgUrl = 'images/' + imgFile;
      document.getElementById("bigbottle").src = imgUrl;
      }
   });
});

There's probably a bit of redundant code, but this was the most efficient way, not putting an onClick event onto everything or having a complex variable that I didn't know how to construct!

Cmeet
  • 1
  • 1