Example assigning a custom color to an icon
Example assigning a custom color to an icon. The features in this examples are all using the same image with the different colors coming from the javascript file. Note that icon files need to obey the same origin policy or send proper CORS headers for this to work. When relying on CORS headers, the ol/style/Icon
must be configured with crossOrigin: 'anonymous'
.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Icon Colors</title>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="index.js"></script>
</body>
</html>
import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import View from 'ol/View';
import Point from 'ol/geom/Point';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {fromLonLat} from 'ol/proj';
import TileJSON from 'ol/source/TileJSON';
import VectorSource from 'ol/source/Vector';
import {Icon, Style} from 'ol/style';
var rome = new Feature({
geometry: new Point(fromLonLat([12.5, 41.9]))
});
var london = new Feature({
geometry: new Point(fromLonLat([-0.12755, 51.507222]))
});
var madrid = new Feature({
geometry: new Point(fromLonLat([-3.683333, 40.4]))
});
rome.setStyle(new Style({
image: new Icon({
color: '#8959A8',
crossOrigin: 'anonymous',
src: 'data/square.svg'
})
}));
london.setStyle(new Style({
image: new Icon({
color: '#4271AE',
crossOrigin: 'anonymous',
src: 'data/dot.png'
})
}));
madrid.setStyle(new Style({
image: new Icon({
color: [113, 140, 0],
crossOrigin: 'anonymous',
src: 'data/dot.png'
})
}));
var vectorSource = new VectorSource({
features: [rome, london, madrid]
});
var vectorLayer = new VectorLayer({
source: vectorSource
});
var rasterLayer = new TileLayer({
source: new TileJSON({
url: 'https://a.tiles.mapbox.com/v3/aj.1x1-degrees.json',
crossOrigin: ''
})
});
var map = new Map({
layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'),
view: new View({
center: fromLonLat([2.896372, 44.60240]),
zoom: 3
})
});
{
"name": "icon-color",
"dependencies": {
"ol": "6.1.1"
},
"devDependencies": {
"parcel": "1.11.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --experimental-scope-hoisting --public-url . index.html"
}
}