[GIS] Adding multiple OpenLayers Vector Layer markers to map using AJAX, JSON, and jQuery

ajaxjqueryopenlayers-2

I am attempting to parse a JSON file and place markers on an OpenLayers based map application. I am using jQuery to perform the AJAX and iteration on the JSON file.

I am having a problem with the code below. When inspecting the element, I can see in the console log that the latitude and longitude are being iterated through correctly. However, only one marker appears on the map at the 0,0 location.

Can someone point me in the right direction to make this happen?

A question similar to this was answered before (Adding multiple OpenLayers Vector Layer markers with data parsed from JSON file?), however, the jQuery based answer was replaced with pure Javascript.

 // Setup marker layer for all transmitters from DATA.json file
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);

var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png', size, offset);
$.getJSON('json/DATA.json', function(data) {
    $.each(data.POI, function() {
        markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(this.longitude,this.latitude),icon));
        console.log(this.longitude, this.latitude);
        markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(this.longitude, this.latitude),icon.clone()))
    });
});

Here is a sample of the JSON

"LOCATION_A": {
          "latitude": 10.2070,
          "longitude": 25.3215,
          "altitude": 1.2,
          "status": "CLOSED",
          "serverAddress": "192.168.0.1"
 }

Best Answer

Here is how I solved my own problem:

 var pointLayer = new OpenLayers.Layer.Vector("POI Markers", {projection: "EPSG:4326"});
$.getJSON('json/DATA.json', function(data) {
  $.each(data.POI, function() {
    var pointFeatures = [];
    var px = this.longitude;
    var py = this.latitude;
    // Create a lonlat instance and transform it to the map projection.
    var lonlat = new OpenLayers.LonLat(px, py);
    lonlat.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));

    var pointGeometry = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
    var pointFeature = new OpenLayers.Feature.Vector(pointGeometry, null, {
        pointRadius: 16,
        fillOpacity: 0.7,
        externalGraphic: 'marker.png',
    });

    pointFeatures.push(pointFeature);
    pointLayer.addFeatures(pointFeatures);
  });
});

The code sample above allows me to iterate through the complete DATA.json file and places markers defined by "externalGraphic" on the map based on latitude and longitude.