Below is my code to display a base map, set center coordinates and zoom level to show Ghana in view-port and also style/ color the ghana map for NDVI property of my source layer (mapbox hosted tileset) ghanaNDVILayer.
mapID='myMapID';
mapboxgl.accessToken = 'accessToken';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-1.41, 6.32],
zoom: 5
});
map.on('load', function () {
map.addLayer({
'id': 'main',
'type': 'fill',
'layout': {},
'paint': {
'fill-color': {
property: 'NDVI',
stops: [
[0, '#F2F12D'],
[1, '#EED322'],
[2, '#E6B71E'],
[3, '#DA9C20'],
[4, '#CA8323'],
[5, '#B86B25'],
[6, '#A25626'],
[7, '#8B4225'],
[8, '#723122']
]
},
'fill-opacity': 0.8
},
'source': {
'type': 'vector',
'url': 'mapbox://' + mapID
},
"source-layer": "ghanaNDVILayer",
});
});
Now if you see in above code I've hard coded the center coordinates, zoom level and stops array which is typical for this Ghana NDVI trends example.
Now, this approach is fine when I am dealing with only one data source (in this case ghana data source) but I can't hard code these values as my data source could change and could be any region of the world and the property could also be anything other than NDVI.
I am using mapbox hosted tilesets as the data source, but I also have the original geoJson data source on my server.
Is there any way in Mapbox to calculate center, zoom and stops dynamically depending on the source we are loading?
The other approach I thought is to pass the tileset source Id to my server and locate the original geoJSON and using that calculate the center, zoom and stops on the server and then pass these values to my client and then render the map in the js.
Let me know what is the best way to calculate these values dynamically.
via Saurabh Palatkar