OpenLayers - Uncaught TypeError: Cannot read prope

2019-08-04 07:58发布

问题:

I'm trying to display markers on vector layer using following code,

var map;
function init(){
   map = new OpenLayers.Map('map_element',{});
   var wms = new OpenLayers.Layer.WMS(
       'OpenLayers WMS',
       'http://vmap0.tiles.osgeo.org/wms/vmap0',
               {layers: 'basic'},
       {}
       );
       map.addLayer(wms);
       if (!map.getCenter())
       {
           map.zoomToMaxExtent();
       }
       var feature_data = {
           "type": "FeatureCollection",
           "features": [
               {"type": "Feature", "properties": {},
                   "geometry": {"type": "Point", "coordinates": [-81, 42]}},
               {"type": "Feature", "properties": {},
                   "geometry": {"type": "Point", "coordinates": [-82, 43]}},
               {"type": "Feature", "properties": {},
                   "geometry": {"type": "Point", "coordinates": [-80, 41]}},
               {"type": "Feature", "properties": {},
                   "geometry": {"type": "Point", "coordinates": [19, -24]}},
               {"type": "Feature", "properties": {},
                   "geometry": {"type": "Point", "coordinates": [4, 42]}},
               {"type": "Feature", "properties": {},
                   "geometry": {"type": "Point", "coordinates": [32, 35]}},
           ]
       }
       var format_geojson = new OpenLayers.Format.GeoJSON({});
       var vector_strategies = [new OpenLayers.Strategy.Cluster({distance: 42})];
       vector_layer = new OpenLayers.Layer.Vector('More Advanced VectorLayer', {strategies: vector_strategies});
       var fLayer = vector_layer.addFeatures(format_geojson.read(feature_data));
       map.addLayer(fLayer);
   }

I'm able to see map on respective div, but missing markers. In console I found following error message,

Uncaught TypeError: Cannot read property 'div' of undefined

Where I did mistake ? I'm new to OpenLayers, I apologies if I made any silly mistake and I don't want to use cluster strategy, is it mandatory to use this, if not how can I skip cluster strategy. ?

回答1:

addFeatures modifies the layer itself, does not return a new layer apparently

This works:

vector_layer.addFeatures(format_geojson.read(feature_data));
map.addLayer(vector_layer);

in place of

var fLayer = vector_layer.addFeatures(format_geojson.read(feature_data));
map.addLayer(fLayer);

Example: http://jsfiddle.net/G8k2H/



标签: openlayers