Mapbox GL JS Examples  |  Query Features

You can query features in Mapbox GL JS, but only features that are currently rendered in the browser window.

« Adding Layers Choropleth Maps »

Full Map Code

      
/*Blank Mapbox GL Map*/

var map = new mapboxgl.Map({
  container: 'map',
  hash: true,
  /*style: 'some mapbox style url*/
  /*below is a blank style*/
  style: {
    "version": 8,
    "name": "blank",
    "sources": {
      "openmaptiles": {
        "type": "vector",
        "url": ""
      }
    },
    "layers": [{
      "id": "background",
      "type": "background",
      "paint": {
        "background-color": "#1d1f20"
      }
    }]
  },
  center: [-95.52, 39.94],
  zoom: 4,
  debug: 1
});
map.addControl(new mapboxgl.NavigationControl());
map.addControl(new mapboxgl.FullscreenControl());

/*End Blank Map*/

/*Add Layers*/
/*Wait for the initial style to load*/

map.on('style.load', function() {
  map.addSource('counties', {
    'type': 'geojson',
    /*many types of data can be added, such as geojson, vector tiles or raster data*/
    'data': '/gis-tutorials/tutorial-data/counties.geojson'
  });

  /*here we are adding a source, then a layer based on that that source*/

  map.addLayer({
    'id': 'countiesLayer',
    'type': 'fill',    /*define the type of layer fill, line, point, fill-extrusion, background, raster, circle*/
    'source': 'counties',
    'layout': {
      'visibility': 'visible'
    },
    
    /*there are many options for styling - this is a simple style*/

    'paint': {
      'fill-color': 'skyblue',
      'fill-outline-color': 'white',
      'fill-opacity': 0.9
    }
  });
});

/*End add layers*/

/*Query with Popup and tooltip example*/

var popup = new mapboxgl.Popup({
  closeButton: false,
  closeOnClick: false
});

function identifyFeatures(location, layer, fields) {
  var identifiedFeatures = map.queryRenderedFeatures(location.point, layer);
  /*console.log(identifiedFeatures);*/
  popup.remove();
  if (identifiedFeatures != '') {
    var popupText = "";
    for (i = 0; i < fields.length; i++) {
      popupText += "<strong>" + fields[i] + ":</strong> " + identifiedFeatures[0].properties[fields[i]] + "<" + "br" + ">"
    };
    popup.setLngLat(location.lngLat)
      .setHTML(popupText)
      .addTo(map);
  }
}

map.on('click', function(e) {
  identifyFeatures(e, 'countiesLayer', ["NAME", "POPULATION", "POP_SQMI"])
});

map.on('mousemove', function(e) {
  identifyFeatures(e, 'countiesLayer', ["NAME", "POPULATION", "POP_SQMI"])
});

/*End popup and tooltip example*/