Search code examples
javascriptopenlayersopenlayers-3

latitude and longitude of current position in openlayer


I am trying to get the current location latitude and longitude values. is there any method to get lat and long values? I am trying to put maker by getting latitude and longitude value of current position.


Solution

  • Not sure exactly what you're looking for but here are a couple of ways to get lat long based on mouse click or location:

    Mouse Click Lat and Lon:

    map.on('click', function(evt){
        console.info(evt.pixel);
        console.info(map.getPixelFromCoordinate(evt.coordinate));
        console.info(ol.proj.toLonLat(evt.coordinate));
        var coords = ol.proj.toLonLat(evt.coordinate);
        var lat = coords[1];
        var lon = coords[0];
        var locTxt = "Latitude: " + lat + " Longitude: " + lon;
        // coords is a div in HTML below the map to display
        document.getElementById('coords').innerHTML = locTxt;
    });
    

    Mouse move/location lat and long:

    map.on('pointermove', function(evt) {
        //Same code as in click event
    });
    

    Not exactly sure what "getting latitude and longitude value of current position." means in your post