Javascript / Openlayers for loop not working -
i'm creating map openlayers , having trouble getting features appear.
i want take array, , assign each coordinate it's own marker. relevant code (full code @ bottom of post):
var npctowns = [ [ 533, mapy-966 ], [ 833, mapy-1766 ], [ 2000, mapy-500 ], [ 1500, mapy-1700 ] ]; (var = 0; < npctowns.length; i++) { var lon = npctowns[i][0]; var lat = npctowns[i][0]; var npctownicons = new ol.feature({ geometry: new ol.geom.point([lon,lat]) }); var iconstyle = new ol.style.style({ image: new ol.style.icon ({ anchor: [0, 0], anchorxunits: 'pixels', anchoryunits: 'pixels', opacity: 1, src: 'assets/img/icons/town.gif' }) }); var vectorsource = new ol.source.vector({ features: [npctownicons] }); var vectorlayer = new ol.layer.vector({ source: vectorsource }); };
i think running problem not assigning feature variable dynamically? not sure how fix it! appreciated!
full map code on jsfiddle: https://jsfiddle.net/dhaurhvj/
you need initialize vectorlayer
outside for
loop, map initialization can access vectorlayer
.
need add features layer (because created before).
i think code should this:
var vectorsource = new ol.source.vector({features: [[]]}); var vectorlayer = new ol.layer.vector({ source: vectorsource }); var iconstyle = new ol.style.style({ image: new ol.style.icon ({ anchor: [0, 0], anchorxunits: 'pixels', anchoryunits: 'pixels', opacity: 1, src: 'assets/img/icons/town.gif' }) }); (var = 0; < npctowns.length; i++) { var lon = npctowns[i][0]; var lat = npctowns[i][0]; var newicon = new ol.feature({ geometry: new ol.geom.point([lon,lat]) }); newicon.setstyle(iconstyle); vectorsource.addfeature(newicon); };
you can populate array (newicon
) features , initialize vectorlayer after loop , pass array it.
Comments
Post a Comment