I want to keep the map center coordinates into some limits. For this I call the setCenter method inside my "center" related callback function:
map.addObserver("center", function (obj, key, newValue, oldValue) {
var limits = {minLat: 47.4136, minLon: 5.9845, maxLat: 54.8073, maxLon: 14.3671};
if (newValue.latitude < limits.minLat || newValue.longitude < limits.minLon ||
newValue.latitude > limits.maxLat || newValue.longitude > limits.maxLon) {
var newLatLon = {latitude: Math.max(Math.min(newValue.latitude, limits.maxLat), limits.minLat),
longitude: Math.max(Math.min(newValue.longitude, limits.maxLon), limits.minLon)};
map.setCenter(nokia.maps.geo.Coordinate.fromObject(newLatLon));
console.log(newValue);
console.log(map.center);
}
});
If I drag the map outside the limits, I see in the console the map.center being correctly adjusted, but the newValue coordinates keep being outisde the limits.
Did I misunderstand the API ?
Adding an observer to a property and then altering that property within the observer function is not guaranteed to work for all properties. My understanding is that re-setting the center is not supported in order to avoid infinite loops. You would be better off using the event framework rather than observers in this case.
The code below restricts the centre of the map to remain within a rectangle centred on Germany. If you drag the map it will stop dead, if you flick the map it will bounce back. You will need to obtain your own free app id and token to get it to work.
I have added event listeners to five events here, dragend, drag, mapviewchange, mapviewchangeend and mapviewchangestart – depending upon the effect you require, you may not need them all. The line
evt.cancel();stops the event from being processed.