Search code examples
openlayerspan

OpenLayers: How to only pan map enough so feature is in view


When I put a feature on the map, I want to make sure it's in view.

I am currently using panTo() and the feature's centroid as a way to do this. However, this moves the map to be centered on the feature every time. This can make a very jittery map when features are nearby.

What I'd like is something where the map pans just enough to ensure the popup is in view (e.g. at the edge of the map vs. centered). And, if the feature is already on the map...don't pan.

Here is the code that generates the feature (NOTE: This is in a high-frequency loop that rapidly adds/remove features to create an animation):

var feature = new OpenLayers.Feature.Vector(
                    new OpenLayers.Geometry.Collection(geometries), {
                        "color" : color,
                        "strokeOpacity" : settings.lineOpacity,
                        "fillOpacity" : settings.fillOpacity,
                        "label" : ""
                    });

layer.addFeatures([ feature ]);
setCenter(lon, lat);

And, here is the code for setCenter:

setCenter : function(lon, lat) {
    chMap.map.panTo(
        new OpenLayers.LonLat(
            lon, lat
        ).transform(chMap.EPSG4326, chMap.EPSG900913)
    );
}

Solution

  • In case it helps others, here's the final code I ended up with to allow "following" of features on a map:

    if (!map.getExtent().containsBounds(feature.geometry.getBounds(), false, true)) {
        chMap.setCenter(lon, lat);
    }
    

    The use of containsBounds() ensures that the entire feature is visible. The onScreen() method that was originally tried would not move the map if even 1 pixel of the feature was on the screen.

    Hat tip to John Barça for his help