我正在尝试使用这个tutorial和Laravel 5创建商店定位器应用程序.这些问题Here和Here中的人似乎正在使用@foreach循环和其他刀片模板语言来运行他们的纬度/经度坐标.他们是怎么做到的?
当我的地图代码在js文件中时,我基本上不知道如何使用刀片循环坐标?怎么可能?我做错了吗?
我正在使用具有以下代码的js文件(maps.js)显示我的地图:
function initialize() {
var map_canvas = document.getElementById('map');
// Initialise the map
var map_options = {
center: location,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
// Put all locations into array
var locations = [
@foreach ($articles as $article)
[ {{ $article->lat }}, {{ $article->lng }} ]
@endforeach
];
for (i = 0; i < locations.length; i++) {
var location = new google.maps.LatLng(locations[i][0], locations[i][1]);
var marker = new google.maps.Marker({
position: location,
map: map,
});
}
// marker.setMap(map); // Probably not necessary since you set the map above
}
但显然这会卡在@foreach线上.
PS:如果有人在Laravel 5上学习本教程,我将非常感谢这部分的任何信息:用PHP输出XML. 解决方法: 无法在外部Javascript文件中使用Blade模板.
Laravel只能将数据传递给视图/模板; Javascript文件在外部加载,因此App数据不会传递给它们.
为了解决这个问题,您需要创建< script>您的Blade模板文件中的标签:
{{-- Code in your template file, e.g., view.blade.PHP --}}
<script type="text/javascript">
// Put all locations into array
var locations = [
@foreach ($articles as $article)
[ "{{ $article->lat }}", "{{ $article->lng }}" ],
@endforeach
];
// NOTE: I've added a comma which will be needed to delimit each array within the array.
// Quotes will also be needed since lat and long are not integers.
</script>
确保此代码段位于包含maps.js文件的代码之前.如果您已经在< head>中包含了maps.js文件标签,您将需要将该包含片段向下移动到页面底部.
然而,这是一个相当基本的解决方案.更好的方法是使用AJAX在初始化时从maps.js文件中检索数据.
当然,这需要您创建一个新的Controller方法和相应的路由,它可以处理请求并返回所需的数据. (编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|