[GIS] OpenLayers 6.0.1 set custom center after load map

javascriptopenlayers

I am using OpenLayers 6.0.1 web map. I have plot a new marker on map with custom image and want to put the map to be centered newly plotted marker position.

Best Answer

Since you have already added the marker on the map this means you already have the coordinates of that Marker. Note that a marker is just a Point feature with a specific Icon style which needs a coordinate set that fits your projection. In order to center the map on the marker you have just created, you can do the following:

I guess you are using an EPSG:3857 projection on your map and that you have coordinates in EPSG:4326 which is very usual.

     let marker = new Feature({
        geometry: new Point(fromLonLat([38.71, 88.66]))
     });
     marker.setStyle(new Style({
            image: Icon({
                  anchor: [0, 0],
                  src: 'yourimage.png'
               })
           }));

     let vectorLayer = new VectorLayer({
          source: new VectorSource({
             features: [marker]
       })
     });
    map.addLayer(vectorLayer);
    map.getView().animate({zoom: 5, center: fromLonLat([38.71, 98.66])});

Of course, there is plenty of output ommited in this example, but I'm posting it just to give you an idea of how you can animate your viewport to a specific location. Most of the mentioned code and imports should already exist in your project so you just need to grab the coordinates and animate the map.