As asked in previous question: Displaying icon name next to icon using OpenLayers? , now I need to change data source to the JSON API data, and used jquery plugin bypass CORS (http://www.ajax-cross-origin.com/install.html). The code part i changed from previous question jsfiddle:
var apiURL = 'https://map.navifleet.pl/api.php?api_key=[api-key]&type=1';
$.ajaxSetup({
crossOrigin: true,
proxy: 'proxy.php'
});
$.getJSON(apiURL, null, function(data){
console.log(data);
console.log(JSON.stringify(data));
var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
data.forEach(function(item) {
console.log(item);
console.log(JSON.stringify(item));
var feature = new ol.Feature(item);
feature.set('name', item.name);
var coordinate = transform([parseFloat(item.lon), parseFloat(item.lat)]);
var geometry = new ol.geom.Point(coordinate);
feature.setGeometry(geometry);
mapSource.addFeature(feature);
});
});
The code returns Uncaught TypeError: data.forEach is not a function.
Updated code: code
Example JSON Data from API:
{
"success": true,
"data": [{
"device": {
"id": 1555,
"name": "Iveco Daily 2015",
"icon_color": "009900",
"mark": "IVECO",
"model": "DAILY",
"license": "K1 NAVI",
"mileage": 20966.707
},
"data": [{
"gps_timestamp": 1542282655,
"lon": 18.5842,
"lat": 49.7232,
"speed": 101,
"direction": 239,
"distance": 0.8741,
"total_distance": 199918
}]
}, {
"device": {
"id": 7102,
"name": "Iveco Daily 2018",
"icon_color": "1873BA",
"mark": "Iveco",
"model": "Daily",
"license": "",
"mileage": 0
},
"data": [{
"gps_timestamp": 1541508344,
"lon": 20.0676,
"lat": 50.0865,
"speed": 0,
"direction": 258,
"distance": 0,
"total_distance": 322.622
}]
}]
}
datashows it comprises a success boolean followed by a data array{"success":true,"data":[{so you will need to usedata.data.forEach()datais being returned as a string, that's why you see\"in the log when you stringify it. So you will needJSON.parse(data).data.forEach()