1

I'm a beginner in Leaflet and I need help to deal with GeoJSON files.

I succeeded in creating a Leaflet basemap. I can add markers without troubles but I cannot manage to show a GeoJSON layer.

Here is the code I picked up from Leaflet Tutorials website https://leafletjs.com/examples/geojson/ :

var geojsonFeature = {
    "type": "Feature",
    "properties": {
        "name": "Coors Field",
        "amenity": "Baseball Stadium",
        "popupContent": "This is where the Rockies play!"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.99404, 39.75621]
    }
};
L.geoJSON(geojsonFeature).addTo(map);

Unfortunatly, the GeoJSON does not appear in my map.

Can you tell me where I missed something ?


Alright, you're fine Francisco, this part was OK. I changed the whole script and it works !

However, would you know how to load a GeoJSON from an external source ?

I tried this :

var geojsonLayer = new L.GeoJSON.AJAX("foo.geojson");       
geojsonLayer.addTo(map);

from Loading external GeoJSON file into Leaflet map?

but this definitely does not work.

Any ideas ?


I am not skilled enough to understand your advice.

Here is the whole code I am using to create my map :

<!DOCTYPE html>
<html>
<head>
<title>data</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script type="text/javascript" src="http://maps.stamen.com/js/tile.stamen.js?v1.3.0"></script>
<script src="/js/leaflet-0.7.2/leaflet.ajax.min.js"></script>
<script src="htdocs/webmap101/leaflet.ajax.min.js" type="text/javascript" ></script>
<style>
   #map {width: 960px; height:700px;}
</style>
</head>
<body>
  <div id="map"></div>
<script>
  // create map
var lat = 44.933331; var lon = 4.9; 
var map = L.map('map',{center: [lat,lon],zoom: 6});
  // basemaps
var base = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', 
 {attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
 });
var toner = new L.StamenTileLayer("toner");
var watercolor = new L.StamenTileLayer("watercolor");
var landscape = L.tileLayer('https://tile.thunderforest.com/landscape/{z}/{x}/{y}.png');
base.addTo(map);
  // markers 
var mark1=L.marker([lat,lon])
mark1.addTo(map)

  // layers panel
 L.control.layers({"base": base, "water": watercolor, "toner": toner , "landscape" : landscape}).addTo(map);

  // geojson files
var geojsonFeature = {
    "type": "Feature",
    "properties": {
        "name": "Coors Field",
        "amenity": "Baseball Stadium",
        "popupContent": "This is where the Rockies play!"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.99404, 39.75621]
    }
};
L.geoJSON(geojsonFeature).addTo(map);

  //ajax 
var geojsonLayer = new L.GeoJSON.AJAX("foo.geojson");       
geojsonLayer.addTo(map);

</script>
</body>
</html>

I know it's a bit messy but this is actually my very first HTML script... I guess I did not include in a proper way the AJAX library.


Actually, I just want a solution to replace the lines where I create the GeoJSON by something that tells javascript to load the GeoJSON stored locally in my folder. This :

var geojsonFeature = {
    "type": "Feature",
    "properties": {
        "name": "Coors Field",
        "amenity": "Baseball Stadium",
        "popupContent": "This is where the Rockies play!"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.99404, 39.75621]
    }
};

should be transformed into something like (I don't know if it exists) :

var geojsonFeature = [foo.geosjon]

where "foo.geosjson" is a file like :

{ "type": "FeatureCollection", "name": "abies", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "features": [ { "type": "Feature"

3
  • It seems good. Maybe the problem is in another part of the code or the html. Can you post the full code. Or there is any error in the console? Dec 16, 2019 at 15:16
  • Are you running your map from server or from local file? Where is your foo.geojson file located?
    – TomazicM
    Dec 17, 2019 at 11:45
  • Script is running on the localhost. My foo.geojson is in the same folder as the html.
    – RG70
    Dec 17, 2019 at 17:46

2 Answers 2

4

L.GeoJSON.AJAX call belongs to leaflet-ajax plugin, so you should have required includes. If that part is OK and foo.geojson exists in your default directory and .geojson MIME is supported on your server, then what is missing is wait till GeoJSON data is fetched by ajax call:

var geojsonLayer = new L.GeoJSON.AJAX("foo.geojson");
geojsonLayer.on('data:loaded', function(){
  geojsonLayer.addTo(map);
});
2

When asking for help is a good idea open the Developer Tools of your browser (Mozilla, Chrome) and paste the output of the console, or clarify that there is no output.

Commonly is also a good idea trying to explain how you are running the code.

My bet is that you are using Open file in the browser and not loading the file from a (local) server. The leaflet-ajax plugin that seems that you are using expects that the file lives in a server and can not load it from the file system.

An easy way to run a local http server, that takes as root the folder where you launch is use reload if you like npm/node or python default server

For npm/node:

npx reload
# open in the browser http://localhost:8080/NAME_OF_YOUR_HTML_FILE_WITH_EXTENSION

For Python 3

python3 -m http.server
# open in the browser http://localhost:8000/NAME_OF_YOUR_HTML_FILE_WITH_EXTENSION

Also, to load the data in this way, it must be a valid (Geo)Json file. The data you post in your example, is defined in JavaScript, i mean, you have a variable declaration var geojsonFeature = and you are assigning some a literal javascript objet to it. Is just, that this "literal javascript object" is also valid geojson data. So, you foo.geojson file should only contain the data and not the variable declaration

File foo.geojson

{
    "type": "Feature",
    "properties": {
            "name": "Coors Field",
            "amenity": "Baseball Stadium",
            "popupContent": "This is where the Rockies play!"
    },
    "geometry": {
         "type": "Point",
         "coordinates": [-104.99404, 39.75621]
    }
}

If you want to try it in another way there is a common trick. Instead of load the data by means of an HTTP request, arrange the data to look like a JavaScript variable and load the file in a script tag. So the variable will be available in the global namespace.

As example:

File index.html

<!DOCTYPE html>
<html>
<head>

    <title>GeoJSON tutorial - Leaflet</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>

    <style>
        html, body {
        height: 100%;
            margin: 0;
        }
        #map {
            width: 600px;
            height: 400px;
       }
    </style>

</head>
<body>

    <div id='map'></div>

    <script src="sample-geojson.js" type="text/javascript"></script>

    <script>
         var map = L.map('map').setView([39.74739, -105], 13);

         L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
         maxZoom: 18,
             attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
                      '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                          'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
             id: 'mapbox/light-v9'
         }).addTo(map);

         L.geoJSON(geojsonFeature).addTo(map);

    </script>

</body>
</html>

File sample-geojson.js:

var geojsonFeature = {
    "type": "Feature",
    "properties": {
        "name": "Coors Field",
        "amenity": "Baseball Stadium",
        "popupContent": "This is where the Rockies play!"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.99404, 39.75621]
    }
};

And just as final note, you don't need to use a plugin to load geojson data from the server. Is easy enough to use the fetch api or any other tool like jQuery.getJSON, or axios.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.