6

My code is showing markers from GeoJSON, when I'm haved zoomed into zoom-level 10,it load the GeoJSON-file, but how do I avoid to reput out the same markers? Is there a way to check if there already exist a marker on a specific place? The code

map.events.register("zoomend", null, function(){

      if(map.zoom == 10)
      {
        var bounds = map.getExtent();
        console.log(bounds);
        var ne = new OpenLayers.LonLat(bounds.right,bounds.top).transform(map.getProjectionObject(),wgs84);
        var sw = new OpenLayers.LonLat(bounds.left,bounds.bottom).transform(map.getProjectionObject(),wgs84);
        var vectorLayer = new OpenLayers.Layer.Vector();
        map.addLayer(vectorLayer);
        $.getJSON('ajax.php?a=markers&type=json&sw=('+sw.lon+','+sw.lat+')&ne=('+ne.lon+','+ne.lat+')',function(data){
        //$.getJSON('test.json',function(data){
            var geojson_format = new OpenLayers.Format.GeoJSON({
                'externalProjection': wgs84,
                'internalProjection': baseProjection
                });
            vectorLayer.addFeatures(geojson_format.read(data));
        });
        }
    });
Max Allan
  • 640
  • 5
  • 18

2 Answers2

4

Why not use the BBOX Strategy [1] ?

That will do what you need, and will for sure be more performant (it will delete existing features and reload new ones on zoomend). Comparing features to add new will need a lot of comparison, and you can end with too much features on your map.

Check out the js source of the example.

HTH,

1 - http://openlayers.org/dev/examples/strategy-bbox.html

EDIT: if you want to change less code, a call to vectorLayer.removeAllFeatures() before adding will solve your problem… Do you really need to keep features out of bound?

tonio
  • 2,376
  • 1
  • 22
  • 28
  • +1 on BBOX Strategy, but how about the zoom level constraint? Is that available in a Strategy? – Niklas Wulff Oct 25 '11 at 15:10
  • Zoom level constraint is not available by default. You can override this class (`OpenLayers.Strategy.BBOX`) to do it. Removing all features (my second solution) won’t cost more than comparing every feature to know if they had to be add. – tonio Oct 27 '11 at 06:50
  • link is down, example for current openlayers version: https://openlayers.org/en/latest/examples/vector-wfs.html – rbs Sep 03 '20 at 11:46
0

First you would need to get the layer off the map using something like map.getLayersByName. Then you can iterate over layer.features to look for the feature you are adding.

If you can modify the backend to use BBOX, then the BBOX strategy with zoom level and projection settings would take care of a lot for you.

ubiquitousthey
  • 467
  • 3
  • 9