Christi Hähnchen Christi Hähnchen - 1 month ago 19
JSON Question

(Geo)JSON to object Array

I´m a beginner in JavaScript and I´m struggling a bit with converting a GeoJSON to a javascript Object Array.

So with JSON.parse I parse my serverside generated JSON into a JSON-Object. So far so good.

The Google method addGeoJson returns me [object (Array)]. But this method shows me onload the shape on the map. I need it later, when I want to display different granularities when I zoom in or out.

I need to generate an [object (Array)] out of an [object]. How do I do this? Out of "generatedGeoJsonPlz2"

This is what I have so far:

var generatedGeoJsonPlz1 = JSON.parse(geoJsonString);
var generatedGeoJsonPlz2 = JSON.parse(geoJsonString2);

var plz1area = plz.data.addGeoJson(generatedGeoJsonPlz1); // returns [object (Array)]

plz.addListener('zoom_changed', function() {
var zoom = plz.getZoom();
if (zoom == 8) {
for (var i = 0; i < plz1area.length; i++) {
plz.data.remove(plz1area[i]);
}
plz.data.addGeoJson(generatedGeoJsonPlz2);
}
// here i´m struggling. i need the [object (Array)] to delete the old Json
else if (zoom == 5) {
var plz2area = generatedGeoJsonPlz2;

for (var i = 0; i < plz2area.length; i++) {
plz.data.remove(plz2area[i]);
}
plz.data.addGeoJson(generatedGeoJsonPlz1);
}
}


Thanks!
Christian

Answer

You can store the result of addGeoJson(generatedGeoJsonPlz2) to be able to remove it later.

This may work for you:

var generatedGeoJsonPlz1 = JSON.parse(geoJsonString); 
var generatedGeoJsonPlz2 = JSON.parse(geoJsonString2);

var plz1area = plz.data.addGeoJson(generatedGeoJsonPlz1);
// Here I already define the variable plz2area
var plz2area;

plz.addListener('zoom_changed', function() {
  var zoom = plz.getZoom();
  if (zoom == 8) {
    for (var i = 0; i < plz1area.length; i++) {
      plz.data.remove(plz1area[i]);
    }
    plz2area = plz.data.addGeoJson(generatedGeoJsonPlz2);
  } else if (zoom == 5) {
    // Only remove plz2area from the map, if it has been initialized before
    if (plz2area) {
      for (var i = 0; i < plz2area.length; i++) {
        plz.data.remove(plz2area[i]);
      }
    }
    plz.data.addGeoJson(generatedGeoJsonPlz1);
  }
}