Gandalf
Gandalf

Reputation: 13683

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

Upvotes: 0

Views: 235

Answers (2)

peeebeee
peeebeee

Reputation: 2618

The reason for the error is that fitBounds() takes a L.latLngBounds as its argument, and you're passing it a single L.point.

You need a different way of panning the map to your desired centre location - maybe map.panTo() or map.flyTo() if you want pan/zoom animation.

Upvotes: 1

Viraj Amarasinghe
Viraj Amarasinghe

Reputation: 941

Try this one,

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

Upvotes: 2

Related Questions