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
var map = new ol.Map ({//carte target: 'map', layers: [mapquest, bingmaps, stamen], controls: ol.control.defaults().extend([ new ol.control.ScaleLine(),//affichage de l'échelle new ol.control.ZoomSlider(),//affichage de la barre de zoom new ol.control.FullScreen() //affichage en plein écran ]), renderer: 'canvas', view: view }); // ajouter un stle pour la couche batiment var styleBatiment = new ol.style.Fill({ color : [187, 165, 41, 0.52] // couleur en rgba }); var strokeBatiment = new ol.style.Stroke({ color : [121, 38, 255, 0.97], // couleur en rgba width : 1, }); var textBatiment = new ol.style.Text({ font: '12px Calibri,sans-serif', fill: new ol.style.Fill({ color: '#000' }), stroke: new ol.style.Stroke({ color: '#fff', width: 3 }), text: '1' }); var batimentstyle = new ol.style.Style({ fill : styleBatiment, stroke : strokeBatiment, text : textBatiment }); // ajouter une couche vecteur : batiments const building = new ol.layer.VectorImage({ source : new ol.source.Vector({ url:'./data/building.geojson', format: new ol.format.GeoJSON() }), visible : true, title : 'Batiments', style : batimentstyle }); map.addLayer(building);`
My Geojson file looks like this :
{ "type": "FeatureCollection", "name": "building", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "features": [ { "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 ] ] ] ] } }, { "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 ] ] ] ] } },
Advertisement
Answer
You need to use a style function where you set the text in the style to the value of the feature property
style : function(feature) { batimentstyle.getText().setText(feature.get('osm_id')); return batimentstyle; }