Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot place marker at the right coordinates using openlayers 3

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.

like image 967
Amir Avatar asked Jan 11 '15 18:01

Amir


People also ask

How to create a map using OpenLayers JavaScript?

Include the OpenLayers JavaScript library at the end of the <body> section of your HTML page Put a <div id="map"> element where you want your map to be Now you can add a <script> section at the end of the <body> section (after the <script> that loads OpenLayers JavaScript library).

How to add markers to an OpenStreetMaps map?

OpenLayers is an open source Javascript library, which can be used to embed OpenStreetMaps data on a web page. You can check out their quick-start guide, which shows you how to embed a basic slippy map. However, to a beginner it may not be obvious how to add markers to this map. To do so, you need to add a Vector Layer containing the marker point.

What version of the OpenLayers library does this tutorial use?

This tutorial is based on OpenLayers Quick Start Guide and the OpenLayers Popup Example and uses version 5.3.0 of the library. I suggest you check if there is a more up-to-date version before proceeding.

How do I add OpenLayers to an HTML page?

Include the OpenLayers stylesheet in the <head> section of your HTML page Include the OpenLayers JavaScript library at the end of the <body> section of your HTML page


1 Answers

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')
like image 135
erilem Avatar answered Oct 10 '22 20:10

erilem