I came across an interesting solution on stackoverflow for dynamically inserting data into a map using OpenLayers 3.*. Everything seems to be working fine when I directly input the numbers like this:
geometry: new ol.geom.Point(ol.proj.transform([-72.0704,46.678],'EPSG:4326','EPSG:3857')),
However, things take a strange turn when I attempt to use JSON data as shown in the following code:
- Replacing only the longitude displays the marker correctly,
- Substituting only the latitude results in zero latitude value,
When substituting both longitude and latitude, the marker disappears.
function AddMarkers() { var iconFeatures=[]; data = [{"longitude":"-72.0704","latitude":"46.678"},{"longitude":"-73.1234","latitude":"45.678"},{"longitude":"46.738586","latitude":"24.774265"}]; var iconFeature = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([data[0].longitude,46.678], 'EPSG:4326', 'EPSG:3857')), name: 'Null Island', population: 4000, rainfall: 500 }); var iconFeature1 = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([28.7753927 , data[1].latitude], 'EPSG:4326', 'EPSG:3857')), name: 'Null Island Two', population: 4001, rainfall: 501 }); var iconFeature2 = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([data[2].longitude,data[2].latitude], 'EPSG:4326', 'EPSG:3857')), name: 'Null Island Two', population: 4002, rainfall: 502 }); iconFeatures.push(iconFeature); iconFeatures.push(iconFeature1); iconFeatures.push(iconFeature2); var vectorSource = new ol.source.Vector({ features: iconFeatures //add an array of features }); var iconStyle = new ol.style.Style({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({ anchor: [0.5, 46], anchorXUnits: 'fraction', anchorYUnits: 'pixels', opacity: 0.75, src: 'images/icon.png' })) }); var vectorLayer = new ol.layer.Vector({ source: vectorSource, style: iconStyle }); return vectorLayer;
}
Why does this puzzling behavior occur only when using data from a JSON array, but not when manually inputting the values?