[GIS] Google Maps API: Can’t load GeoJSON when inside a function

google-maps-api

I use the sample provided on the Google Maps API page (https://developers.google.com/maps/documentation/javascript/datalayer).

I put the sample inside a function like following

function loadCableGeom(){
        _this.map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json');
        _this.map.data.setStyle({
          fillColor: 'green',
          strokeWeight: 1
        });
        console.log("LOAD");
}

function removeCableGeom(){
        _this.map.data.setMap(null);
}

I am sure the call to loadCableGeom() is done as the console.log("LOAD") works well.

If the loadGeoJson is put outside the function just above the function definition (in this case I remove the underscore), the GeoJSON is well loaded. And in this case the GeoJSON is removed when the function removeCableGeom() is called.

Best Answer

Try to catch you map in a log.

function loadCableGeom(){
  console.log(yourmap);
  _this.map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json');
  _this.map.data.setStyle({
    fillColor: 'green',
    strokeWeight: 1
  });
  console.log("LOAD");
}

If it doesn't work try to pass it into your function with a parameter function loadCableGeom(map). Maybe your _this.map doesn't work.

Related Question