如何在Google Maps API地图中为每个标记在模态框展示对应图片(Laravel环境)
实现方案
你可以按照以下步骤完成功能,同时提供两种实现方式供你选择:
方案1:AJAX请求实现(符合你最初的思路)
步骤1:新增路由
在routes/web.php文件中新增获取图片地址的路由:
use App\Http\Controllers\ProblemController; Route::get('/get-problem-image/{id}', [ProblemController::class, 'getProblemImage'])->name('get.problem.image');
步骤2:控制器新增对应方法
在你的控制器中新增处理图片请求的方法:
public function getProblemImage($id) { $problem = Problem::with('problemImages')->findOrFail($id); return response()->json([ 'image_url' => asset('storage/' . $problem->problemImages[0]['name_of_the_file']) ]); }
步骤3:添加模态框HTML结构
在welcomePage.blade.php的body末尾加入模态框代码:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">问题对应图片</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <img id="problem-image" src="" alt="问题图片" class="img-fluid"> </div> </div> </div> </div>
步骤4:修改前端JS代码
首先修改createMarker方法里的信息窗口内容,给链接加上问题ID属性:
function createMarker(location, map, id) { let marker = new google.maps.Marker({ position: location, animation: google.maps.Animation.DROP, map: map, }); let infoWindow = new google.maps.InfoWindow({ content: `<p><b>ID: </b>${id}</p> <a href="javascript:void(0)" data-problem-id="${id}" class="show-image-btn">Show image</a>` }); marker.addListener('click', function () { infoWindow.open(map, marker); }); }
然后在JS代码末尾新增点击事件监听,处理AJAX请求:
// 注意需提前引入jQuery库 $(document).on('click', '.show-image-btn', function() { const problemId = $(this).data('problem-id'); $.get(`/get-problem-image/${problemId}`, function(res) { $('#problem-image').attr('src', res.image_url); $('#myModal').modal('show'); }); });
方案2:无AJAX轻量实现(更适合当前场景,无需额外网络请求)
你已经在渲染页面时获取了所有$problems的图片数据,可以直接把图片地址预传给标记,省去后端请求步骤:
步骤1:修改displayMarkers方法,传递图片地址
function displayMarkers() { @foreach($problems as $problem) var loc = split("{{ $problem->location }}"); // 直接拼接生成图片地址 var imageUrl = "{{ asset('storage/' . $problem->problemImages[0]['name_of_the_file']) }}"; createMarker(getLocVar(loc[0], loc[1]), map, "{{$problem->id}}", imageUrl); @endforeach }
步骤2:修改createMarker方法,直接绑定图片地址
// 新增imageUrl参数 function createMarker(location, map, id, imageUrl) { let marker = new google.maps.Marker({ position: location, animation: google.maps.Animation.DROP, map: map, }); let infoWindow = new google.maps.InfoWindow({ content: `<p><b>ID: </b>${id}</p> <a href="javascript:void(0)" class="show-image-btn">Show image</a>` }); marker.addListener('click', function () { infoWindow.open(map, marker); }); // 信息窗口渲染完成后绑定点击事件 infoWindow.addListener('domready', function() { document.querySelector('.show-image-btn').addEventListener('click', function() { document.getElementById('problem-image').src = imageUrl; $('#myModal').modal('show'); }); }); }
模态框HTML部分和方案1一致即可。
内容的提问来源于stack exchange,提问作者Michal Sorát
相关产品推荐
相关产品推荐

