seanrs97
seanrs97

Reputation: 333

Is there a way to add a layer to data generated via an AJAX callback using Mapbox?

Using the code below (that generates event data from an API) I want to create a mapbox layer, which I can then use to create markers and symbols across the map. I don't however want to use Mapbox markers as this causes issues with my code and is not something I want to use.

I have already managed to achieve this for hard coded data and I want to do the same for the data received from the API. Iv'e tried converting the data generated into GeoJSON as well as trying to loop over the data (this results in multiple id's being created and the code breaking)

callbackEventbrite(function(result){
console.log("env", result)
//var geo = GeoJSON.parse(result.events,{Point: [result.location.latitude, result.location.longitude]});
//console.log(geo);
const keys = Object.values(result);
for(const key of keys){
    geojson = {
        type: 'featureCollection',
        features: [{
            type: 'feature',
            geometry: {
                type: 'Point',
                coordinates: [key.venue.longitude, key.venue.latitude]
            }
        }]
    }
    eventInfo.push(
        {"longitude": key.venue.longitude , "latitude": key.venue.latitude , "name": key.name.text, "venue": key.venue.name, "date": key.start.local, "category": key.category_id}
    );

}
});

function callbackEventbrite(callback){
$.ajax(briteSettings).done(function(data){
    callback(data.events);
});
}
// What Iv'e got to work (hard coded data)
map.on("load", function(){
map.addLayer({
    "id": "locations",
    "type": "symbol",
    "source": {
        "type": "geojson",
        "data": {
            "type": "FeatureCollection",
            "features": [
                {
                  "type": "Feature",
                  "properties": {
                    "Title": "The Congress Inn",
                    "Description": "Pub located in Longton",
                    "Type": "Pub",
                    "Address": "14 Sutherland Rd, Stoke-on-Trent ST3 1HJ",
                    "Longitude": 2.1316,
                    "Latitude": 52.9878,
                    "icon": "bar"
                  },
                  "geometry": {
                    "coordinates": [
                      -2.131836,
                      52.987238
                    ],
                    "type": "Point"
                  }
                }

In a working state, each result generated from the API should have it's own symbol on the map, generated through the addLayer method. Any help is much appreciated!

Upvotes: 0

Views: 742

Answers (1)

samfader
samfader

Reputation: 161

Here's an example of an AJAX call made via d3 that is used to add a source and layer to the map: https://docs.mapbox.com/mapbox-gl-js/example/timeline-animation/

Disclaimer: I work at Mapbox.

Upvotes: 1

Related Questions