如何修复Uncaught ReferenceError: L is not defined?Leaflet地图开发求助
Let's break down exactly what's going on and how to fix it:
Core Cause
That error pops up because your code is trying to use Leaflet's global L object, but you haven't loaded the Leaflet library itself into your page yet. Every Leaflet API call (like L.map() or L.tileLayer()) relies on this L object being available in the browser's global scope.
Step-by-Step Fixes
1. Load Leaflet's CSS and JS Before Your Custom Code
First, you need to include Leaflet's required files in your HTML. You can use a CDN for easy access—add these lines in your <head> section, and make sure they come before your custom JavaScript code:
<!-- Leaflet Stylesheet --> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/> <!-- Leaflet JavaScript Library --> <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
Since you're also using jQuery (for $("#addmarker") and other selectors), make sure jQuery is loaded before your custom JS too.
2. Fix Your Code Execution Order
Looking at your code, you've got another small issue: you're trying to add a tile layer to map before you even define the map variable. That will throw an error once Leaflet is loaded. Reorder those lines like this:
// First, create the map instance var map = L.map("map").setView([60.201424, 24.934037], 12); // Then add the tile layer to the map L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
3. Ensure DOM is Ready Before Running Code
To avoid issues where your code tries to access the #map div before it exists in the DOM, wrap your entire Leaflet code in a DOM ready handler. If you're using jQuery, you can do:
$(document).ready(function() { // All your Leaflet code goes here var map = L.map("map").setView([60.201424, 24.934037], 12); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); // ... rest of your marker logic });
Or use vanilla JS if you prefer:
document.addEventListener('DOMContentLoaded', function() { // Your Leaflet code here });
Final Check
Double-check the load order of your resources to make sure everything loads in the right sequence:
- Leaflet CSS
- Leaflet JS
- jQuery (if using)
- Your custom JavaScript code
Once you make these changes, the L is not defined error should disappear, and your map should initialize properly.
内容的提问来源于stack exchange,提问作者Zami Coskula

