Skip to content

Problems with map.locate() and bounding box #962

@cahlf

Description

@cahlf

I'm not sure if this is a bug or if my code is just crap, but in my example I'm taking most of the code from the tutorial, so I think there might be an issue with leaflet itself.

What I want to achieve: I want to locate the user and then load markers dynamically as the user pans according to the actual bounding box of the map. The problem arises when I want to get the bounding box after having located the user. So here is my code, mostly taken from the 'mobile'-tutorial:

var map = L.map('map');

L.tileLayer('http://{s}.tile.cloudmade.com/[API-Key]/997/256/{z}/{x}/{y}.png', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>',
    maxZoom: 18
}).addTo(map);

map.locate({setView: true, maxZoom: 16});

function onLocationFound(e) {
    L.marker(e.latlng).addTo(map).bindPopup("You are here.").openPopup();
}

map.on('locationfound', onLocationFound);

map.on('moveend', function() {
    console.log("map was panned!");
    console.log("zoom: " + map.getZoom());    // prints out zoom level
    console.log("center: " + map.getCenter());    // prints out map center
    console.log(map.getBounds());    // throws error
});

So there is really nothing special to it. But since I want to load new markers every time the user pans the map, I have to use the 'moveend'-event of the map and get the current bounding box. Here comes the tricky part: when the user is located, the 'moveend'-event seems to be fired. But although I can access the actual zoom level (map.getZoom()) and map center (map.getCenter()), I cannot acces the bounding box. The console error says: "Uncaught Error: Set map center and zoom first." Well, as said before, I can access these two properties, so they must have been set. But I cannot access the bounding box, although the user has been located successfully.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions