Search code examples
amchartsamcharts4

Amcharts4 Maps with custom geojson data only show one feature (geographical region) out of many?


I was trying to create a map with amcharts4's custom maps using this tutorial. It works perfectly when I used a map from amcharts geojson library. But when I add a different map like this map. It only shows the last feature of geojson feature collection. I tried adding a id as described here in this issue but It gave me the same result. Can anybody help me to get this work?

here is a code pen demostrating the issue: https://codepen.io/sankhax/pen/YzwLdJy

Thanks in advance.


Solution

  • Your GeoJSON is still missing the id property, which needs to be unique for each feature in your JSON's features array; the tutorial states that it needs to be in the top-level of the feature object, but having an id in the properties object also works, as you can see in the other map in your codepen. The value stored in electoralDistrictCode from your properties data is a good candidate for an id:

    [{
        "type": "Feature",
        "id": "MON",
        "properties": {
            "electoralDistrictCode": "MON",
            "electoralDistrict": "Monaragala",
            // ...
        },
        "geometry": {/* ... */}
    },{
        "type": "Feature",
        "id": "ANU",
        "properties": {
            "electoralDistrictCode": "ANU",
            "electoralDistrict": "Anuradhapura",
            // ...
        },
        "geometry": {/* ... */}
    },
    // ...
    ]
    

    Once you add this to your JSON, your map will render correctly in AmCharts v4. Demo below, using a manual AJAX request to mutate the JSON to work with the library:

    var map = am4core.create("chartdiv", am4maps.MapChart);
    // indonesia geojson
    fetch(
      "https://raw.githubusercontent.com/GayanSandaruwan/elections/master/electoral_with_results.geojson"
    )
      .then(function(resp) {
        if (resp.ok) {
          return resp.json();
        }
        throw new Error("Unable to fetch json data");
      })
      .then(function(data) {
        //add the missing id property before assigning it to the map
        data.features.forEach(function (feature) {
          feature.id = feature.properties.electoralDistrictCode;
        });
        map.geodata = data;
      });
    map.projection = new am4maps.projections.Miller();
    var polygonSeries = new am4maps.MapPolygonSeries();
    polygonSeries.useGeodata = true;
    map.series.push(polygonSeries);
    <script src="https://www.amcharts.com/lib/4/core.js"></script>
    <script src="https://www.amcharts.com/lib/4/maps.js"></script>
    <div id="chartdiv" style="width: 100%; height: 400px;"></div>