Incorporating PHP arrays into JavaScript for creating a dynamic Leaflet map

I have a PHP array containing names and coordinates for infrastructure stored in a database. Here is how I am trying to pass it:

    $data = array();
    @endphp

    @foreach ($infrastructures as $infrastructure)
        @if ($loop->iteration)
            @php
                $name = $infrastructure->inf_name;
                $coord = $infrastructure->inf_lat.",".$infrastructure->inf_long;
                $data = $name.",". $coord;
            @endphp
        @endif
    @endforeach

The result of the loop is (Red Beach Seawall,1.3582,172.9266 Buota Bridge,1.3901,173.1343 Nippon Causeway,1.3399,172.9579 Maaman Kaburara,0.403,173.9217 TUC Main Road,0.2264,182)

However, I want the output to be formatted like this in JavaScript.

<script>
                var infras= <?= json_encode($infras); ?>;
                var mymap = L.map('mapid').setView([1.3582,172.9266], 13);
                L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
                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>',
                maxZoom: 10,
                id: 'mapbox/streets-v11',
                tileSize: 512,
                zoomOffset: -1,
                accessToken: enter your accesstoken here
                }).addTo(mymap);

                for (var i = 0; i < infras.length; i++){
                var marker = L.marker([infras[i][1],infras[i][2]]).addTo(mymap).bindPopup(infras[i][0]);
                }
 </script>

Could someone please help me with this?

Thank you

Answer №1

To optimize the process, consider converting it into an array in the controller first and then passing $infras to the view.

php snippet

$infras= [];

foreach ($infrastructures as $infrastructure) {
  $infras[] = [
     $infrastructure->inf_name,
     infrastructure->inf_lat.",".$infrastructure->inf_long
  ];
}

You can directly render it into the js within the view or experiment with @json() based on your Laravel version. In complex json structures, using json_encode is recommended due to potential issues.

js script

 var infras= <?= json_encode($infras); ?>;

Update as per comment received

public function index(Request $request) {    
     $infrastructures = $this->infrastructureRepository->all();   

     $infras= [];
    
     foreach ($infrastructures as $infrastructure) {
       $infras[] = [
          $infrastructure->inf_name,
          infrastructure->inf_lat.",".$infrastructure->inf_long
       ];
     }
     
     return view('dashboard.index', [
        'infras' => $infras,
        'infrastructures' => $infrastructures,
       ]);  
     }
}

Answer №2

Within my controller...

public function displayMap(Request $request)
        {
            $locations = $this->locationRepository->all();
    
    
            $coords= [];
    
            foreach ($locations as $location) {
              $coords[] = [
                 $location->loc_name,
                 $location->loc_lat,$location->loc_long
              ];
            }
    
            return view('dashboard.map', [
                'coords' => $coords,
                'locations' => $locations,
               ]);
        }
    }

Inside my map.blade.php file

        <div id='mapid' style='width: 100%; height: 300px;'></div>
        <script>
            var coords= <?= json_encode($coords); ?>;
            var mymap = L.map('mapid').setView([1.3582,172.9266], 13);
            L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
            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>',
            maxZoom: 20,
            id: 'mapbox/streets-v11',
            tileSize: 512,
            zoomOffset: -1,
            accessToken: 'enter your accesstoken here'
            }).addTo(mymap);

            for (var i = 0; i < coords.length; i++){
            var marker = L.marker([coords[i][1],coords[i][2]]).addTo(mymap).bindPopup(coords[i][0]);
            }
        </script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which design pattern would be best suited for monitoring the completion of multiple ajax requests?

In my code, I have combined 3 separate ajax calls in one function along with checkAjaxCompletion method to monitor each ajax completion flag. The current approach involves sending multiple independent ajax calls and using an interval method to continuousl ...

Issue with ThreeJs: Difficulty loading separate images on top and bottom surfaces

I've been trying to place different textures on the top and bottom sides using Threejs to display unique images on each side. However, I'm encountering an issue where the same image is being displayed on both the top and bottom sides. Below is th ...

Prevent Editing of Input Box in JQuery UI Sortable

Having some trouble placing an input box within a sortable UL. The sortable functionality is working, but the text seems to be "locked" or the click event is overridden...unsure of how to proceed. Came across this link which touches on my current issue. ...

Develop a custom cell editor for ag-Grid and insert it into a designated location within

I am currently working with Angular 16 and AgGrid 30. My goal is to have the cell editor created in a different location than its default position, which is within a div element at the bottom of the body with these classes: ag-theme-material ag-popup. I w ...

Difficulty encountered while managing dropdown functionality in Protractor using TypeScript

I'm encountering some difficulties when it comes to selecting a dropdown in Protractor. Here's the structure of my DOM: https://i.stack.imgur.com/qK8sT.png This is the XPath I'm using to select the dropdown with the value "Yes": //label[ ...

Why is AngularJS redirection not retrieving the value from window.localStorage?

After utilizing local storage, I encountered an issue where upon logging in and being redirected to the myprofile page, the local storage value was not loading properly. Instead, I was getting a null value. It wasn't until I manually reloaded the page ...

What is the method for retrieving the JSON data with the fetch API?

I'm currently stuck trying to access a JSON file called map.json using fetch(). Here's my code snippet: export function importJSON(url) { return fetch(url) .then(r => r.json()) .then(data => { return data; ...

Access the environment variables generated throughout a collection run in the Newman Library

Is there a way to access environment variables created in collection requests while using Newman as a library and executing through Node.js? Currently, I have the following: Example Although this setup works partially, I encounter an issue due to my eve ...

Reverse the order in which the array is iterated

In the loop below, I am iterating over counts: for (var key in counts) { var entry = counts[key]; for (var entryKey in entry) { arrOfCounts.push(entry[entryKey]); } } I wanted to iterate over counts in reverse order, so I attempte ...

Steps to fix ESlint warning: Avoid using assignment in return Statement (no-return-assign)

In my React application, I am utilizing the package found at https://github.com/appleboy/react-recaptcha to create a Recaptcha component. Below is an image of what the component looks like, along with an eslint warning: https://i.sstatic.net/ZleMK.png Th ...

Use jQuery to dynamically capture and store the value of data-rowindex into an array

Is there a way to dynamically store the data-rowindex value into an array? <tr class="ewTableRow" data-rowindex="1" id="r1_assessment_training" data-rowtype="2"> Below is the code I've attempted. Not entirely sure if it is the correct approach ...

Shift the sideways movement of the triangle symbol

I currently have a main menu in the header with links, accompanied by a moving triangle that changes position as the user hovers from one page to another. While I want to maintain the dynamic movement, I am seeking a smoother transition effect similar to w ...

Tips for using jQuery to add several image source URLs to an array

My JavaScript code uses jQuery to collect all image sources on document load and store them in an array: var sliderImg = []; sliderImg.push($('.thumbnail').children('img').attr('src')); Then, I have a click event set up to a ...

Guide on displaying a document in react-doc-viewer from a protected API endpoint in either Next.Js or ReactJs

I am looking to display files in my Next.JS web application using a secure API. The API provides the following data: { "name": "Test1.docx", "contentUri": "https://api.mypurecloud.ie/api/v2/downloads/x ...

"Enhancing Error Handling in Express with Node.js Middleware for Parsing

I've been working on developing a middleware to manage errors, but I'm struggling to send the correct format to my frontend. Below, I'll outline my various attempts in the hopes of getting some guidance on this issue. Attempt 1 app.use(fun ...

Limit user input in TextField to positive unsigned integers using ReactJS Material-UI

I'm working on an input field that should only allow positive integers, without accepting characters like - + , or .. <TextField fullWidth type="number" placeholder={'[1-100]'} id="simple-start-adornmhent" onChange={this.handle ...

Embedding a line chart created with chart.js into an SVG container with the help of d3.js

My initial attempt was successful using a button element with the necessary classes and attributes. <button type="button" class="btn btn-default glyphicon glyphicon-arrow-left"></button> However, my next endeavor involve ...

I encountered a SyntaxError that reads "Unexpected token instanceof" while using the Chrome Javascript console

I find it quite surprising that the code below, when entered into the Chrome JavaScript console: {} instanceof Object leads to the error message displayed below: Uncaught SyntaxError: Unexpected token instanceof Could someone kindly explain why this ...

What is the best way to retrieve a value from an asynchronous function in Node.js?

var fs = require('fs'); var ytdl = require('ytdl-core'); var favicon = require('serve-favicon'); var express = require('express'); var app = express(); app.use(favicon(__dirname + '/public/favicon.png')); ...

I am looking to create an engaging photo viewing experience by utilizing a modal to display each image in my gallery when clicked

I created a stunning image gallery featuring 13 photos that I discovered on W3Schools and customized to suit my own preferences. The gallery looks great, but there's an issue - only the first image can be opened using a modal window. I tried editing s ...