javascript - 从链接加载传单 map

标签 javascript leaflet

我正在尝试从链接加载传单 map 。如果我点击第一个链接, map 加载,然后如果我点击第二个链接, map 不加载。两个链接都调用相同的函数。我无法理解发生了什么。 提前致谢!

<!DOCTYPE html>
<html>
<head>
    <title>Simple Leaflet Map</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css" />
</head>
<body>
    <a href="#" onclick="showMap('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')">OpenStreetMap</a><br>
    <a href="#" onclick="showMap('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png')">Thunderforest</a><hr>
    <div id="map" style="width: 600px; height: 400px"></div>

    <script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"> </script>
    <script>
        function showMap(url){
            var map = L.map('map').setView([-33.4387,-70.647], 14);
            var mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>';           

            L.tileLayer(url, {
            attribution: 'Map data &copy; ' + mapLink,
            maxZoom: 18,
            }).addTo(map);
        }
    </script>
</body>
</html>

最佳答案

您收到错误消息是因为您正在尝试初始化 map 容器一秒钟。以下是解决此问题的方法:

<!DOCTYPE html>
<html>
<head>
    <title>Simple Leaflet Map</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css" />
</head>
<body>
    <a href="#" onclick="showMap('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')">OpenStreetMap</a><br>
    <a href="#" onclick="showMap('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png')">Thunderforest</a><hr>
    <div id="map" style="width: 600px; height: 400px"></div>

    <script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"> </script>
    <script>

       var map;

        function showMap(url){
            if(!map)
            {  
               map = L.map('map').setView([-33.4387,-70.647], 14);
            }

            var mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>';           

            L.tileLayer(url, {
            attribution: 'Map data &copy; ' + mapLink,
            maxZoom: 18,
            }).addTo(map);
        }
    </script>
</body>
</html>

关于javascript - 从链接加载传单 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31184943/

相关文章:

javascript - jQuery 第 67 行说 "TypeError: ' undefined' 不是一个函数。”

leaflet - Mapbox 鼠标右键单击

javascript - 取消选择 jquery 选择器

delphi - 如何在 Delphi VCL 应用程序中显示开放街道 map 并与之交互

javascript - 将父子数组转换为树

javascript - Socket.io + node.js - 客户端未接收广播发射

javascript - 解析连接的 JavaScript 字符串

javascript - 创建一个带有区域设置的日期

javascript - Leaflet Draw Plugin::如何找到折线的纬度并将其保存到数据库

leaflet - 如何在传单中获取wms图层的边界框