1

adding markers works fine using OpenLayers 2 but now I need to add markers using OpenLayers 4, how can I do this? my code as follows:

var markers = <?php echo json_encode($data)?>;

    var points = new OpenLayers.Layer.Markers( "Markers" );


    for (var i = 0; i < markers.length; i++) { 

    var lon = markers[i][0];
    var lat = markers[i][1];

        var lonLat = new OpenLayers.LonLat(lon,lat)
        .transform(
        new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
        map.getProjectionObject() // to Spherical Mercator Projection

        );

    points.addMarker(new OpenLayers.Marker(lonLat));

    };   

    map.addLayer(points);

    var poiBounds = points.getExtent();
    var lonLat = poiBounds.getCenterLonLat()
    map.setCenter (lonLat, 8)
  • Check this answer, it shows how can use Marker (Feature in OpenLayers 4) – Moh Mar 14 '18 at 20:18
0
var Markers
[
    {lat: 41.28247976112171, lng: 28.000645778308126},
    {lat: 41.28247976112171, lng: 28.000645778308126}
];

var myMap = new ol.Map({
    target: $element,
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        })
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([41.1878, 28.00158]),
        zoom: 6
    })
});

var features = [];


for (var i = 0; i < Markers.length; i++) {
    var item = Markers[i];
    var longitude = item.lng;
    var latitude = item.lat;

    var iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(ol.proj.transform([longitude, latitude], 'EPSG:4326', 'EPSG:3857'))
    });

    var iconStyle = new ol.style.Style({
        image: new ol.style.Icon(({
            anchor: [0.5, 1],
            src: "http://cdn.mapmarker.io/api/v1/pin?text=P&size=50&hoffset=1"
        }))
    });

    iconFeature.setStyle(iconStyle);
    features.push(iconFeature);

}

var vectorSource = new ol.source.Vector({
    features: features
});

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.