Hi Anne!
mapboxgl.accessToken
expects the literal token, so let’s say your token was
pk.eyJ2Ijoic3RtLWFudmlsIiwiYSI6ImNqcXA1a2FsNTBoOHo0Mm13YjJuN3IydGQifQ.RJ3divudCfU2qoDZ8CmELh
you would use it like so:
mapboxgl.accessToken = 'pk.eyJ2Ijoic3RtLWFudmlsIiwiYSI6ImNqcXA1a2FsNTBoOHo0Mm13YjJuN3IydGQifQ.RJ3divudCfU2qoDZ8CmELh';
// ... and the rest of the inialisation code ...
But as you point out, it is more secure to store the token in a Secret. To do this, you need to pass it into the JavsScript from the Python, so your initialisation needs to go into a function:
function initMap(token) {
mapboxgl.accessToken = token;
map = new mapboxgl.Map({
container: 'mapBoxMap',
style: 'mapbox://styles/annee/cjqsbbdsrafaz2tpakytjdxze',
center: [6.0, 70.0],
zoom: 3
});
}
This can be called from the show
event of the Form using call_js
:
# On the client side, in MapBoxMap
def form_show(self, **event_args):
"""This method is called when the HTML panel is shown on the screen"""
# Get the token from the server
token = anvil.server.call_s('get_mapbox_token')
# Call the JavaScript function to initialise MapBox
self.call_js('initMap', token)
Remember to bind the form_show
method to the show
event on the Form! Like so:
That’s not the end of the story - the anvil.server.call_s
is there because Secrets can only be accessed on the server side, for security reasons. So we have a server function to access the token and return it to the client:
# In a Server module
@anvil.server.callable
def get_mapbox_token():
return anvil.secrets.get_secret('Mapbox_token')
Let me know whether you get this working, do ask more questions if anything’s not clear.