0

I have the following piece of code below, where the positions are not shown on the map and after 4 days of searching I still don't know why. Can someone help me please? I really don't know why it does not work. The data is correctly retrieved from a webservice to my JavaScript but the map becomes empty :(

Any help would be very appreciated. Thanks in advance.

It works if I update a few points without fetching data from server like the example below

var baseMapLayer = new ol.layer.Tile({
  source: new ol.source.OSM()
});
var map = new ol.Map({
  target: 'map',
  layers: [ baseMapLayer],
  view: new ol.View({
          center: ol.proj.fromLonLat([-9.294444444,38.70833333]), // Cordinates of EDISOFT
          zoom: 7 //Initial Zoom Level
        })
});

var myMarkerFeatures = [];

//Adding a marker on the map near sines

var marker1 = new ol.Feature({
  geometry: new ol.geom.Point(
    ol.proj.fromLonLat([-9.294444444,37.70833333])
  ),  // Cordinates of EDISOFT Thales in Paço de Arcos

});

marker1.setStyle(new ol.style.Style({
        image: new ol.style.Icon(({
            crossOrigin: 'anonymous',
            src: 'AISSymbols/cargo-ship.png',
        scale: 0.30

        })),
    text: new ol.style.Text({
            text: '501',
            fill: new ol.style.Fill({color: 'black'}),
            stroke: new ol.style.Stroke({color: 'yellow', width: 1}),
            offsetX: -20,
            offsetY: 20
        })
    }));

marker1.setId(501);


//Adding a marker on the map near EDIOSFT
var marker2 = new ol.Feature({
  geometry: new ol.geom.Point(
    ol.proj.fromLonLat([-9.294444444,38.70833333])
  ),  // Cordinates of 1 degree to the west of EDISOFT location

});
marker2.setStyle(new ol.style.Style({
        image: new ol.style.Icon(({
            crossOrigin: 
'anonymous',
            src: 'AISSymbols/AIS_Vessel.svg',
        rotation: Math.PI / 4.0,
        scale: 0.30

        })),
    text: new ol.style.Text({
            text: '502',
            fill: new ol.style.Fill({color: 'black'}),
            stroke: new ol.style.Stroke({color: 'red', width: 1}),
            offsetX: -20,
            offsetY: 20
        })

    }));
marker2.setId(502);

//myMarkerFeatures = [marker1, marker2];

var vectorSource = new ol.source.Vector({
  features: myMarkerFeatures
});


myMarkerFeatures.push(marker1);
myMarkerFeatures.push(marker2);


//Adding a marker on the map near shore
var markerVectorLayer = new ol.layer.Vector({
  source: vectorSource,

});
map.addLayer(markerVectorLayer);


var marker = new ol.Feature({
  geometry: new ol.geom.Point(
    ol.proj.fromLonLat([-9.694444444,38.70833333])
  ),  // Cordinates of New York's City Hall
});
marker.setStyle(new ol.style.Style({
        image: new ol.style.Icon(({
            crossOrigin: 
'anonymous',
            src: 'AISSymbols/AIS_Vessel.svg',
        rotation: Math.PI / 1.0,
        scale: 0.30

        })),
    text: new ol.style.Text({
            text: '503',
            fill: new ol.style.Fill({color: 'black'}),
            stroke: new ol.style.Stroke({color: 'back', width: 1}),
            offsetX: -20,
            offsetY: 20
        })

    }));
marker.setId(503);
myMarkerFeatures.push(marker);

map.renderSync();
vectorSource.clear(true);
vectorSource.addFeatures(myMarkerFeatures);

//////////////////////////////////////////////////////////

vectorSource.clear(true);
for (var i=0; i<myMarkerFeatures.length;i++){
    if (myMarkerFeatures[i].getId() === 502){
        myMarkerFeatures[i].set('geometry', new ol.geom.Point(getPointFromLongLat(-10.694444444,38.70833333)));
        //myMarkerFeatures[i].getGeometry().setCoordinates([-10.694444444,38.70833333]);
        //myMarkerFeatures[i].getGeometry().setCoordinates(getPointFromLongLat(-10.694444444, 38.70833333));


    }else if (myMarkerFeatures[i].getId() === 501){
        myMarkerFeatures[i].set('geometry', new ol.geom.Point(getPointFromLongLat(-9.294444444,36.70833333)));
        //myMarkerFeatures[i].getGeometry().setCoordinates([-9.294444444,36.70833333]);
        //myMarkerFeatures[i].getGeometry().setCoordinates(getPointFromLongLat(-9.294444444, 36.70833333));
    } else if (myMarkerFeatures[i].getId() === 503){
        myMarkerFeatures[i].set('geometry', new ol.geom.Point(getPointFromLongLat(-9.694444444,39.70833333)));
        //myMarkerFeatures[i].getGeometry().setCoordinates([-9.694444444,39.70833333]);
        //myMarkerFeatures[i].getGeometry().setCoordinates(getPointFromLongLat(-9.694444444, 39.70833333));
    } else {
        alert('Dummy points found');
    }
};

//map.renderSync();

vectorSource.addFeatures(myMarkerFeatures);

function getPointFromLongLat (long, lat) {
    return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')
}






var baseMapLayer = new ol.layer.Tile({
    source: new ol.source.OSM()
});
var map = new ol.Map({
    target: 'map',
    layers: [baseMapLayer],
    view: new ol.View({
        center: ol.proj.fromLonLat([-9.294444444, 38.70833333]), // Cordinates of EDISOFT
        zoom: 7 //Initial Zoom Level
    })
});


var aisMarkerFeatures = [];
var vectorSource = new ol.source.Vector({
    features: aisMarkerFeatures //add an array of features
});
var vectorLayer = new ol.layer.Vector({
    source: vectorSource
});


map.addLayer(vectorLayer);




function addMarker(MMSI, lon, lat, COG) {

    var found = false;

    for(var i = 0; i < aisMarkerFeatures.length; i++) {
        if (aisMarkerFeatures[i].getId() === MMSI) {
            aisMarkerFeatures[i].set('geometry', new ol.geom.Point(getPointFromLongLat(lon, lat)));
            aisMarkerFeatures[i].setStyle(new ol.style.Style({
                image: new ol.style.Icon(({
                    crossOrigin:
                        'anonymous',
                    src: 'AISMarkers/cargo-ship.png',
                    rotation: Math.PI * COG / 180.0,
                    scale: 0.30
                })),
                text: new ol.style.Text({
                    text: MMSI,
                    fill: new ol.style.Fill({ color: 'black' }),
                    stroke: new ol.style.Stroke({ color: 'black', width: 1 }),
                    offsetX: -20,
                    offsetY: 20
                })
            }));
            found = true;
            break;
        }
    }
    if (found == false) {
        var markerGeometry = new ol.geom.Point(ol.proj.fromLonLat([lon, lat]));
        var markerFeature = new ol.Feature({
            geometry: markerGeometry
        });

        markerFeature.setId(MMSI);

        markerFeature.setStyle(new ol.style.Style({
            image: new ol.style.Icon(({
                crossOrigin:
                    'anonymous',
                src: 'AISMarkers/cargo-ship.png',
                rotation: Math.PI * COG / 180.0,
                scale: 0.30
            })),
            text: new ol.style.Text({
                text: MMSI,
                fill: new ol.style.Fill({ color: 'black' }),
                stroke: new ol.style.Stroke({ color: 'black', width: 1 }),
                offsetX: -20,
                offsetY: 20
            })
        }));
        aisMarkerFeatures.push(markerFeature);
    }


};

function getPointFromLongLat(long, lat) {
    return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')
}


window.setInterval(function () {

    //clean the layer from any existing markers
    vectorSource.clear(true);

    $.ajax({
        url: 'http://localhost/aisdataretriever/aisdataretriever.asmx/TransferAISPosition',
        type: 'POST',
        cache: false,
        dataType: 'json',
        success: function (aisdata) {
            $.each(aisdata, function (recordCount, aisship) {


                var createMarker = addMarker(aisship.MMSI, aisship.Longitude, aisship.Latitude, aisship.COG);

            });
            //and here add the newly created features to the layer
            vectorSource.addFeatures(aisMarkerFeatures);

        }, error: function () {
            console.log("Connection Failed");
        }
    });
}, 5000);

The map is unexpectedly shown without points

barbsan
  • 3,418
  • 11
  • 21
  • 28
  • Is this code Javascript? – Scary Wombat Jul 02 '19 at 02:00
  • 1
    Hi Joao, and welcome to StackOverflow. You say "to my java script ", but you have tagged your question with "Java". Despite the similarity in names, Java is a totally different language from JavaScript (and please also note that JavaScript is one word, not containing a space - not least to reduce the possibility of confusing the two languages). Upshot is, please remove the Java tag and replace it with a JavaScript tag, which will help users familiar with JavaScript to find your question. – racraman Jul 02 '19 at 02:13
  • Try using `vectorSource.refresh()` after you add features to vectorSource in `success` of your ajax call. – capnam Jul 02 '19 at 12:44
  • Thank you very much racraman for your comment. The problem is solved. I found out the geography data read from my webservice/database where the Longitude and Latitudfe is read from needs to be converted to float (parseFoat was used) before invoking the openlayer methods where the feature points are defined. Now my data is shown in the webpage. – JoaoOliveira Jul 03 '19 at 11:54

0 Answers0