javascript - 我无法让我的 map 显示在传单 JS 中

标签 javascript css leaflet

我有一个使用 leaflet.js 的 HTML 页面,由于某种原因我无法显示 map 。

我在正确的位置有来自 ma​​pbox 的 API,但没有 map 。以下是 JS 代码、标记和 CSS,看看我搞砸了什么。

HTML :

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Learn Maps</title>
    <link rel="stylesheet" type ="text/css" href="style.css" />
    <link rel="stylesheet" href="night_class/leaflet-0.7.3/leaflet.css" />
    <script src="night_class/leaflet-0.7.3/leaflet.js"></script>
    <script>
        window.onload = function() {
            //every part goes here
            var map = L.map('map').setView([45.46, -122.739], 4);
            L.tileLayer('https://a.tiles.mapbox.com/v4/rodneyabutler.db94e2a6/page.html?access_token=pk.eyJ1Ijoicm9kbmV5YWJ1dGxlciIsImEiOiJiYzd2SVVvIn0.R7uMtxUochQCrDmpiwg6QQ#4/45.51/-122.69', {
    attribution: 'Map data &copy; <a href="http://mapbox.com">Mapbox</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18
}).addTo(map);
        }

    </script>


</head>


<body>

<div id="map">MAP</div>

</body>
</html>

CSS:

body{
    margin: 0px;
}

#map {
    display: block;
    margin-left: auto;
    margin-right: auto;
    margin-top: 10px;
    height:300px;
    width:50%;
    border: solid crimson 4px;
    /*background-color:#000;*/
}

最佳答案

使用Leaflet,您需要在创建 map 之前设置保存 map 的div,否则 map 对象不知道去哪里。尝试将您的脚本标签移动到 map div 下方。

最终的脚本应该是这样的:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head lang="en">
<head>
<meta charset="UTF-8">
<title>Learn Maps</title>
<link rel="stylesheet" type ="text/css" href="style.css" />
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />

</head>


<body>

<div id="map"></div>

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

<script>

        window.onload = function() {

        var tileLayer = L.tileLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}.png", {maxZoom: 18, attribution: 'MRLC, State of Oregon, State of Oregon DOT, State of Oregon GEO, Esri, DeLorme, HERE, TomTom, USGS, NGA, EPA, NPS, U.S. Forest Service'});

        var map = new L.map('map', {
            layers: tileLayer
        }).setView([45.46, -122.739], 4);

    };

</script>

</body>
</html>

关于javascript - 我无法让我的 map 显示在传单 JS 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29910035/

相关文章:

r - 使用 R 在传单 map 上投影我的 shapefile 数据

javascript - 如何使用leaflet.label绑定(bind)多个标签?

javascript - Meteor - 在 meteor 服务器上生成二维码

javascript - 使用 Javascript 从 2 个数组中提取值并删除重复的 'titles' ...?

javascript - 打开一个特定变量 Angular JS

javascript - 如何在没有div的情况下自动将内容拆分为2行

r - 在 rShiny 应用程序中使用markerClusterOptions() 时弹出传单

javascript - 有没有办法在调用 toString 方法时评估函数内不是函数参数的变量?

html - Div 跨越浏览器的 100% 高度并缩放

html - 如何在同一个 div 中创建图标和文本,如表格格式