JakeJ JakeJ - 5 months ago 9
Javascript Question

Leaflet - I cannot seem to get the basic examples working

I have been trying to get Leaflet (a webmapping API) working for hours. At first I made the mistake of trying to do too much, now I am just trying to get the basic examples working.

Here's the code that I have (HTML and Javascript):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="./leaflet.js"></script>
<link rel="stylesheet" type="text/css" href="./leaflet.css" />
<script type="text/javascript">
function initmap(){
var map1 = L.map('map');
//map1.setView([38.642433, -90.255372]),9); //Thanks!
map1.setView([38.642433, -90.255372],9);

// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '&amp;copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map1);
}
</script>




#map {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
top: 0;
z-index: 0;
}
</style>
<!-- Without this styling to set the map dimension, the tiles will get downloaded, but nothing will display on the map div! Thank you choz for answering this question! -->
</head>

<body onload="initmap()">
<div id='map'></div>
</body>
</html>


Summary: I was at first getting "missing ; before statement" and "Reference Error: initmap not defined". That was fixed by removing the extra parenthesis in the map definition, per choz's first comment.
Then I had a problem with the maps not showing up, even though the tiles were being downloaded. Choz commented again about the needed style for the map. I included the working code above.

Answer

You probably forgot to set the dimension of your #map. Here's a very basic sample how you get it working.

// create a map in the "map" div, set the view to a given place and zoom
var map = L.map("map").setView([39.50, -98.35], 5);

// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
#map {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  top: 0;
  z-index: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<div id='map'></div>

Comments