please i’m working on openlayers and i can’t use attribute value as label for my GeoJSON vector file.
I want to show the text from properties “osmid” in my GeoJSON file as label.
here is my code
JavaScript
x
56
56
1
var map = new ol.Map ({//carte
2
target: 'map',
3
layers: [mapquest, bingmaps, stamen],
4
controls: ol.control.defaults().extend([
5
new ol.control.ScaleLine(),//affichage de l'échelle
6
new ol.control.ZoomSlider(),//affichage de la barre de zoom
7
new ol.control.FullScreen() //affichage en plein écran
8
]),
9
renderer: 'canvas',
10
view: view
11
});
12
13
// ajouter un stle pour la couche batiment
14
15
var styleBatiment = new ol.style.Fill({
16
color : [187, 165, 41, 0.52] // couleur en rgba
17
});
18
19
20
var strokeBatiment = new ol.style.Stroke({
21
color : [121, 38, 255, 0.97], // couleur en rgba
22
width : 1,
23
});
24
25
26
var textBatiment = new ol.style.Text({
27
font: '12px Calibri,sans-serif',
28
fill: new ol.style.Fill({
29
color: '#000'
30
}),
31
stroke: new ol.style.Stroke({
32
color: '#fff',
33
width: 3
34
}),
35
text: '1'
36
});
37
38
39
var batimentstyle = new ol.style.Style({
40
fill : styleBatiment,
41
stroke : strokeBatiment,
42
text : textBatiment
43
});
44
// ajouter une couche vecteur : batiments
45
const building = new ol.layer.VectorImage({
46
source : new ol.source.Vector({
47
url:'./data/building.geojson',
48
format: new ol.format.GeoJSON()
49
}),
50
visible : true,
51
title : 'Batiments',
52
style : batimentstyle
53
});
54
55
map.addLayer(building);`
56
My Geojson file looks like this :
JavaScript
1
8
1
{
2
"type": "FeatureCollection",
3
"name": "building",
4
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
5
"features": [
6
{ "type": "Feature", "properties": { "osm_id": 86944868, "name": null, "type": "semidetached_hou" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 2.0568994, 48.93285799998651 ], [ 2.0569538, 48.932929999986484 ], [ 2.0569832, 48.932920099986482 ], [ 2.0569749, 48.932909099986489 ], [ 2.0570069, 48.932898299986483 ], [ 2.0569589, 48.932837599986492 ], [ 2.0568994, 48.93285799998651 ] ] ] ] } },
7
{ "type": "Feature", "properties": { "osm_id": 86944890, "name": null, "type": "detached" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 2.0577999, 48.933744699986484 ], [ 2.0578716, 48.933812699986483 ], [ 2.0579672, 48.933769099986492 ], [ 2.0578954, 48.933701199986487 ], [ 2.0577999, 48.933744699986484 ] ] ] ] } },
8
Advertisement
Answer
You need to use a style function where you set the text in the style to the value of the feature property
JavaScript
1
5
1
style : function(feature) {
2
batimentstyle.getText().setText(feature.get('osm_id'));
3
return batimentstyle;
4
}
5