Adapting coordinates order

by Génesis García Morilla

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.js"></script>
<p>Coordinates</p>
<div id="map"></div>

JavaScript

// Imagine you cannot change this function
function show_latlon(lat, lon) {
  document.querySelector('p').textContent = `lat ${lat}, lon ${lon}`
}

let map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  target: 'map',
  controls: [],
  view: new ol.View({
    center: ol.proj.transform([-4, 36], 'EPSG:4326', 'EPSG:3857'),
    zoom: 8
  })
})


// The lon,lat order should be used, because the x-axis relates to longitude and y-axis to latitude and the x,y order is usually prefered, however you can adapt it easily using reverse and destructuring
show_latlon(...ol.proj.toLonLat(map.getView().getCenter()).reverse())