Home > Mobile >  How to do foreach in JS using data from laravel views?
How to do foreach in JS using data from laravel views?

Time:09-26

var map = L.map('map').setView([-6.935118, 107.766995], 15);

 L.marker([-6.93155, 107.775831]).addTo(map)
  .bindPopup('Bus Stops')
  .openPopup();
        

I have this function on javascript, and I have a database that store the lat, lng, and the place name. Is there any possible way that I can do a loop so the marker is added automatically from what I have in my database? I'm using laravel blade. PS: its a leafletjs

CodePudding user response:

First, modify your JS function to something similar to this:

function addMarker(lat, lng, place){
         L.marker([lat, lng]).addTo(map)
         .bindPopup(place)
         .openPopup();
        }

For old versions of laravel:

<script>
    var coordinates = <?php echo json_encode($coordinates); ?>;
</script>

For latest versions of laravel:

<script>
    var coordinates = {{ Js::from($coordinates) }};
</script>

Then Loop through the array :

<script>
    coordinates.foreEach(function(item){
        addMarker(item.lat, item.lng, item.place);
    });
</script>

CodePudding user response:

Hmm, I'm not sure about that but you could try doing something like that

// We will loop for every element/index inside the L if it's an array it should
// work,             
  • Related