Search code examples
javascriptmarkermapbox-gl-js

Mapbox gl js Add a Marker from firebase database


I want to add some costumized markers to my mapbox map based on my firebase database but i don't know how.

So i got my gotData function that receives the latitude and longitude from my database

    function gotData(data) {

  console.log(data.val());
  var dados = data.val();
  var keys = Object.keys(dados);
 // console.log(keys);
for (var i = 0; i < keys.length; i++) {
    var k = keys[i];
    var latitude = dados[k].latitude;
    var longitude = dados[k].longitude;
    //console.log(latitude, longitude);
    var li = createElement('li', latitude + ': ' + longitude);   
}   

}

And I have placed on my HTML file a code to add a Marker but I don't know what to put inside the "coordinates":

mapa.on('load', function () {
mapa.addLayer({
    "id": "points",
    "type": "symbol",
    "source": {
        "type": "geojson",
        "data": {
            "type": "FeatureCollection",
            "features": [{
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [What goes here?]
                },
                "properties": {
                    "title": "title",
                    "icon": "circle"
                }
            }]
        }
    },
    "layout": {
        "icon-image": "{icon}-15",
        "text-field": "{title}",
        "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
        "text-offset": [0, 0.6],
        "text-anchor": "top"
    }
});

});

Any tips are welcome


Solution

  • In GeoJSON (spec here), the coordinates for a point is an array in [longitude, latitude] order.

    So for your code you want something like:

    var features = [];
    for (var i = 0; i < keys.length; i++) {
        var k = keys[i];
        var latitude = dados[k].latitude;
        var longitude = dados[k].longitude;
        //console.log(latitude, longitude);
        var li = createElement('li', latitude + ': ' + longitude);   
    
        features.push({
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [+longitude, +latitude]
            },
            "properties": {
                "title": "title",
                "icon": "circle"
            }
        });
    
    }   
    
    
    mapa.addLayer({
        "id": "points",
        "type": "symbol",
        "source": {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                "features": features
            }
        },
        "layout": {
            "icon-image": "{icon}-15",
            "text-field": "{title}",
            "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
            "text-offset": [0, 0.6],
            "text-anchor": "top"
        }
    });