Использование setColor () с .addLayer () Mapbox - PullRequest
0 голосов
/ 20 апреля 2020

Здравствуйте. Я возиться с некоторыми публикуемыми наборами данных c Covid_19 и пытаюсь создать визуализацию стран мира и их соответствующих подтвержденных случаев, смертей и восстановленных статистических данных. Я использую mapbox для создания карты и .addSource для добавления гео Json слоя стран. Прямо сейчас этот слой всего одного цвета, потому что внутри части .addLayer он принимает только один цвет:

map.addLayer({
      'id': 'world_countries_fill',
      'type': 'fill',
      'source': 'world_countries',
      'paint': {
           'fill-color': '#f08', // <<<
           'fill-opacity': 0.4
      }

можно ли использовать функцию, которая возвращает цвет, основанный на количестве смертей для этого одна страна в mapbox .addLayer ()?

Или мне стоит использовать листовку и газон. js featureCollection?

вот мой полный js файл:

function Country(name, death, recovered, confirmed) {
    this.name = name;
    this.death = death;
    this.recovered = recovered;
    this.confirmed = confirmed;
}

var countryArray = []; //array of country objects

function init() {
    get_data();

    console.log(countryArray);

    mapboxgl.accessToken = '***';
    var map = new mapboxgl.Map({
        container: 'map_area',
        style: 'mapbox://styles/mapbox/dark-v10',
        center: [4.899, 52.372],
        zoom: 2,
    });

    map.scrollZoom.disable();


    map.on('load', function() {
            map.addSource('world_countries', {
                type: 'geojson',
                data: 'world.geojson'
            });

            map.addLayer({
                'id': 'world_countries_fill',
                'type': 'fill',
                'source': 'world_countries',
                'paint': {
                    'fill-color': '#f08',
                    'fill-opacity': 0.4
                }
                //color function here
                /*
                'fill-color': function() {
                    let length = countryArray.length;

                    for(let i = 0; i < length; i++) {
                        let country = countryArray[i];
                        let color = getColorDeaths(country.deaths)
                    }
                    return color;
                },
                */
            });
    });


}

function getColorDeaths(d) {
    return d > 500000 ? '#800026' :
            d > 350000  ? '#BD0026' :
            d > 150000  ? '#E31A1C' :
            d > 85000  ? '#FC4E2A' :
            d > 25000   ? '#FD8D3C' :
            d > 8500   ? '#FEB24C' :
            d > 950   ? '#FED976' :
                        '#FFEDA0';
}

//fetchs data from the source and calls load_country_data on the json file
function get_data() {
    fetch("https://pomber.github.io/covid19/timeseries.json")
        .then(response => response.json())
        .then(data => {
            //console.log(data); //will print the json object
            load_country_data(data);
        })
        .catch(err => console.error(err));
}

//creates a Country object from each key in the json data fetched and appends the object to an array.
function load_country_data(data) {
    let json_Length = Object.keys(data).length; //amount of countrys
    let c_keys = Object.keys(data); //list of the keys
    //console.log(json_Length);

    for(let i = 0; i < json_Length; i++) {
        let tmp = new Country(); // create new Country object for each country
        let name = c_keys[i] //get the name of the country
        let length = data[name].length; //get the length from inside the country

        let tmp_deaths = 0;
        let tmp_recovered = 0;
        let tmp_confirmed = 0;

        //console.log(test[i]); // <this is how you would get the name of each country as a string
        //console.log(data['Angola']); // <this is how you get to each country

        //console.log(data[name][4]);
        //console.log(data[name][4].deaths);

        for(let i = 0; i < length; i++) {
            tmp_deaths += data[name][i].deaths;
            tmp_recovered += data[name][i].recovered;
            tmp_confirmed += data[name][i].confirmed;
        }

        //fill in the country object with the data!
        tmp.name = name;
        tmp.death = tmp_deaths;
        tmp.confirmed = tmp_confirmed;
        tmp.recovered = tmp_recovered;

        countryArray.push(tmp); //add the new object to an array to keep track
    }
}



window.onload = init;

1 Ответ

0 голосов
/ 28 апреля 2020

Вы можете реализовать эту функцию, используя выражение для свойства 'fill-color'. Вот пример , демонстрирующий, как стилировать круги с помощью свойства, управляемого данными. Ваша реализация может использовать аналогичный подход, вместо этого используя, возможно, выражения interpolate или step, чтобы указать различные цвета заливки в зависимости от количества случаев. В этом примере создания и стили кластеров показано, как использовать выражение step очень похоже на то, что вы хотите сделать, закрашивая кружки в зависимости от того, в какой диапазон чисел попадает счет для конкретного кластера.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...