简体   繁体   中英

OpenLayers.Map setCenter causes misplaced OpenLayers.Vector elements

I have an OpenLayers.Map ( map ) that has an OpenLayers.Layer.Vector ( map.addLayer(vectorLayer) ), and I use the vectorLayer.addFeatures to add a series of OpenLayers.Feature.Vector objects to vectorLayer .

The process is a bit like this:

var map, vectorLayer;
function initialize()
{
    map = new OpenLayers.Map(/*...*/);
    vectorLayer = new OpenLayers.Layer.Vector(/*...*/);
    map.addLayer(vectorLayer);
}

function populate()
{
    arrayOfStuff.foreach(function(thing, i) // data from an AJAX call
    {
        var feature = new OpenLayers.Feature.Vector(/*...based on thing*/));
        feature.vector_type = 'marker';
        vectorLayer.addFeature(feature);
    }
}

When I then use map.setCenter to move the map, the vectors get misplaced: some shift with the map, some do not, some do both (causing duplicates), and so on. Manually panning the map even slightly immediately fixes these misplaced vectors. Unfortunately, simply calling map.pan does not (consistently) have the same effect, and vectorLayer.refresh() doesn't seem to have any effect at all.

Why is this happening and how do I get it to stop? Failing that, what can I do to force the map to fix itself (as it does when I move the map).

The code snippets you provided are not sufficient to diagnose the problems you're having.

It's a shot in the dark, but a common cause of misplaced markers is mixing map layers which are using different coordinate systems. OpenLayers uses a flat coordinate system based on latitude and longitude (EPSG:4326) whereas Google Maps, Microsoft Virtual Earth, Yahoo Maps, and other commercial API providers use a spherical coordinate system (EPSG:3857) also called Spherical Mercator Projection. See these related SO questions here and here .

Fortunately OpenLayers has APIs that let you transform your coordinates between various projections so that all of your layers play nicely together. The OpenLayers documentation dedicated a whole chapter to 'Spherical Mercator Projection' which contains some examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM