0

I'm using openlayers v3.17.1 along with OSM Server as tile server.

I got errors when I called vectorSource.addFeatures with the parameter Array containing more than about 10 features.

Error Info: TypeError: Cannot read property '0' of null with the following code:

zoom_level = 10;
var FEATURE_URI = {
  1: '/marker/blue.png',
  2: '/marker/yellow.png',
  3: '/marker/red.png',
  4: '/marker/blue.png',
}

// feature alert
function Alert(f_lon, f_lat, o_alert) {
  var feature = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([f_lon, f_lat])),
    name: o_alert.name,
    msg: o_alert.msg,
  });

  feature.setStyle(new ol.style.Style({
    image: new ol.style.Icon({
      opacity: .6,
      src: FEATURE_URI[o_alert.level],
      scale: 1 / 16,    // 32px
    })
  }));

  return feature;
}

var vectorSource = new ol.source.Vector({
  features: []
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource
});

var map = new ol.Map({
  target: document.getElementById('map'),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM({
        url: host + '/osm_tiles/{z}/{x}/{y}.png',
        crossOrigin: null,
      })
    }),
    vectorLayer
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([lon, lat]),
    zoom: zoom_level
  })
});

var element = $('#popup')[0];
var popup = new ol.Overlay({
  element: element,
  positioning: 'bottom-center',
  stopEvent: false,
  offset: [0, -30]
})

map.addOverlay(popup);

map.on('click', function (evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel,
    function (feature) {
      return feature;
    });
  if (feature) {
    var coordinates = feature.getGeometry().getCoordinates();
    popup.setPosition(coordinates);
    $(element).popover({
      'placement': 'top',
      'html': true,
      'title': feature.get('name'),
      'content': feature.get('msg')
    });
    $(element).popover('show');
  } else {
    $(element).popover('destroy');
  }
});

// change mouse cursor when over marker
map.on('pointermove', function (e) {
  if (e.dragging) {
    $(element).popover('destroy');
    return;
  }
  var pixel = map.getEventPixel(e.originalEvent);
  var hit = map.hasFeatureAtPixel(pixel);
  map.getTarget().style.cursor = hit ? 'pointer' : '';
});


var features = [];
// points is the Array returned from server.
points.forEach(function(val, idx) {
  if(idx > 32) return;
  var loc = val.Location.split(',');
  features[idx] = new Alert(
    +loc[0] + idx / 45,
    +loc[1],
    val
  )
});
vectorSource.addFeatures(features);
1

All Right, using the ol-debug.js, I got the point.

It's because of the missing of img src in FEATURE_URI.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.