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.


You can put a feature on map and fit him

 var vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector()
  var marker = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([-44,-2]))

  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
    view: new ol.View({
      center: ol.proj.fromLonLat([37.41, 8.82]),
      zoom: 4
  var extent = vectorLayer.getSource().getExtent();
|improve this answer|||||

I have got answer from https://stackoverflow.com/questions/51207211/openlayer-load-map-with-initial-marker

<h2>Location Map</h2>
  <div id="mapLat"></div>
    <div id="mapLon"></div>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      var mapId = "map";
    var lat,lon;
function createMap() {
    var queryString = window.location.search;
    queryString = queryString.substring(1);
    var queries = queryString.split("$");
    var Qstring = [];
        var temp = queries[i].split('=');
    lat = Qstring[0];
    lon = Qstring[1];
    document.getElementById('mapLat').innerHTML = 'Latitude:' + lat;
    document.getElementById('mapLon').innerHTML = 'Longtiude:' + lon;

  var coordinate = [lon, lat];
  var vectorSource = new ol.source.Vector({});
  var vectorLayer = new ol.layer.Vector({
    source: vectorSource
  var view = new ol.View({
    center: ol.proj.fromLonLat(coordinate),
    zoom: 10,
    maxZoom: 19,
    minZoom: 5
  var map = new ol.Map({
    layers: [new ol.layer.Tile({
      source: new ol.source.OSM({
        key: 'myKey',
        crossOrigin: ''
    }), vectorLayer, ],
    target: document.getElementById(mapId),
    controls: ol.control.defaults(),
    view: view
  // create custom marker image with custom text in bottom
  var iconStyle = new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [12, 37],
      anchorXUnits: 'pixels', //'fraction'
      anchorYUnits: 'pixels',
      opacity: 0.8,
      //src: 'https://maps.google.com/mapfiles/ms/micons/blue.png'
      src: 'img/pin/location_pin.gif'

  var marker;
  this.setMarker = function(coordinate) {
    marker = new ol.Feature(
      new ol.geom.Point(ol.proj.fromLonLat(coordinate))
  return this;

var map = createMap();
map.setMarker([lon, lat])
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.