简体   繁体   中英

OpenLayers3 add Text over Circle

After searching a lot, I finally managed to find a block of code that allows me to draw a circle on the map.

HTML:

<div id="mapHolder"></div>

CSS:

#mapHolder{
  width: 100%;
  height: 200px;
  background-color: #ccc;
}

JavaScript:

$(document).ready(function(){
  var map = new ol.Map({
          target: 'mapHolder',
          interactions: ol.interaction.defaults({mouseWheelZoom:false}),
          layers: [
            new ol.layer.Tile({
              source: new ol.source.OSM()
            })
          ],
          view: new ol.View({
            center: ol.proj.transform([parseFloat(8.680239), parseFloat(50.114034)], 'EPSG:4326','EPSG:3857'),
        zoom: 13
          })
        });



  var vectorSource = new ol.source.Vector();
  var circleLayer = new ol.layer.Vector({
    source: vectorSource
  });
  map.addLayer(circleLayer);

  var coordinate = ol.proj.transform([parseFloat(8.680239), parseFloat(50.114034)], 'EPSG:4326','EPSG:3857');
  vectorSource.addFeature(new ol.Feature(new ol.geom.Circle(coordinate, 2000)));

});

this is the fiddle: https://jsfiddle.net/79hjbxw9/

1) How can I put a text on the Circle with the title "Approximate Area"; and also be able to define the color and font.

2) also I want to change the color and thickness of Circle border.

You can get that using a style on your vector layer.

Declare your style

     var myStlye = new ol.style.Style ({
      fill: new ol.style.Fill({
         color: 'rgba(255,100,50,0.5)'
       }),
       stroke: new ol.style.Stroke({
         color: 'blue',
         width: 3
       }),
       text: new ol.style.Text({
         textAlign: "Start",
         textBaseline: "Middle",
         font: 'Normal 12px Arial',
         text: 'Approximate Area',
         fill: new ol.style.Fill({
           color: '#ffa500'
         }),
         stroke: new ol.style.Stroke({
           color: '#000000',
           width: 3
         }),
         offsetX: -45,
         offsetY: 0,
         rotation: 0
       })
    });

and then attach it to your layer

 var circleLayer = new ol.layer.Vector({
        style:myStlye,
        source: vectorSource
      });

here is a fiddle to see it in action

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