Cristian
Cristian

Reputation: 11

Problems with leaflet marker and the 'onclick' event

I am using PHP 7, leaflet 1.5.1 and I am looking to call an AJAX when the marker is clicked to display content in a different DIV than the map.

The problem is that the function does not wait for the 'click' and is automatically activated when the page is loaded and shows in the DIV that it listens for the parameter of the last marker.

And then when I click on a marker, nothing happens, of course

Ideas?

THE SCRIPT

<script src='https://code.jquery.com/jquery-3.4.1.js' integrity='sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=' crossorigin='anonymous'></script>
    <script>
     function mostrar2(id){
     var parametro = {id : id};
     $.ajax({
       data: parametro,
       url: 'elphp.php',
       type: 'post',
       beforeSend: function(){$("#panel").html("Thinking...");},
       success: function(response){$("#panel").html(response)}
       });        
     }
    </script>

DIV THAT LISTENS

<div class="col-lg-3" id="panel">

MAP DIV

<div class="col-lg-9 map" id="map" style="width: 400px; height: 400px;">
 <script>
  var mymap = L.map('map').setView([51.505, -0.09], 13);
  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
     maxZoom: 18,
     attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
                '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
     id: 'mapbox.streets'
}).addTo(mymap);

L.marker([51.5, -0.09]).addTo(mymap).on('click', mostrar2(15741));
L.marker([51.5, -0.99]).addTo(mymap).on('click', mostrar2('11'));

</script>
</div>

AND THE PHP

<?php
    $trajo = $_POST['id'];
    echo "YOU SENT : " . $trajo;
?>

This is how it looks

Upvotes: 0

Views: 1933

Answers (1)

Cristian
Cristian

Reputation: 11

A friend solved it with this simple change.

The issue: mostrar2 function was executed right away, and because mostrar2 returns nothing (undefined implicitly), no click event handlers where ever registered on markers.

By wrapping calls to mostrar2 with a predefined id within an anonymous function and pass that function as a click event handler for each marker, mostrar2 calls now occure only when click events are triggered on markers and with the appropriate id.

L.marker([51.5, -0.39]).addTo(mymap)
   .on('click', function () {
       mostrar2('15');
   }
);

Upvotes: 1

Related Questions