I am trying to implement some location-based services features on my MVC 4 web page. I am completely new to using Javascript and MVC so please bear with me.
This is my current web page:
@{
ViewBag.Title = "OnlineUsers";
}
<html>
<head>
<title>Online Users</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.4/leaflet.js"></script>
</head>
<body>
<button onclick="showMap()">Show Map</button>
<button onclick="goToLocation()">My Location</button>
<div id="locationDetails"></div>
<div id="map" style="height: 500px; width: 800px"></div>
<script type="text/javascript">
**var map = L.map('map');**
function showMap() {
var map = L.map('map');
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>'
}).addTo(map);
map.locate({ setView: true, maxZoom: 16 });
}
</script>
</body>
</html>
At the top of the script section is the following piece of code: var map = L.map('map');. If I include this code within a function, the page loads and calling the function creates the map. However, if I place this code (or any other JS code) outside of a function, the page simply does not load.
I used Chrome’s debugger and the console showed the following error:
Uncaught ReferenceError: L is not defined
I don’t see ‘L’ being defined anywhere, but then why does this work when called from within the function?
It works within your function because L is a part of leaflet, which is not loaded by the time your function is called but not on page load. L is minified representation of something else.
It would be usual to wait until document is ready, so you can be sure that your referenced js has loaded, e.g. if you have jQuery then the following
UPDATE: it may be slow to load this js, so you could put a check in that it is there first, e.g.