skip to Main Content
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

3

Answers


  1. 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,  👇 here we declare l variable so we can use inside the foreach loop
    L.forEach((l) => {
      // Example
      console.log(l);
    });
    

    As well i can’t test it because i don’t have the code, It would be great if you added the variable L to the code so i can help you more with it.

    If the L is convertible to Array or it’s already an array it should work.
    For more information about forEach loops check here!

    If L is not an array you might need to add L.toArray().forEach,
    You can follow this link to see prototypes for toArray() method.

    Login or Signup to reply.
  2. you must get the all data and make it into Api
    i make my Javascript like this

    async function getAllMarker() {
        map.setZoom(8);
        const res = await fetch("/api");
        const data = await res.json();
        data.forEach((item) => {
            const position = {
                lat: Number(item.latitude),
                lng: Number(item.longitude),
            };
            addMarker(position, map, item);
        });
    }
    

    for Add Marker my Function Look Like This

    function addMarker(position, map, item){
             L.marker(position).addTo(map)
             .bindPopup(item.marker)
             .openPopup();
            }
    
    Login or Signup to reply.
  3. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search