My use case : Fill the color on building/address based on user’s searched building/address in Mapbox GL.
What I have achieved till now : I am able to get the searched building’s details by using GeoCoder event “result” and I am getting feature ID in response along with coordinates of the searched address. And I am changing it’s color by using setFeatureState method but it’s filling the color on whole state/country. Please checkout my JS code.
const bounds = [
[-97.846976993, 30.167105159], // Southwest coordinates
[-97.751211018, 30.242129961], // Northeast coordinates
];
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/smallcrowd/cl07a4926001b15pnu5we767g",
center: [-79.4512, 43.6568],
zoom: 13,
maxBounds: bounds,
});
// Add the control to the map.
const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
});
geocoder.on("result", (e) => {
map.addSource("states", {
type: "geojson",
data: "https://docs.mapbox.com/mapbox-gl-js/assets/us_states.geojson",
});
map.addLayer({
id: "state-fills",
type: "fill",
source: "states",
layout: {},
paint: {
"fill-color": "#FFA500",
},
});
console.log(e);
map.setFeatureState({
id: e.result.id, //feature id
source: "states",
});
});
document.getElementById("geocoder").appendChild(geocoder.onAdd(map));
This is geocoder result response:
result: {
center: (2) [-97.791161, 30.229803]
context: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
geometry: {coordinates: Array(2), type: 'Point'}
id: "poi.412316930875"
place_name: "Texas Tool Traders, 2101 W Ben White Blvd, Austin, Texas 78704, United States"
place_name_en-US: "Texas Tool Traders, 2101 W Ben White Blvd, Austin, Texas 78704, United States"
place_type: ['poi']
properties: {foursquare: '53d16d13498ea4ebec82bc78', landmark: true, address: '2101 W Ben White Blvd', category: 'hardware, shop'}
relevance: 1
text: "Texas Tool Traders"
text_en-US: "Texas Tool Traders"
type: "Feature"
}