我有MapController和PagesController。从数据库中获取地址行到MapController并将其传递到home.view,以便在Google Map中使用它。而且在PagesController中,我也正在提取所有行,包括地址行。并将其传递给相同的视图但是当我这样做的时候。弹出未定义的var错误。
这里是控制器和视图。
PagesController
public function search(Request $request)
{
$q = $request->q;
$estates = \DB::table('allestates')
->where("building_name", "LIKE", "%" . $q . "%")
->orWhere("address", "LIKE", "%" . $q . "%")
->orWhere("company_name", "LIKE", "%" . $q . "%")
->orWhere("region", "LIKE", "%" . $q . "%")
->orderBy('price')->paginate(5);
return view("home", compact('estates', 'q'));
}
和视图
@foreach($estates as $estate)
<div class="row" id="main-wrapper">
<div class="col-sm">
<img src=" https://dummyimage.com/150x150/000/fff" alt="" class="img-radius">
</div>
<div class="col-6">
<h3>{{$estate->building_name}}</h3>
<p>
<br>
{{str_limit($estate->address, $limit = 80)}}
<br>
{{ $estate->price }}
<br>
{{ $estate->rooms }}
<br>
{{ $estate->extend }}
<br>
</p>
</div>
<div class="col-sm">
<button class="detail-btn">物件概要</button>
</div>
<hr style="width: 100%; margin:10px; border-color: #34495e;">
</div>
@endforeach
MapController
$adres = DB::table("allestates")
->get();
return view("home", compact('adres'));
视图
function initMap(){
var options = {
zoom:8,
center:
'{!! $adres[0]->address !!}'
}
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position:
@foreach($adres as $addr)
'{!! $addr->address !!}',
@endforeach
map:map
});
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
})
}
在我将PagesController放入之前,没有任何错误。如何使这种情况发生? 并向我显示MapController时出错?
未定义变量:adres(查看: /var/www/html/laravel/resources/views/layouts/app.blade.php)(查看: /var/www/html/laravel/resources/views/layouts/app.blade.php)
答案 0 :(得分:1)
感谢您的回答,但我几乎没有解决问题。只是在两个控制器中赋予了相同的$ var。
答案 1 :(得分:0)
而不是js中的@foreach将其提倡到您的代码中:
var data = {!! $addres !!};
debugger; < --- use this to inspect that the array exists
然后进行for迭代,并以此方式为每个项目放置一个标记(更改数据库中您具有不同的变量):
for (var i = 0; i < data.length; i++) {
var pos = new google.maps.LatLng(data[i].latitud, data[i].longitud);
markers[i] = new google.maps.Marker({
position: pos,
map: map,
icon: 'images/locred.png',
description: data[i].desc,
id: i
});
var infowindow = new google.maps.InfoWindow({
content: data[i].name
});
infowindow.open(map, markers[i]);
google.maps.event.addListener(markers[i], 'click', function () {
alert(markers[this.id].description)
})
}
答案 2 :(得分:0)
在您MapsController
中,试试这个
$adres = DB::table("allestates")->all();
return view("home", compact('adres'));