Cannot place marker at the right coordinates using openlayers 3
Asked Answered
Y

1

7

I am working on openlayers 3 and want to implement a search functionality, which gets a name of the place and positions a marker on the map. I am able to get the coordinates but when I want to add it's marker on the map, I am always getting different locations for it. The marker of the input place is not being placed on actual coordinates of the map.

Here is the code on which I have been working:

function addmarker(lat, long, pointerimgsrc){

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


    var iconStyle = new ol.style.Style({
        image: new ol.style.Icon(({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 0.75,
        //src: 'data/icon.png'
        src: pointerimgsrc
        }))
    });

    iconFeature.setStyle(iconStyle);

    vectorSource = new ol.source.Vector({
        features: [iconFeature]
    });

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

    map.addLayer(vectorLayer);

}// END addmarkerr()

I hope I have clearly explained my problem, looking forward for a solution. Thank you very much in advance for your time and support.

Yellowbird answered 11/1, 2015 at 18:31 Comment(0)
R
8

The EPSG:4326 coordinate order lon, lat not lat, lon. So you should change the line that does the EPSG:4326 to EPSG:3857 transformation.

ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857')
Rotherham answered 11/1, 2015 at 18:38 Comment(3)
No still same problem, I am entering Munich (actual Lat/Long are: 48.1372719, 11.5754815) but it places marker at Lat/Long: 11.557617187499996,-41.60722821271713Yellowbird
But it works, if I write hard coded values. As below: ol.proj.transform([11.5754815, 48.1372719], 'EPSG:4326', 'EPSG:3857')Yellowbird
Maybe your lon, lat values are strings. Convert them to numbers, using +lon and +lat, before passing them to transform.Rotherham

© 2022 - 2024 — McMap. All rights reserved.