1

I am adding using GeoJSON data pulled from a service. I want to load the GeoJSON layer but I don't want to display the data on map. This code is adding myLayer with the default blue color to the map. Why is my layer added to the map even if I have not called myLayer.addTo(map)? I just want to use it as source data for a search function, not to display them on the map.

fetch('url')
.then(function(response) {
    return response.text();
  })
  .then(function(res) {
    return JSON.parse(res)
  })
  .then(function(res){
    myLayer= new L.geoJSON(res);
  })
1
  • 1
    Please provide a minimal runnable example that reproduces the error, for example with jsfiddle.net or codepen.io. Alternatively post the code here. Its very hard to say without more code.
    – til_b
    Commented Feb 28, 2019 at 11:10

1 Answer 1

3

I have a minimal working example at https://codepen.io/anon/pen/MxaEOW that does what you want without error.

The relevant code part is

var map = new L.Map('map').setView([ 52, 9 ], 4);
....
var myLayer; // just create the global variable, no assignment yet!


document.getElementById("fetch").addEventListener("click",
  function() {

    fetch("https://gist.githubusercontent.com/anonymous/e54a23c4d5204d7ea8c1/raw/a9559d405c30630caccc4a59c26e20a2d44f3d6e/map.geojson")
    .then(function(response) {
      return response.text();
    })
    .then(function(res) {
      return JSON.parse(res)
    })
    .then(function(res){
      // assign to global variable. Don't add yet!
      myLayer= new L.geoJSON(res);
      // display feature count, for debugging purposes (returns 6 features)
      document.getElementById("r").innerHTML = Object.keys(myLayer._layers).length + " features"
    })
  }
);

document.getElementById("addmylayer").addEventListener("click",
  function() {
    // add myLayer to map here. myLayer is global, so can be used.
    myLayer.addTo(map);
  });

This works, so probably you already added the layer somewhere in your code, either by calling myLayer.addTo(map) or by specifying the layer in the map constructor (thanks @TomazicM , see comment)!

2
  • Thanks for your example, really neat! I must look again at my code where it might be added on the map. It's quite small application so I am surprised that I might have missed it. Will be out for a couple of days but will go and have a look and compare
    – geogrow
    Commented Feb 28, 2019 at 17:18
  • 1
    Layer can also be added when defining map, for example: var map = L.map('map', {center: [52, 9], zoom: 4, layers: [myLayer] });
    – TomazicM
    Commented Feb 28, 2019 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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