0

I am trying to add a .json vector layer to a Leaflet.js map, viewable here via GitHub page, with source code here.

Here's a shortened version of the file for reference (the GitHub page linked above shows it working in context).

<!DOCTYPE html>
<html>

<head>

  <meta charset="utf-8">


  <!-- LEAFLET-->

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />
  <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>

  <style>
    html,
    body {
      height: 100%;
      margin: 0;
    }

    #map {
      width: 600px;
      height: 600px;
    }
  </style>

</head>

<body>

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

  <script>
    var map = L.map('map').setView([-7.08, -78.5565467], 12);
    let osmLayer = L.tileLayer('https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}@2x.png', {
      attribution: 'Wikimedia maps beta | &copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    let marker = L.marker([-7.2861634, -78.579712])
      .addTo(map);
    let marker2 = L.marker([-7.1605494, -78.5392218])
      .addTo(map);
    ///let test_L = L.geoJSON("test.json", {
    ///weight: 2,
    /// color: '#100'
    ///}).addTo(map);
    //let layerGroup = L.geoJSON(watersheds, {
    // onEachFeature: function (feature, layer) {
    //layer.bindPopup('</h1><p>name: '+feature.properties.WTSHNAME+'</p>');
    //  }
    // }).addTo(map);
    //street layer using mapbox basic
    // Changed to OSM just to avoid the token requirement, for the purpose of demo.
    var mapboxbasic = L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
      maxZoom: 18,
      zIndex: 1
    });
    //aerial layer using mapbox satellite
    // Changed to OSM just to avoid the token requirement, for the purpose of demo.
    var mapboxsat = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 18,
      zIndex: 2
    });
    var Esri_WorldImagery = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
      attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
    });
    var basemap = {
      'Streets': mapboxbasic,
      'Aerials': mapboxsat,
      'ESRI Imagery': Esri_WorldImagery
    } // Refer to the individual Tile Layers only. They will go into the tilePane.
    ;
    L.control.layers(basemap).addTo(map); // Layers Control just to switch between the 2 basemaps.
  </script>


</body>

</html>

The code (with the errant sections commented out) successfully add in markers using lat long coordinates, but my code breaks when I try to reference the .json file. [By 'breaks', I mean that the base layer selection panel in the top right corner disappears and the vector layer is not added.]

The .json file is called in using <script src="test.json" type="text/javascript"></script> [with the .json file hosted on GitHub]

The code I have tried is:

    let test_L = L.geoJSON(test, {
        weight: 2,
        color: '#100'
      }).addTo(map);

Following the official example at: https://leafletjs.com/examples/geojson/

And :

   $.getJSON("test.json",function(data){
   L.geoJson(data).addTo(newMap);
   });

Following the discussions here on StackOverflow, on this forum, and as modelled with this gist -- all to no avail.

I am clearly missing something, but I don't understand what.

For comparison, I managed to get this example working on Observable.

Can anyone help to point me in the right direction? I'd really appreciate it!!

Thanks in advance for your time and guidance,

Aaron

aaron.kyle
  • 163
  • 3
  • 10
  • ` – Quentin Sep 05 '18 at 20:47
  • `$.getJSON("(test.json"` — This looks like you just made a typo and added a `(` to the URL. – Quentin Sep 05 '18 at 20:49
  • 1
    If the typo isn't the problem, then there isn't much we can say given the information you've provided. Do some debugging. Use the developer tools in your browser. Check the network tab to see if the data is being fetched correctly. Add console.log statements to see if functions are being run and if the data looks the way you expect. – Quentin Sep 05 '18 at 20:49
  • Thanks Quentin! I tried referencing in the `.json` file with ``). I am still learning here (very much a newbie). – aaron.kyle Sep 05 '18 at 20:51
  • Thank you again, Quentin. I checked and the typo does not appear to be the problem. I'll try to look into the developer tools. I provided the link to my code on GitHub, but can add the full code in here (with the problematic sections commented out). I suspect the issue is indeed with fetching the data. I am not sure how to resolve. – aaron.kyle Sep 05 '18 at 20:54
  • You mentioned using the URL to the github .json file. How are you setting the url in $.getJSON? Or is it internal and on the same level as the html file? – CodeMonkey Sep 05 '18 at 20:59
  • Hi @CodeMonkey, and thanks for your help! It doesn't work as either an absolute URL: `$.getJSON("https://raw.githubusercontent.com/aaronkyle/concept/gh-pages/web-gis/sandbox/test.json",function(data){ L.geoJson(data).addTo(newMap); });` .. or as an abbreviated URL: `$.getJSON("test.json",function(data){ L.geoJson(data).addTo(newMap); });` The file is sitting in the same directory and [on the same level as the HTML file](https://github.com/aaronkyle/concept/tree/gh-pages/web-gis/sandbox). – aaron.kyle Sep 05 '18 at 21:07
  • @aaron.kyle — See my previous comment about debugging. You need to narrow down where the problem is. – Quentin Sep 05 '18 at 21:22
  • One thing that can help with debugging is moving the script code into a `.js` file. That way you can utilize the the debugger in browsers. – CodeMonkey Sep 05 '18 at 21:54
  • @CodeMonkey - the debugger does work with inline ` – Quentin Sep 05 '18 at 21:54
  • So it seems. Never knew. Still, good practice to put the scripts in `.js` files. – CodeMonkey Sep 05 '18 at 22:02

2 Answers2

2

Thanks to @CodeMonkey for the leads on this answer:

This guidance on loading in .json files from other forum posts was good, the code

   $.getJSON("test.json",function(data){
   L.geoJson(data).addTo(newMap);
   });

is appropriate for calling in the JSON data. My mistake, as @CodeMonkey notes, is that I used map as the id / name for the function, but the examples were adding data to newMap, which didn't exist in my example.

Also, to get this working properly, I needed to add in JQuery to my HTML file, so adding:

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

into the <head> section.

The code now works:

https://aaronkyle.github.io/concept/web-gis/sandbox/leaflet-test.html

Awesome.

Thanks to everyone for helping me to work though this question!!

aaron.kyle
  • 163
  • 3
  • 10
0

So first thing that I noticed was that the github link you have for the raw of the .json file is not working. Probably a github issue.

I mention that because you were trying to get it to use. in jQuery, when using a URL on a remote host, you have to add at the end ?callback=? to get it to use JSONP instead. stackoverflow answer

Moving on, to reference the .json file, you need to use the path in relative format. If the .json file is in the same directory as the .html file, then it should work. If it is down a level, then you would do /down/test.json as the path.

I was able to replicate part of your code into a plunker

I think the issue was you were trying to set the .json points to newMap which does not exist.

CodeMonkey
  • 1,136
  • 16
  • 31
  • "when using a URL on a remote host, you have to add at the end ?callback=? to get it to use JSONP" — (1) It isn't on a remote host. The OP said they were in the same folder. (2) JSONP (a) only works if the data is in JSONP format and (b) is a horrible hack that was superceded years ago by CORS. – Quentin Sep 05 '18 at 21:37
  • This is the OP's quoted code: `$.getJSON("test.json"`. That is a relative URL. – Quentin Sep 05 '18 at 21:38
  • 1
    Did you even read? He mention that he tried using the link of it via GitHub. I am working on what I know and can gather from the OP and other places. I went on to point out that his code was setting to `newMap`, not `map`, which I believe is the issue, unless the OP was mistaken or was trying something not shown. I only pointed out the relative path part because the OP seemed confused or not well informed on how it worked, since he is, as he said, "very much a newbie". Perhaps he did know about, but perhaps not. – CodeMonkey Sep 05 '18 at 21:47
  • *"when using a URL on a remote host, you have to add at the end ?callback=? to get it to use JSONP instead"* only works the remote host supports JSONP. It's not a silver bullet to access any kind of remote resource. – Felix Kling Sep 05 '18 at 22:15
  • Thanks to all of you for helping me through this! I am still working to figure out how to use the debugging tools per @Quentin 's guidance, but haven't yet found a solution. To get around any CORS issues, I tried using rawgit.com, and therefore substituted the relative path `test.json` with https://cdn.rawgit.com/aaronkyle/concept/gh-pages/web-gis/sandbox/test.json, but this didn't get me through it. As @Quentin noted, the issue does seem to have to do with the `.json` file not being appropriately "loaded" (for lack of a better term), but I still don't get why or how to correct. – aaron.kyle Sep 05 '18 at 23:41
  • Console log the data when it comes out of the jQuery. And see what it is. If it is not what you expected then you have narrowed it down. – CodeMonkey Sep 06 '18 at 00:16
  • Thanks @CodeMonkey. Honestly I am not so good yet with these console logs, but am trying.... More soon (though I am surprised this is such an active discussion and challenging issues; seems there's just something simple I'm missing regarding how to call in the json data using Leaflet.js). – aaron.kyle Sep 06 '18 at 00:21