我正在尝试传递一个php数组,该数组保存名称和坐标以存储在数据库中的基础结构。这就是我的方法。
$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
该循环的结果是(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)
但是我希望结果在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 © <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>
有人可以协助我吗?
谢谢
尝试将其转换为控制器中的数组,然后将$ infras传递给视图
PHP代码
$infras= [];
foreach ($infrastructures as $infrastructure) {
$infras[] = [
$infrastructure->inf_name,
infrastructure->inf_lat.",".$infrastructure->inf_long
];
}
在视图中,您可以将其直接呈现到js中,也可以根据您的laravel版本尝试@json(),尽管我在使用更复杂的json结构时遇到了问题,通常可以使用json_encode。
js代码
var infras= <?= json_encode($infras); ?>;
根据评论更新
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,
]);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句