如何在 Laravel 8 中显示多个 Gmaps 标记?

How to Display Multiple Gmaps Markers in Laravel 8?

我想在仪表板上显示多个 gmaps 标记。这个标记数据,取自数据库。我已经这样写了,但是还是不行。

控制器

public function index()
{
    $markers = Report::select('location','latitude','longitude')->get()->toArray();
    
    // dd($markers);
    return view('dashboard', compact('markers'));
}

在blade中,我是这样制作的。这是我从 google documentation

得到的参考

Blade

@section('styles')
<style>
    /* Set the size of the div element that contains the map */
    #map {
    height: 400px;
    /* The height is 400 pixels */
    width: 100%;
    /* The width is the width of the web page */
    }
</style>
<script>

function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 10,
        center: { lat: -6.261493, lng: 106.810600 },
});

setMarkers(map);
}

const locations = <?php print_r(json_encode($markers)) ?>;

function setMarkers(map) {

const image = {
    url: "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png",
    // This marker is 20 pixels wide by 32 pixels high.
    size: new google.maps.Size(20, 32),
    // The origin for this image is (0, 0).
    origin: new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at (0, 32).
    anchor: new google.maps.Point(0, 32),
};

const shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: "poly",
};

for (let i = 0; i < locations.length; i++) {
    const location = locations[i];

    new google.maps.Marker({
    position: { lat: parseFloat(location[1]), lng: parseFloat(location[2]) },
    map,
    icon: image,
    shape: shape,
    title: location[0],
    zIndex: location[3],
    });

    console.log(locations[i]);
    }
}

</script>

@endsection

...
...
<div class="col-12">
    <div class="card">
         <div class="card-body">
               <div id="map"></div>
         </div>
    </div>
</div>
...
...

如果我查看控制台,输出显示如下。

Console.log

如何解决?谢谢

已解决。这种情况可以通过在控制器中使用集合映射来解决

    public function index()
    {
        $markers = Report::select('location','latitude','longitude')->get();

        $markers = $markers->map(function ($item, $key){
            return [$item->location, $item->latitude, $item->longitude];
        });

        return view('dashboard', compact('markers'));
    }