Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the location center of a map using Leaflet API?

My map (Mapbox) takes up the whole background of the site so the center is in the middle of the site. But the focus of the map for the user is on the right side because I have content overlapping the map on the left side. When leaflet grabs the location, it's from the center of the map, but it would be more convenient if I could set it to grab the location from the center of the right third of the site, so that way the user won't be centering the map on targets bordering content on the left half of the site.

Is there a way I could set the center or location focus of the leaflet API for the map?

Here's how I have it set up currently,

mapOptions: {
        maxZoom: 18,
        zoomControl: false,
        worldCopyJump: true 
},

createMap: function() {
        Map.map =  L.map('map', Map.mapOptions);
        Map.layer = L.mapbox.tileLayer(Map.mapID, {
                unloadInvisibleTiles: true,
        }).addTo(Map.map);              
        Map.map.locate({setView: true});
        Map.map.addControl(L.mapbox.geocoderControl(Map.mapID));
        new L.Control.Zoom({ position: 'topright' }).addTo(Map.map);
},
like image 662
Conor Patrick Avatar asked Jul 20 '13 03:07

Conor Patrick


3 Answers

You can use a combo of panBy() and getSize() to offset the map the width of your overlay.

Here's a snippet that should get you a started:

// Calculate the offset
var offset = map.getSize().x*0.15;
// Then move the map
map.panBy(new L.Point(-offset, 0), {animate: false});

In my example, my overlay is 33% of the width of the map. So I grab the size of the map area, then multiple by 0.15 (this was based on some experimenting to see what the best offset amount was) and use panBy() to offset the map center.

Here's a full example.

like image 169
Brett DeWoody Avatar answered Oct 12 '22 06:10

Brett DeWoody


If you have multiple markers and want to center the map in their bounds and at the same time you have overlapping container, you can use the fitBounds options (paddingTopLeft, paddingBottomRight, padding).

http://leafletjs.com/reference.html#map-paddingtopleft

like image 39
Tihomir Mihaylov Avatar answered Oct 12 '22 06:10

Tihomir Mihaylov


First you will need to know the lat and long of the point on the map you want to center on. Then it is simple, just call Map.map.setView passing in your coordinates and zoom level. Api reference: http://leafletjs.com/reference.html#map-set-methods

If you don't know your coordinates then you can find it by trial and error, just create a marker and add it to the map.

like image 2
Mark Gibbons Avatar answered Oct 12 '22 06:10

Mark Gibbons