0

I'm following this post which wonderfully shows how to loop through map markers using blade templating within Javascript.

I'd like to add on the ability to loop through the content as well. In other words, I'd like to loop through one value, in this case, Props, with multiple parts, in this case, coords and contents.

The code below is my latest attempt. I can't get it to work. Any idea where I may be going wrong?

Thanks!

 <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 38.7222524, lng: -9.139336599999979},
          zoom: 12
        });

        var props = [
          @foreach ($rooms as $room)
              coords = [  "{{ $room->lat }}", "{{ $room->lng }}" ],
              contents = [ "{{ $room->title }}" ],
          @endforeach
          ];
          for (i = 0; i < props.length; i++) {
              var prop = new google.maps.LatLng(props[i][0], props[i][1]);

              var marker = new google.maps.Marker({
                  position: props.coords,
                  map: map,
              });

              var infoWindow = new google.maps.InfoWindow({
                content: props.content,
              });
          }


        marker.addListener('click', function(){
          infoWindow.open(map, marker);
        });


      var transitLayer = new google.maps.TransitLayer();
        transitLayer.setMap(map);
      };
    </script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_GOOGLE_MAPS_KEY&callback=initMap"
    async defer></script>
Brad Ahrens
  • 4,864
  • 5
  • 36
  • 47

1 Answers1

2

this is much more javascript than it is Laravel, but with that being said, your javascript syntax is incorrect.

When your snippet eventually evaluates it becomes:

var props = [
  coords = [ ..., ...],
  contents = [ ... ],
  coords = [ ..., ...],
  contents = [ ... ],
  ... // continues @foreach ($room)
];

which is incorrect Javascript syntax. Please check the source after loading the page and see what it actually is, and what you can do to fix the syntax. What you really want is to end up with an array of objects like so:

var props = [ { lat: '...', long: '...', title: '...' }, { lat: '...', long: '...', title: '...'}, ... ];

To get this, you would do:

var props = [
  @foreach ($rooms as $room)
  { lat: "{{ $room->lat }}", lng: "{{ $room->lng }}", title: "{{ $room->title }}" },
  @endforeach
];

You would then need to iterate through the array like so...

for (i = 0; i < props; i++) {
var prop = new google.maps.LatLng(props[i].lat, props[i].lng);
var title = props[i].title;
...
heisian
  • 6,127
  • 1
  • 17
  • 17