【问题标题】:AmCharts4: getPolygonById method for custom map from GeoJSON?AmCharts4:来自 GeoJSON 的自定义地图的 getPolygonById 方法?
【发布时间】:2022-01-19 22:35:18
【问题描述】:

我正在尝试将 getPolygonById 方法与使用自定义 GeoJSON 数据创建的地图多边形系列一起使用(这是为了缩放到具有特定 ID 的多边形)。我已按照creating custom maps 提供的说明进行操作。

来自自定义 GeoJSON 数据的 Map Polygon Series 渲染和事件正常运行(例如,缩放到多边形或在“点击”时更改颜色)。

但是,当调用 customSeries.getPolygonById("ExampleID") 时,该方法返回“undefined”。请注意,customSeries 的 GeoJSON 源包含相应的 id 字段(即“id”:“ExampleID”)。

也就是说,尽管渲染正确,但以下代码返回“未定义”:

var customSeries = map.series.push(new am4maps.MapPolygonSeries());
customSeries.geodataSource.url = "/geojson/customSeries.geojson";
customSeries.useGeodata = true;
console.log(customSeries.getPolygonById("ExampleID"));

这与使用 Amcharts 地图模板时返回的带有指定地图多边形的 JSON 对象形成对比。例如,以下代码返回一个对应于“US”id 的 Map Polygon 的对象:

var worldLow = map.series.push(new am4maps.MapPolygonSeries();
worldLow.useGeodata = true;
worldLow.geodata = am4geodata_worldLow; 
console.log(worldLow.getPolygonById("US"));

这是我的数据的问题吗?或者从自定义 GeoJSON 调用地图多边形系列上的 getPolygonById 是否需要额外的东西?

【问题讨论】:

    标签: geojson amcharts amcharts4


    【解决方案1】:

    通过 DataSource / GeoDataSource 对象加载数据是异步完成的,因此您的 getPolygonById 调用在数据被解析并加载到系列之前执行。您可以使用DataSource中的done事件或系列中的datavalidated事件在调用getPolygonById之前检查数据是否已加载

    polygonSeries.geodataSource.events.on('done', function() {
      // timeout needed as the data isn't complately loaded at this point
      setTimeout(function() {
        console.log('done: ', polygonSeries.getPolygonById('BCH'))
      }, 100)
    })
    // OR
    polygonSeries.events.on('datavalidated', function() {
      // check if there's data loaded in the array before looking up
      // the polygon
      if (polygonSeries.data.length) {
        console.log('data loaded', polygonSeries.getPolygonById('BCH'))
      }
    })
    

    Demo

    【讨论】:

    • 这很有帮助,感谢您的澄清!
    • 三个后续问题:(1)是否有与geodataSource 和/或dataValidated 事件的事件监听器相关的AmCharts 文档? (2) 我知道“dataValidated”只记录数据的变化——因此如果数据已经验证,事件不会触发? (3) 可以使用 async/await 来等待添加地理数据吗?
    • 1:是的,有几个:amcharts.com/docs/v4/concepts/event-listeners 和 amcharts.com/docs/v4/concepts/data/loading-external-data/… 以及参考部分中的特定于类的文档。 2:每当需要重新解析数据时触发,包括初始化和更改。 3.没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    相关资源
    最近更新 更多