0

I add a marker "beginPoint" for each element in the array "starts". When initializing the webpage the onclick function runs for each marker sequentialy without me clicking on them (this is not intentional).

The onclick function sends a request to my API which will return the data of the "track" associated with the marker that was clicked on. Finally this data is injected into my html page.

My probmel is thus the fact that the onclick function doesn't seem to trigger when I click on a maker but runs when te page loads for all of them. Thanks in advance!

    //marker at the beginning of each track
    var starts = Object.values(starts);
    starts.forEach(function (element){
        var latlng = new L.LatLng(element.Latitude, element.Longitude);
        var beginPoint = L.marker(latlng, {icon:beginIcon}).addTo(mymap);
        beginPoint.on('click', onClick(element.id));
    });

}

//function called when clicking on marker @home
function onClick(e) {

    var request = {
      id: e
    };

    var url = "api/tracks/select"

    fetch(url,
        {
            method: 'post',
            headers: {'Content-type':'application/json'},
            body: JSON.stringify(request)
        }
    )
        .then(response => response.json())
        .then(json => insertTrackDetails(json));
}

// set the data corresponding to the selected track
// to the details field in the home view
function insertTrackDetails(data){

    var data = Object.values(data);
    var image = data[0].image;
    image = image.replace('public/images', '/storage/images');

    document.getElementById('pills-detail').innerText = data[0].description;
    document.getElementById('pills-image').src = image;

    //TODO document.getElementById('pills-comments').innerText = data.description;
}

1 Answers1

1

When you add a function in the .on() with () it is excuted immediately and not while clicking. So change this beginPoint.on('click', onClick(element.id)); to this beginPoint.on('click', onClick);

Then you have the problem how to know the id. Add the id to the marker and then read it out:

starts.forEach(function (element){
        var latlng = new L.LatLng(element.Latitude, element.Longitude);
        var beginPoint = L.marker(latlng, {icon:beginIcon}).addTo(mymap);
        beginPoint.elmId = element.id; // store the id on the marker
        beginPoint.on('click', onClick);
    });
...


//function called when clicking on marker @home
function onClick(e) {
    var id = e.target.elmId; // readout the id from the marker
    var request = {
      id: id
    };
    ...
Falke Design
  • 10,635
  • 3
  • 15
  • 30