简体   繁体   中英

How to send PHP data to Javascript file in Laravel (Google maps API)

Im having trouble with my pagespeed in Laravel, because of the javascript in my page view.

Im trying to make my pagespeed better by not having any javascript on the page view, and instead in a seperate search.js file.

Im generating a map with google maps, and putting about 100 markers on the map. The data depending on where the markers should be placed are stored in a MySQL database (as part of the users information).

Right now im having a script on the page within a foreach loop on the page for each user passed to the view. This makes the page source code extreamly long, as it goes trough the loop 100 times and displayed all this javascript in the source code.

Below is only an example of my code to get the jist of what I mean, whole code is displayed here .

<script>
@foreach($usersall as $user)
...

var latlng{{ $user->id }} = {lat: {{ $user->lat }} , lng: {{ $user->long }} };

var marker{{ $user->id }} = new google.maps.Marker({
  map: map,
  clickable : true,
  icon: '/assets/img/pin_marker_open.png',
  position: latlng{{ $user->id }}
});

markers.push(marker{{ $user->id }});

...
@endforeach
</script>

I cant do that in my search.js file, because I dont have the data from $usersall .

So here goes my question: How do I pass the PHP variables for a user to the search.js file, so I can display all the markers on the map without having any of the javascript in the page view itself?

This isn't the best way to do this, but it's the most direct:

<script>
    var users = {{ $usersall }};
</script>

The default output of a collection (when echoed) will be cast to a JSON string. Therefore you can directly assign this to a variable in JS.

However, ideally you should retrieve this value via AJAX and pass it into the function separately.

If what you want is to get the values of the variables of the php inside your search.js as far as i know you can't.

I recommend to use ajax for this purpose, if that is not an option you could make a loop of your users in your html to hiddien fields like

@foreach($usersall as $user)
    <input type="hidden" class="user" value="{{$user}}">
    //if fails try encoding json_encode($user) or json_decode($user) i don't rememer
@endforeach

And then loop in your js file you can get all the elements with the user class and loop them to get the value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM