Saurabh Palatkar
Saurabh Palatkar

Reputation: 3384

Filling color to polygons using Mabox-gl-js

I've countries GeoJson with a geometry of type polygon. Each polygon has only one property name (name is the country name). each polygon represents a country.

Now I want to paint each polygon with different color depending on the value of the name property, but this is not working properly.

See this JS bin Demo

map.on('load', function () {
    map.addLayer({
        'id': 'maine',
        'type': 'fill',
        'layout': {},
        'paint': {
            'fill-color': {
              property: 'name',
                stops: [
                    ['Albania', '#F2F12D'],
                    ['Algeria', '#7A4900'],
                    ['Australia', '#63FFAC'],
                    ["South Africa", "#4FC601"],
                    ["South Korea", "#3B5DFF"],
                ]
            },
            'fill-opacity': 0.8
        },
        'source': {
            'type': 'vector',
            'url': 'mapbox://saurabhp.countries_tileset'
        },
       "source-layer": "countries",
    });
});

Upvotes: 1

Views: 1606

Answers (1)

Aravind
Aravind

Reputation: 389

Every thing in your code was perfect, the only thing which you have missed out is type: 'categorical' inside the fill-color, You need to specify the type

Checkout this link for more details run the below code snippet to see the demo

mapboxgl.accessToken = 'pk.eyJ1Ijoic2F1cmFiaHAiLCJhIjoiY2l6OWRwM2JlMDAxZTJ3b2ZwejAzdzhpdSJ9.nc4cEdRwhErEg2wuUkABbw';
var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v9',
  center: [-1.41, 6.32],
  zoom: 5
});

map.on('load', function () {
    map.addLayer({
        'id': 'maine',
        'type': 'fill',
        'layout': {},
        'paint': {
            'fill-color': {
              property: 'name',
              type: 'categorical',
                stops: [
                    ['Albania', '#F2F12D'],
                    ['Algeria', '#7A4900'],
                    ['Australia', '#63FFAC'],
                    ["South Africa", "#4FC601"],
                    ["South Korea", "#3B5DFF"],
                ]
            },
            'fill-opacity': 0.8
        },
        'source': {
            'type': 'vector',
            'url': 'mapbox://saurabhp.countries_tileset'
        },
       "source-layer": "countries",
    });
});
<html>

<head>
  <meta charset='utf-8' />
  <title></title>
  <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
  <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.js'></script>
  <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css' rel='stylesheet' />
  <style>
    body {
      margin: 0;
      padding: 0;
    }
    
    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }
  </style>
</head>

<body>

  <div id='map'></div>

</body>

</html>

Upvotes: 4

Related Questions