John Doi2021
John Doi2021

Reputation: 103

Adding onclick call for mapbox icons

I'm struggling with adding a click event to points on my mapbox map. I'm having to add the source from a backend sql query into a hbs template. I've tried just adding business1 as the source without the for loop but i get an invalid geojson object warning. If i add just 'locations' as the id obviously it gives me a warning that the id already exists on the map.

So how i can add an onclick call for dynamics id's?

How i load the points

business1 = {{{businesses}}}

for(i=0;i<business1.length;i++){
  // Add the data to your map as a lyer
  map.addLayer({
    id: 'locations'+[i],
    type: 'symbol',
   minzoom: zoomThreshold,
    // Add a GeoJSON source containing place coordinates and information.
    source: {
      type: 'geojson',
      data: business1[i]
    },
    layout: {
      'icon-image': 'circle-stroked-15',
      'icon-allow-overlap': true,
    }
  });

}

How the map click is called-with the added [i] just to show what i'm thinking

map.on('click', function(e) {

  var features = map.queryRenderedFeatures(e.point, {
    layers: ['locations'+[i]] // replace this with the name of the layer
  });

  if (!features.length) {
    return;
  }

What else i've tried-but always returns the same location regardless of what is clicked

   for(i=0; i<business1.length;i++){

    var features = []
    var feature = [i]
        feature.dataPosition = i;
 var clickedNameClicked = names[this.dataPosition]
 console.log(clickedNameClicked)

  features.push(business1[i]);

  }

Upvotes: 0

Views: 270

Answers (1)

riastrad
riastrad

Reputation: 1774

I definitely don't recommend adding a new source / layer for each business. That will not be performant if you have a bunch of layers, and I think it's adding too much complexity to your on click logic.

I've tried just adding business1 as the source without the for loop but i get an invalid geojson object warning.

This is a strong indication that there's something awry with your business data that you should address before adding it to your map and worrying about click events. I would recommend using a tool like http://geojsonlint.com/ to see what is going on there.

Once you have valid geojson, it will be much easier to add click events to your icons. https://docs.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures-around-point/


⚠️ Disclaimer: I currently work at Mapbox ⚠️

Upvotes: 1

Related Questions