2

I'm quite new to JavaScript and I have been trying to add my GeoJSON files to a web page. I can't seem to figure out how to get the GeoJSON to actually load. I've checked it using GeoJson.io and it draws correctly there. I just can't get it to load on my page. The OSM portion works just fine no issues showing that.

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?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.streets'
}).addTo(mymap);

var StratStyle = {
    "color": "#d3d3d3",
    "weight": 5,
    "opacity": 0.65
};

var geojson = new L.GeoJSON.AJAX("StratfordBoundary", {style:StratStyle});
geojson.addTo(map);

here is the entire code

enter image description here

  • Why is var mymap = L.map('map1').setView([43.370917,-80.983042], 13); inside <style> ? That shouldn't work at all. – obrob Feb 9 at 18:59
  • Idk, when I take it out it still works. I think it's just residual from something I was trying. I don't think it's an issue right now though – PVar Feb 9 at 19:00
  • var mymap = L.map('map1').setView([43.370917,-80.983042], 13); creates your map variable. It must be in the code so later you can actually add your geojson to this variable which contains your map. Put it right in front of L.tileLayer inside your js-script. – obrob Feb 9 at 19:08
  • @PVar Regarding your last posted code see EDIT2 in my answer. – TomazicM Feb 10 at 15:14
3

New answer:

Try this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test</title>

    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
    <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-ajax/2.1.0/leaflet.ajax.min.js"></script>

<style> 
    #map1 { height: 500px; width: 550px }
</style>

</head>

<body>

    <div id="map1">
    </div>

<script>
var mymap = L.map('map1').setView([43.370917,-80.983042], 13);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?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.streets'
}).addTo(mymap);

var geojson = new L.GeoJSON.AJAX("StratfordBoundary.geojson");
geojson.on('data:loaded', function(){
geojson.addTo(mymap);
});
</script>

</body>

</html>

The errors I could find:

  • L.GeoJson.ajax needs to be L.GeoJSON.AJAX
  • var mymap = L.map('map1').setView([43.370917,-80.983042], 13); needs to be in your script, not inside your style definition
  • The div container for your map was missing

However, the .html file above now works fine for me with my own test .geojson. I just drew a simple polygon in QGIS and saved it as StratfordBoundary.geojson (EPSG:4326) in the same folder as the .html file.


Old answer:

Try without a style first until it works:

var geojson = new L.GeoJSON.AJAX("StratfordBoundary.geojson");
geojson.addTo(mymap);

Add the filetype and check if the path to your .geojson is correct. Also make sure to point to the correct map instance you are using. I assume it is mymap as you use this for OSM and this one is working. If its working you can try:

var geojson = new L.GeoJSON.AJAX("StratfordBoundary.geojson", {style:StratStyle});
geojson.addTo(mymap);

It also seems like you are pointing to a wrong path for the plugin. It should be without a / at the beginning:

<script src="js/leaflet-0.7.2/leaflet.ajax.min.js"></script>

Alternatively you can also use jQuery with $.getJSON. Here is an example:

$.getJSON("StratfordBoundary.geojson", function (data) {
    var StratfordBoundary = L.geoJSON(data,
        {
            onEachFeature: function onEachFeature(feature, layer) {
                layer.bindPopup('<strong>' + feature.properties.Title + '</strong><br><br>Description: ' + feature.properties.Descr);
        }
        }).addTo(mymap);
});     

Also try the console of your webbrowser. This may help finding your issue. Firefox and Chrome

2

Most probably geoJSON layer does not show because data is not loaded yet when you add layer to the map. Try with this code:

var geojson = L.geoJson.ajax('StratfordBoundary', {style: StratStyle});
geojson.on('data:loaded', function() {
  mymap.addLayer(this);
});

As PVar wrote, also make sure that geoJSON file named StratfordBoundary actually exists on home directory of your project on server.

EDIT1: If you run your code locally on file system, then you must add local: true option to ajax call:

var geojson = L.geoJson.ajax('StratfordBoundary', {style: StratStyle, local: true});

EDIT2: The way you refer to leaflet.ajax.min.js in the last incarnation of your question:

<script src="Z:\Leaflet\leaflet.ajax.min.js"><script>

will never work because of security reasons. Put your Leaflet directory in the same directory where you have your project file and refer to it:

<script src="Leaflet/leaflet.ajax.min.js"><script>

The second problem is calling your project in browser from file system, not from server. Here you will have CORS (cross-origin) security problems. It also depends on the settings of the browser, but I managed to display map and geojson successefully from file system in Firefox, but not in Chrome or IE11. Crome reports the following error in console:

leaflet.ajax.js:373 Access to XMLHttpRequest at 'file:///C:/inetpub/wwwroot/LeafletExamples/geoJSON/StratfordBoundary.geojson'
from origin 'null' has been blocked by CORS policy:
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
  • So I just added that in and my data still won't load – PVar Feb 9 at 18:13
  • Do you have file named StratfordBoundary on home directory of your project on the server? Does your server allow loading files without file type? – TomazicM Feb 9 at 18:17
  • I do have it in the same directory – PVar Feb 9 at 18:23
  • What about the second question? Is the file displayed if you refer to it directly in the browser: http://server/path/StratfordBoundary? – TomazicM Feb 9 at 18:36
  • The geojson file is just on my machine. Not hosted on a server or anything – PVar Feb 9 at 18:50
0

Here I just define the layer, than using JQuery's getJSON, I load the GeoJSON into the layer, then add it to the map. Example link included.

var url = 'states.json';  // my GeoJSON data source.

function style(feature) {
    return {
        fillColor: 'green', 
        fillOpacity: 0.5,  
        weight: 2,
        opacity: 1,
        color: '#ffffff',
        dashArray: '3'
    };
}
        function forEachFeature(feature, layer) {

            var popupContent = "<p><b>STATE: </b>"+ feature.properties.STATE_NAME +
                "</br>REGION: "+ feature.properties.SUB_REGION +
                "</br>STATE ABBR: "+ feature.properties.STATE_ABBR +
                "</br>SQ Miles: "+ feature.properties.SQMI.toLocaleString() +'</p>';

            layer.bindPopup(popupContent);

        }

// Null variable that will hold layer
var stateLayer = L.geoJson(null, {onEachFeature: forEachFeature, style: style});

//Adding data to variable
    $.getJSON(url, function(data) {
        stateLayer.addData(data);
    });
//Adding layer to map
 stateLayer.addTo(map);

http://www.gistechsolutions.com/leaflet/DEMO/basic/basic_Poly.html

  • Does this solution work if you run page locally from file system and geojson file is also local file? Because that's basically the problem that PVar has. – TomazicM Feb 11 at 14:36
  • Yes, I edited my response the include my url variable, it's just a GeoJSON file stuck in the same web folder as the html. It could be a PHP page service GeoJSON, if you wanted dynamic data from a database, but static data from a file works also. – Bill Chappell Feb 11 at 14:42
  • I was not clear enough. PVar runs his/her map page (probably something.html) locally from file system, not from web server. And then there come CORS problems (see EDIT2 in my answer). – TomazicM Feb 11 at 14:48
  • You could place a script tag in the HTML <script src="sample-geojson.js" type="text/javascript"></script> and then put a variable in the GeoJOSN file, Finally using L.geoJSON leafletjs.com/examples/geojson But really it should be on a web server. – Bill Chappell Feb 11 at 15:47
  • Yes, this is the final possibility when running from file system. – TomazicM Feb 11 at 17:00

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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