1

I am trying to load a leaflet map from a link. If I click the first link, the map loads, then if I click the second link, the map does not load. Both links call the same function. I cannot understand what is happening. Thanks in advance!

<!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>

1 Answers1

2

You are getting an error because your are trying to initialize the map container for a second. Here is how you can solve this:

<!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>
Shai Aharoni
  • 1,955
  • 13
  • 25