Search code examples
openlayers-5

Open Layers 5.3.0 project, problem with Point customization


I'm learning openstreetmaps and openlayers. I started with application approach (Parcel + openlayers). Most of examples you find here, that could possibly help me are used with older code, which as I understand does not support all features such as Clusters and other stuff. I tried them and was not able to make it work with new environment (of cause it was not just copy-past). My question is relatively simple, I want to customize Features with [Points][1], docs say I can set their style by [setStyle][2] they also have example where it actually works. I used that example to start but whatever style I describe in there I see no new point on a map, and there are none any errors in Parsel or in browser console. If I do not use setStyle I see my point on a map. I tried different ways to set a style but none of them actually worked for me.

I do it like that, first I set style:

var iconStyle = new Style({ fill: 'red' }); After that I add point to features array like that

features.push( new Feature({ geometry: new Point(coordinates), address: 'Адрес точки 2', ordererName: 'Имя человека 2', }) ); and afterwards I set a style for a point:

features[1].setStyle(iconStyle);

and put all of that into map:

var source = new VectorSource({
        features: features
    });

    var vectorLayer = new VectorLayer({
        source: source
    });

    var raster = new TileLayer({
        source: new OSM()
    });

    //EPSG:3857 - web
    //EPSG:4326 - GPS
    var map = new Map({
        layers: [
            raster, 
            //source,
            //clusters, 
            vectorLayer
        ],
        target: 'map',
        view: new View({
            center: transform(map_center, 'EPSG:4326', 'EPSG:3857'),
            zoom: 13
        })
    });

So my question is how to set a style for a point and actually see on a map? If you also capable to suggest how to add such a custom Point on click on a map after you created a map with layers and points that is highly appreciated. Thanks in advance.


Solution

  • Your style setup isn't complete, to display a point your need to style it as an image, for example a red filled circle

      var iconStyle = new Style({
        image: new CircleStyle({
          radius: 10,
          fill: new Fill({
            color: 'red'
          })
        })
      });
    

    If adding a feature after creating the map it might look like this:

    map.on('click', function(event) {
      var feature = new Feature({
        geometry: new Point(event.coordinate)
        ...
        ...
      });
      feature.setStyle(...);
      source.addFeature(feature);
    });