Monday 17 June 2019

openlayers - Looping through an array to show multiple points on the map



I am trying to add multiple points on the map. Data comes from the server as a multi array.


JSFiddle.


Notice that all points share the same name (when clicking on the point)


This is the response from PHP:


[
{
name: "Parking0001",
lat: "35.1495",

lon: "33.39243"
},
{
name: "RecycleBin0001",
lat: "35.1495",
lon: "33.39243"
},
{
name: "WaterA27",
lat: "35.1495",

lon: "33.39243"
},
{
name: "WaterA12",
lat: "35.1495",
lon: "33.39243"
}
]

Something I am doing wrong and i get undefined on iconFeature in the loop



function OpeNlayers(data) {

var iconFeature = new ol.Feature({
geometry: new ol.geom.Point([199, 154]),
name: 'A point',
population: 4000,
rainfall: 500
});

var iconStyle = new ol.style.Style({

image: new ol.style.Icon({
anchor: [0.5, 0.5],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'icon.png'
})
});

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

});

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

var rasterLayer = new ol.layer.Tile({
source: new ol.source.TileJSON({
url: 'https://a.tiles.mapbox.com/v3/aj.1x1-degrees.json',
crossOrigin: ''

})
});

$.each(data, (index, data) => {
let iconFeature = new ol.Feature({
geometry: new ol.geom.Point([data.lon, data.lat]).transform('EPSG:4326', 'EPSG:3857'),
name: data.name
})
iconFeature.setStyle(iconStyle)
vectorSource.addFeature(iconFeature)

})

var map = new ol.Map({
target: 'map',
layers: [rasterLayer, vectorLayer],
view: new ol.View({
center: ol.proj.fromLonLat([35.1495, 33.39243]),
zoom: 7
})
});

}

$.post("MapMarkers.php", null, null, "json")
.done(data => {
OpeNlayers(data)
}).fail(function () {
alert("error loading data")
});

enter image description here





No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...