[GIS] Geojson not displayed within leaflet

geojsonleaflet

I made some more complex leaflets before, but here I'm stucked. You can find my geojson file here:
https://gist.github.com/Supermarmotte/16e0466c9d17f4ab341b6fdb805bb849
It is displayed correctly and is stored beneath the html file.

Grrr

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

<script>
    var map = L.map('map').setView([47.439278,9.529174], 10);
    mapLink = 
        '<a href="http://openstreetmap.org">OpenStreetMap</a>';
    L.tileLayer(
        'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; ' + mapLink + ' Contributors',
        maxZoom: 18,
        }).addTo(map);
    L.marker([47.439278,9.529174]).addTo(map).bindPopup("Willkommen in Heiden!").openPopup();

    var map = L.map('map2').setView([9.529174,47.439278], 10);
    L.geoJSON(post4).addTo(map);
</script>

Best Answer

The problem as I see is due to the way in which you are adding it to the map.

You have the following line: L.geoJSON(post4).addTo(map); But where is the variable with the name post defined? If you look at your browser's developer console, I bet, that where you'll get an error.

How do you solve this?

There are 3 ways in which geojson data is added to a Leaflet map

  1. Directly in the JS code: In cases where the data is small, you can define a new variable in the same place where you initializing the map etc, and set it to your data. In that case you can use a line like: L.geoJSON(post4).addTo(map); to add it to the map.

  2. In a separate file: In cases where the data is large, having it along with other code (in the same file) can get unwieldy, and reduce readability. What is done in this case, is that you create a separate file with the extension .js and add the variable there, and set it to your geoJSON data. You then add a link to it, in your html page as a <script> tag. After this you can add it to the map by using a line like L.geoJSON(post4).addTo(map);

  3. AJAX load: In cases where you don't want to save your data along with a variable as a JS file, and want to keep it as a JSON object, you can't follow the previous method. You'll have to make a AJAX request, and then load the results. Plugins are also available for this. See this post for some solutions

.