[GIS] OpenLayers – markers not displayed

javascriptopenlayers-2

I just started worrking with OpenLayers and hava a problem with markers that donĀ“t appear.
I have no idea where is the problem.

<script type="text/javascript">

function init() {
    var center = new OpenLayers.LonLat(17.55, 53.7).transform('EPSG:4326', 'EPSG:900913');
    var map = new OpenLayers.Map("map");
    var osm = new OpenLayers.Layer.OSM();
    map.addLayer(osm);
    map.setCenter(center, 12);


    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);
    var table;

    console.log(map);


$.getJSON('url',

function (data) {
    console.log(data);
    $.each(data.response.venues, function (i, venues) {

        markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(venues.location.lng, venues.location.lat).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913")), icon));
        markers.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(venues.location.lng, venues.location.lat).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913")), icon.clone()));
    });
});
}    

1 UPDATE: map.addLayers(markers) changed to map.addLayer(markers)
2 UPDATE: put the getJSON call in the init() function

Best Answer

Two things. First, all your variables defined in init() are out of scope when the JSON function runs. Fix that by putting the getJSON call in the init() function too, or defining the map and other variables in the global scope (especially if you want to do anything else with them).

Secondly, map.addLayer(markers) instead of map.addLayers(markers). There's only one marker layer, so use the singular.