[GIS] Adjust center of the map based on marker position Openlayers

javascriptopenlayers

I have a map in which a moving marker is placed to represent a vehicle. I am using setCoordinate() method to move the marker.

I need to set the center of the map to the position of the vehicle marker whenever the marker reaches any one of the four boundaries of map. How do I know that the marker is at the boundary in order to set the center of the map and set the center whenever it is at the boundary.

Best Answer

Somehow, I found the answer

//calculate the extent of the map

var extent = map.getView().calculateExtent(map.getSize());
extent = ol.proj.transformExtent(extent, 'EPSG:3857', 'EPSG:4326');

//compare the values with the marker position 

 if((extent[0]>lon || lon>extent[2])||(extent[1]>lat || lat>extent[3])) {
        //set the center to the marker position 
  map.getView().setCenter(ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857'));
}