Search code examples
leafletmapsmapboxopenstreetmap

Centering a marker at the center of a div


I have a div that i am using to hold a leaflet map. It currently looks like this

enter image description here

I want the marker to be at the center or near center of the div so that its visible always even the marker is further left and out of view or out of view in any direction.

Currently my code looks like this

var mymap = L.map('mapid').setView([51.505, -0.09], 18);


    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: 50,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
            '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox.streets'
    }).addTo(mymap);

    L.marker([52.573921, -0.250830]).addTo(mymap)
    .bindPopup('A pretty CSS3 popup. <br> Easily customizable.')
    .openPopup();

    mymap.fitBounds([52.573921, -0.250830]);
    mymap.setView([52.573921, -0.250830]);
    mymap.setZoom(18);

I get the error bounds are not valid.

I would like my marker to be at least here

enter image description here


Solution

  • Try this one,

    mymap.panTo(new L.LatLng(52.573921, -0.250830));