Search code examples
reactjsopenlayersopenlayers-3

How to get the coordinates from the OpenLayers Map in ReactJS?


Some three locations are connected in a triangle shape in Open Layer Map. I am trying to get all the three locations (latitude and longitude) with the help of OpenLayers and React JS. But unfortunately, I am able to get the Latitude and Longitude of visible view and not the marked layers.

When I used the below code, it is not fetching the expected long and lat and it is resulting the visible map long and lat.

var glbox = map.getView().calculateExtent(map.getSize()); 
var box = proj.transformExtent(glbox,'EPSG:3857','EPSG:4326'); 
console.log("Latitude and longitude :",box);

So, I have tried with the below options as well and it is not resulting the expected long and lat.

console.log("Long and Lat :",map.getFeaturesAtPixel());  //--> null
console.log("Long and Lat :",map.getLayers());  
console.log("Long and Lat :",map.getFeaturesAtPixel());  //--> null

How can I get the latitude and longitude of the all three locations that are shown in the image?

Map with Triangle Shape


Solution

  • It will never work the way you are currently doing things. What do I mean? I mean that going through map.getFeaturesAtPixel is one way that can work but you didn't read the API docs. You need at least to provide pixel (x, y screen coordinates) to the function.

    You can get pixel using the following

    map.on('click', evt => {
      console.log(evt.pixel);
    })
    

    I've done a simple demo to illustrate. Go to http://openlayers.org/en/latest/examples/gpx.html and paste the following code in the browser debugger console. Click on point(s) and observe the behavior in the console.

    map.on('click', evt => {
      var features = map.getFeaturesAtPixel(evt.pixel);
      if (features) {
        // Get name (but it depends of your data attributes)
        console.log(features
          .filter(feature => feature.getGeometry().getType() == 'Point')
          .map(feature => feature.get('name')));
        // Get the features, filter to only get Point, then get geometry
        // and coordinates, change projection to lon lat
        console.log(features
          .filter(feature => feature.getGeometry().getType() == 'Point')
          .map(feature => `Longitude, latitude: ${ol.proj.toLonLat(feature.getGeometry().getCoordinates()).join(', ')}`));
      }
    })
    

    Edit due to feedback.

    To get the points from a LineString, just do

    var featuresLinestringPointsCoordinates = vector.getSource().getFeatures()
      .map(feature => {
        return feature
          .getGeometry()
          .clone()
          .transform('EPSG:3857','EPSG:4326')
         .getCoordinates();
    });
    console.log(featuresLinestringPointsCoordinates);
    // More readable and we only get the first linestring
    console.table(featuresLinestringPointsCoordinates[0])
    

    Tested on the official snap demo after drawing a LineString