问题
I need to have different custom images for each points in the map using mapbox-gl-js, But I don't find a way to give custom icon for each feature in a feature collection
incidentMarkers = {
"type": "FeatureCollection"
"features": [{
"type": "geojson",
"data": {
"type": "Feature",
"properties": {
},
"geometry": {
"type": "Point",
"coordinates": [
longitude
latitude
]
}
}
},
{
"type": "geojson",
"data": {
"type": "Feature",
"properties": {
},
"geometry": {
"type": "Point",
"coordinates": [
longitude
latitude
]
}
}
}]
}
map.addSource('incidentMarkers', {
"type": "geojson"
"data": incidentMarker
})
window.map.addLayer({
"id": 'incidentMarkers',
"type": "symbol",
"source": 'incidentMarkers'
"layout": {
"icon-image": "image-1",
"icon-size": 0.25,
"icon-allow-overlap": true,
"text-allow-overlap": true
}
})
Now I am adding each point as separate layer for having custom image for each icon, But for having clustering with markers I need to have all markers as same layers, Is there any way to add custom images for each layers
pointsData.forEach (data) ->
window.map.loadImage("#{data.category_image_path}", (e, image) ->
window.map.addImage("image-#{data.id}", image)
incidentMarker = {
"type": "Feature",
"properties": {
},
"geometry": {
"type": "Point",
"coordinates": [
data.longitude
data.latitude
]
}
}
map.addSource('incidentMarkers' + data.id, {
"type": "geojson",
"data": incidentMarker
})
window.map.addLayer({
"id": 'incidentMarkers' + data.id,
"type": "symbol",
"source": 'incidentMarkers' + data.id
"layout": {
"icon-image": "image-#{data.id}",
"icon-size": 0.25,
"icon-allow-overlap": true,
"text-allow-overlap": true
}
})
And if I have more than one marker at same latlng only one marker is showing up, Even I set icon-allow-overlap
option to true
回答1:
If you reference which icon should be used in each feature's properties you can use mapbox' data-driven styling capabilities to use a different icon for each feature:
const geojson = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {icon: 'image-1'},
geometry: {/* */}
},
{
type: 'Feature',
properties: {icon: 'image-2'},
geometry: {/* */}
}
]
}
// add source
map.addLayer({
type: 'symbol',
source: 'source-id',
layout: {
'icon-image': ['get', 'icon']
}
})
The ['get', 'icon']
is an expression which "gets" the property "icon" from each feature and uses it as the value for icon-image
.
来源:https://stackoverflow.com/questions/51481471/adding-custom-icons-for-each-feature-in-feature-collection-with-mapbox-gl-js