-2

I created a map using html and javascript code but it is not showing up. Is my code ok? Am I calling the Esri basemap the right way?

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Map</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Load Leaflet from CDN-->
    <link rel="stylesheet" href="//cdn.jsdelivr.net/leaflet/0.7.3/leaflet.css" />
    <script src="//cdn.jsdelivr.net/leaflet/0.7.3/leaflet.js"></script>

    <!-- Load Esri Leaflet from CDN -->
    <script src="//cdn.jsdelivr.net/leaflet.esri/1.0.0/esri-leaflet.js"></script>


</head>

<body>
    <div id="map" style="width:400px;height:400px;"></div>
    <script src="basemap.js" defer></script>
</body>
</html>

basemap.js

(function() {
var map = L.map('map').setView([54.296500, -2.209221], 5);
L.esri.basemapLayer('Oceans').addTo(map);

var popup = L.popup();

})();
Toronto23
  • 327
  • 8
  • 20

2 Answers2

0

You are not creating the necessary div with "map" id.

Add it as:

<body>
    <div id="map" style="width:400px;height:400px;"></div>
</body>

Here is an example fiddle

André Teixeira
  • 2,392
  • 4
  • 28
  • 41
  • I added the div inside the body but it still does not show up. I clicked on your fiddle link but nothing comes up. – Toronto23 Dec 29 '15 at 19:30
  • I saw the fiddle and it works. But for some reason when I add the div id in the html document, the map still is not showing up. – Toronto23 Dec 29 '15 at 19:45
0

You call your anonymous function which contains L.map('map') within basemap.js script in your HTML head, when the body and its DOM are not ready yet (they do not "exist" yet in memory).

Please refer to pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it.

The most simple workaround is to put your basemap.js script tag after your div with id="map". A common practice is (was) to put all script tags just before the end of the HTML body.

The current recommended practice is to keep your script tags in your HTML head, but use async (or defer) attribute, and attach instructions that need the DOM to be ready to the DOMContentLoaded event. See also Where is the best place to put <script> tags in HTML markup?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
ghybs
  • 47,565
  • 6
  • 74
  • 99
  • I edited the code. I put the basemap.js script after the div. But the map still does not show up. What about the script tags that loads the leaflet? Does it need to be after the div as well? (Though I did try that and the map does not show up) – Toronto23 Dec 29 '15 at 21:49