如何实现Leaflet示例代码显示简易地图与标记点?页面空白排查
问题排查与解决
你的页面空白核心原因是地图容器没有设置尺寸样式,Leaflet需要明确的宽高才能渲染出地图内容。
解决步骤
在<head>标签内添加样式,给#map容器设置宽高:
<style> #map { width: 100vw; /* 占满视口宽度 */ height: 100vh; /* 占满视口高度 */ margin: 0; padding: 0; } </style>
你也可以根据需求设置固定尺寸(比如width: 800px; height: 600px;),只要保证容器有明确的大小即可。
修改后的完整代码
<html> <head> <title>Map view with Leaflet</title> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" /> <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script> <style> #map { width: 100vw; height: 100vh; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> var map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map); L.marker([51.505, -0.09]).addTo(map); </script> </body> </html>
额外检查项
- 确认网络可正常访问Leaflet的CDN资源(css和js文件)
- 打开浏览器开发者工具(F12)查看控制台,排除其他加载报错
内容的提问来源于stack exchange,提问作者user7665853
相关产品推荐
相关产品推荐

