简体   繁体   中英

How to add text to LineString in OpenLayers?

We use OpenLayers 4.6.5.

The code looks as following:

const line = new Feature({
  geometry: new LineString(points)
})
line.setStyle(
  new Style({
    fill: new Fill({ color: 'black' }),
    stroke: new Stroke({ color: 'black', width: 2 }),
    text: new Text({
      text: '1',
      font: '18px "Roboto", Helvetica Neue, Helvetica, Arial, sans-serif',
      fill: new Fill({ color: 'black' }),
      stroke: new Stroke({ color: 'black', width: 2 })
    })
  })
)

this.vectorLayer.getSource().addFeature(line)

But, I'm getting the error:

Uncaught TypeError: textStyle.getFill is not a function
at _ol_render_canvas_TextReplay_.setTextStyle (textreplay.js?3128:470)
at _ol_renderer_vector_.renderLineStringGeometry_ (vector.js?98c2:183)
at Object._ol_renderer_vector_.renderFeature_ (vector.js?98c2:121)
at Object._ol_renderer_vector_.renderFeature (vector.js?98c2:94)
at _ol_renderer_canvas_VectorLayer_.renderFeature (vectorlayer.js?c03d:429)
at _ol_renderer_canvas_VectorLayer_.eval (vectorlayer.js?c03d:378)
at _ol_renderer_canvas_VectorLayer_.prepareFrame (vectorlayer.js?c03d:395)
at _ol_renderer_canvas_Map_.renderFrame (map.js?1103:183)
at _ol_Map_._ol_PluggableMap_.renderFrame_ (pluggablemap.js?0fa0:1180)
at _ol_Map_.eval (pluggablemap.js?0fa0:87)      

Without text settings, there is no error, just a line.

To work correctly Text needs to have been imported correctly, for example

import {Text} from 'ol/style';

or

import Text from 'ol/style/Text';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM