v. josh
v. josh

Reputation: 119

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.

Upvotes: 4

Views: 12280

Answers (2)

Hasan A Yousef
Hasan A Yousef

Reputation: 24908

You can use either:

  1. var lonlat = ol.proj.toLonLat(evt.coordinate);

  2. Or var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');

And get it as: alert("latitude : " + lonlat[1] + ", longitude : " + lonlat[0]);

Within: map.on('click', function (evt) { }

Upvotes: 3

GoinOff
GoinOff

Reputation: 1802

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

Upvotes: 12

Related Questions