使用JQuery和在线JSON数据填充JVectorMaps

问题描述 投票:1回答:1

我正在使用JSON数据直接填充JVectorMaps(及其他)。大多数常见指标的最新统计信息可通过json在线获得-因此此脚本应使您可以快速,轻松地提取所需的任何数据。我只是还不太了解格式代码,因为我对JQuery和JS非常陌生。我在被困的地方打了一个问号。

理想情况下,获取和数据脚本可以采用ind_id变量和标签,以在Vector Map上显示任何指标,而不仅仅是我在此处用作示例的一个GDP(NY.GDP.MKTP.CD)指标。

document.addEventListener('DOMContentLoaded', () => {
    console.log("loaded")
    fetchCountryData()
})

function fetchCountryData () {
    fetch('http://api.worldbank.org/v2/country/all/indicator/NY.GDP.MKTP.CD?format=json&mrv=1&per_page=300)
    // 
    .then(resp => resp.json())
    .then(data => {
        let country.id = data[1]
        let value = data[1]
    create-GDP-Data(country.id,value)
})  
}

function create-GDP-Data(country.id,value){
    let gdpData = ?
}

$('#world-map-gdp').vectorMap({
  map: 'world_mill',
  series: {
    regions: [{
      values: gdpData,
      scale: ['#C8EEFF', '#0071A4'],
      normalizeFunction: 'polynomial'
    }]
  },
  onRegionTipShow: function(e, el, code){
    el.html(el.html()+' (GDP - '+gdpData[code]+')');
  }
});

GDP数据(gdpData)的格式应如下:

var gdpData = {
  "AF": 16.63,
  "AL": 11.58,
  "DZ": 158.97,
  ...
};
javascript jquery json jvectormap
1个回答
0
投票

您知道请求的数据集返回的数据结构与jVectorMap所需的数据结构有所不同。因此,您需要的是从传入数据到后者的重新映射。

为了使这种方法更加灵活,我的建议是使用简单的remapper函数,您可以在其中传递传入字段的名称,然后接收该值。

请参阅下面我提案中的评论以获取更多信息:

DEMO:动态加载jVectorMap区域数据集

$(function() {
  /* Handler for jQuery .ready() */
  
  function mapper(data, key) { 
    /* Deep search for a key, return the value found. */
    var keys = key.split('.'), value = data[keys.shift()];
    for (i=0, l=keys.length; i<l; i++) {value = value[keys[i]]}
    return value;
  }     
   
  function showMapValues(map, schema, values, min, max) { 
    var regions = map.series.regions[0];
    /* Reset the scale min & max, allow recomputation. */ 
    regions.params.min = min;
    regions.params.max = max;
    regions.setValues(values.regions);
    map.dataSetName = schema.dataSetName;
    map.dataSetFormat = schema.dataSetFormat; 
  }
  
  function fetchCountryData(url, params, schema, map) {
    $.ajax({
      url: url,
      dataType: 'json',
      data: params,
      success: function(result) { 
        var values = {regions: {}, markers: {}},
            dataSet = result[schema.dataSetIndex];
        /* Loop over the returned dataset and invoke remap. */
        $.each(dataSet, function(i, item) { 
          var code = mapper(item, schema.countryCodeField),
              value = mapper(item, schema.countryValueField) || 0;
          /* Find out if this is a valid region inside the map. */
          var isRegionCode = typeof map.regions[code] !== 'undefined';
          /* Find out if this is a valid marker inside the map. */
          var isMarkerCode = typeof map.markers[code] !== 'undefined';
          /* Fill two separate datasets for regions & markers. */
          if(isRegionCode) values.regions[code] = value;
          if(isMarkerCode) values.markers[code] = value;
        });         
        /* Dynamically update the map with the new values */
        showMapValues(map, schema, values);
      },
      error: function(request, textStatus, errorThrown) { 
        console.log("error:",request, textStatus, errorThrown);
      }
    }); 
  }
  
  var worldMap = new jvm.Map({
    map: 'world_mill_en',
    container: $('#world-map'),
    zoomOnScroll: true,
    regionsSelectable: true,
    regionsSelectableOne: true, 
    backgroundColor: "aliceblue", 
    markers: [], /* Initialize the map with empty markers */
    series: {
      regions: [{
        values: {}, /* Initialize the map with empty region values */
        scale: ['#C8EEFF', '#0071A4'],
        normalizeFunction: 'polynomial'
      }],
      /* Initialize the map with empty marker values */
      markers: [{attribute: 'fill', scale: {}, values: []}]
    }, 
    onRegionTipShow: function(e, el, code){
      var value = worldMap.series.regions[0].values[code],
          formattedValue = new Intl.NumberFormat('en-US', worldMap.dataSetFormat).format(value);
      el.text(el.text() + ' (' + worldMap.dataSetName + ': ' + formattedValue + ')');
    }
  });
      
                                                                                                                       
  var url = 'https://api.worldbank.org/v2/country/all/indicator/NY.GDP.MKTP.CD',
      params = 'format=json&mrv=1&per_page=300',
      /* Define the data type & the location of the relevant fields inside the incoming data */
      schema = {
        dataSetName: 'GDP', 
        dataSetFormat: {style: 'currency', currency: 'USD'}, 
        dataSetIndex: 1, 
        countryCodeField: 'country.id', 
        countryValueField: 'value'
      }; 
      
  fetchCountryData(url, params, schema, worldMap);
   
});
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/jquery-jvectormap.min.css" type="text/css">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/jquery-jvectormap.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/tests/assets/jquery-jvectormap-world-mill-en.js"></script>
</head>

<body>
  <div id="world-map" style="width: 600px; height: 400px"></div>
</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.