Add a pattern to a polygon
Use the fill-pattern feature to draw a polygon by employing a repeating image pattern. This technique allows for the creation of visually appealing shapes by using a repeated image as a fill. To implement this, refer to the layer ⇾ fill ⇾ fill-pattern section in the GL Style Specification.
NPM module setup
npm install --save @maptiler/sdk
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
const map = new Map({
container: 'map',
style: MapStyle.STREETS,
center: [0, 0],
zoom: 1
});
map.on('load', async function () {
// Add GeoJSON data
map.addSource('source', {
'type': 'geojson',
'data': {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'Polygon',
'coordinates': [
[
[-30, -25],
[-30, 35],
[30, 35],
[30, -25],
[-30, -25]
]
]
}
}
});
// Load an image to use as the pattern
const image = await map.loadImage(
'https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/64px-Cat_silhouette.svg.png');
// Declare the image
map.addImage('pattern', image.data);
// Use it
map.addLayer({
'id': 'pattern-layer',
'type': 'fill',
'source': 'source',
'paint': {
'fill-pattern': 'pattern'
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Add a pattern to a polygon | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map"></div>
<script type="module" src="./main.js"></script>
</body>
</html>
body {margin: 0; padding: 0;}
#map {position: absolute; top: 0; bottom: 0; width: 100%;}