Laravel项目中JS脚本无法在监听器外访问JSON文件求助
Hey Alex, let's work through this JSON access issue you're hitting with your Google Maps markers in Laravel!
First, let's break down why you're seeing this problem: it almost certainly comes down to asynchronous loading scope or timing. When you load your JSON file (probably via fetch or axios), that operation runs in the background. Your code trying to create otherPlace runs immediately—before the JSON has finished loading—so the values don't exist yet. But your placeMarker click listener fires later, after the JSON has loaded, which is why it works there.
Here are two solid solutions to fix this:
Solution 1: Wrap everything in async/await to ensure JSON loads first
If you're loading JSON via an async request, wrap your entire map initialization code in an async function so you wait for the data before using it. Example:
async function initMap() { // Step 1: Wait for the JSON to fully load const response = await fetch('/path/to/your/markers.json'); const markerData = await response.json(); // Step 2: Initialize your map once data is ready const map = new google.maps.Map(document.getElementById('map'), { center: { lat: 37.7749, lng: -122.4194 }, // Replace with your default center zoom: 12 }); // Now you can safely use markerData to create otherPlace const otherPlace = new google.maps.Marker({ position: markerData.otherPlace, // This will exist now! map: map, title: 'Pre-defined Location' }); // Your click listener still works as expected map.addListener('click', function(e) { placeMarker(e.latLng, markerData.someValueFromJson); }); } // Kick off the map initialization initMap();
Solution 2: Inject JSON directly from Laravel (no async needed)
Since you're working in Laravel, you can skip the async request entirely by passing the JSON data directly from your backend to your Blade template. This is super clean and avoids timing issues:
In your Blade view file:
<script> // Use Laravel's @json directive to pass server-side data to JS const markerData = @json($markers); // $markers is the data from your controller function initMap() { const map = new google.maps.Map(document.getElementById('map'), { center: { lat: 37.7749, lng: -122.4194 }, zoom: 12 }); // Create otherPlace with the injected data const otherPlace = new google.maps.Marker({ position: markerData.otherPlace, map: map }); map.addListener('click', function(e) { placeMarker(e.latLng, markerData.someValue); }); } </script>
Quick Checks to Avoid Headaches
- Double-check your JSON file path: If you're using
fetch, make sure the path points correctly to your file in thepublicdirectory (e.g.,/markers.jsonif it's inpublic/markers.json). - Verify your JSON structure: Ensure the
otherPlacekey exists and is formatted correctly as a{ lat: X, lng: Y }object that Google Maps accepts.
Content的提问来源于stack exchange,提问作者Alex

