我对如何在 GeoJSON 文件中添加标签以显示在地图上感到困惑。我已经尝试了许多来自 openlayers.org 的示例,但它们不起作用。
我想在地图顶部和沿线的 GeoJSON 文件中显示属性“名称”中的文本,例如街道名称。现在只显示该行。
这是我的脚本。
<script type="text/javascript">
var style = new ol.style.Style({
text: new ol.style.Text({
font: 'bold 11px "Open Sans", "Arial Unicode MS", "sans-serif"',
placement: 'line',
fill: new ol.style.Fill({
color: 'white'
})
})
});
var format = new ol.format.GeoJSON({
featureProjection:"EPSG:3857"
});
var allbussource = new ol.source.Vector({
features:format.readFeatures(allbus)
});
var allbuslayer = new ol.layer.Vector({
source: allbussource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3
}),
}), function(feature) {
style.getText().setText(feature.get('name'));
return style;
}
});
var allbusdashsource = new ol.source.Vector({
features:format.readFeatures(allbusdash)
});
var allbusdashlayer = new ol.layer.Vector({
source: allbusdashsource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3,
lineDash: [6, 10]
})
})
});
var allbuslayergroup = new ol.layer.Group({
layers: [allbuslayer, allbusdashlayer]
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
url: 'tiles/{z}/{x}/{y}.png',
crossOrigin: null,
})
}), allbuslayergroup
],
view: new ol.View({
center: ol.proj.fromLonLat([100.568, 14.353]),
zoom: 14,
minZoom: 14,
maxZoom: 19,
extent: [11187608.82, 1608083.02, 11203003.55, 1621297.19],
constrainResolution: true
})
});
</script>
这是我的 GeoJSON 文件的示例,我已转换为 .js 并将其包含在 HTML 头中。
var allbus = {
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "osm_id": "21946733", "name": "2400 2435" }, "geometry": { "type": "LineString", "coordinates": [ [ 100.5910608, 14.372016 ], [ 100.5908929, 14.3718848 ], [ 100.5902894, 14.3715546 ], [ 100.5901471, 14.3714576 ], [ 100.5900982, 14.3714101 ], [ 100.5899568, 14.371273 ], [ 100.5898938, 14.3711547 ], [ 100.5898514, 14.3710753 ], [ 100.5897955, 14.3707167 ], [ 100.589761, 14.3704954 ], [ 100.589738, 14.3702688 ], [ 100.5897387, 14.370049 ], [ 100.5898064, 14.3697453 ], [ 100.5899893, 14.3692589 ], [ 100.5901096, 14.3689535 ], [ 100.5903428, 14.3683034 ], [ 100.5904301, 14.3678864 ], [ 100.5904319, 14.3674561 ], [ 100.5904349, 14.3667348 ], [ 100.5904014, 14.3655408 ], [ 100.5903904, 14.3651487 ], [ 100.5903823, 14.3645017 ], [ 100.5905217, 14.3640963 ], [ 100.5909407, 14.3630018 ], [ 100.5913408, 14.3618161 ], [ 100.5913944, 14.3615798 ], [ 100.5913889, 14.3613111 ], [ 100.5913774, 14.3612627 ], [ 100.5913429, 14.3611183 ], [ 100.5911797, 14.3604346 ], [ 100.5908801, 14.3590742 ], [ 100.59081, 14.3587564 ], [ 100.5907702, 14.3585754 ], [ 100.5907349, 14.3580533 ], [ 100.590891, 14.3571796 ], [ 100.5910189, 14.35651 ], [ 100.5911179, 14.3559918 ] ] } },
{ "type": "Feature", "properties": { "osm_id": "23745845", "name": "101 1002*" }, "geometry": { "type": "LineString", "coordinates": [ [ 100.5530414, 14.3614133 ], [ 100.5530547, 14.3613011 ] ] } }
]
};