I have been trying for days to load a GeoJSON file using Ajax and Leaflet. I can get the map & index.html to load using an Apache server and such but the GeoJSON itself does not show up.

Here is my Head:

<!-- ajax plugin -->
<script src="htdocs/webmap101/leaflet.ajax.min.js" type="text/javascript" ></script>

<!-- jQuery library -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css"

<script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"

Heres is my Script:

var mymap = L.map('mapdiv')

          var bl =  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');

        var geojsonLayer = new L.GeoJSON.AJAX('attractions.geojson', {pointToLayer:
              function(feature, latlng) {
              var str = "<h4>"+feature.properties.name+"</h4><hr>";
              str += "<a href=' " + feature.properties.web+ " ' target = 'blank'";
              str += "<img src='img/"+feature.properties.image+" ' width='200px'";
              str += "</a>";
              return L.marker(latlng).bindPopup(str);

Chrome developer tools gives me this error:

GET http://localhost/webmap101/htdocs/webmap101/leaflet.ajax.min.js 404 (Not Found)

index.html:95 Uncaught TypeError: L.GeoJSON.AJAX is not a constructor at index.html:95

  • Have you tried L.geoJSON.ajax(...) ? – Matt Needle Feb 15 at 8:38

There are several things that have to be corrected.

First thing is wrong path to ajax library leaflet.ajax.min.js. Error 404 for file webmap101/htdocs/webmap101/leaflet.ajax.min.js tells you that there is no such file on this path on the server. Check it.

Second thing is that statement for including ajax library

<script src="htdocs/webmap101/leaflet.ajax.min.js" type="text/javascript" ></script>

has to be placed after statement for including Leaflet library

<script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js"

Third thing is that even if you correct above errors, there might be problems beacuse geojson layer is added to map before it is actually loaded. Solution for this is adding layer after it has been loaded:

var geojsonLayer = new L.GeoJSON.AJAX(
geojsonLayer.on('data:loaded', function(){

Ajax call must be AFTER leaflet call in the header.

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

  • If you became aware of error in your question after posting it you can edit your question to correct it. – TomazicM Feb 15 at 18:29

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.