0

I have integrated a Google Map on my Website. I have saved my token_api in a variable in .env and declare as global in twig.yaml. If i access the token via {{token_google_api}} my map display only if i refresh my page.

I have tried to paste my token in raw and it work well, but i don't want to have a secret token write in raw in my code.

Display on refresh:

<script async defer src="https://maps.googleapis.com/maps/api/js?key={{token_google_api}}&callback=initMap"></script>

Display well:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=my_token_in_raw&callback=initMap"></script>

my .env

TOKEN_GOOGLE_API=my_token_in_raw

my twig.yaml

twig:
    globals:
        token_google_api: '%env(TOKEN_GOOGLE_API)%'

Actually i have to refresh my page to display the map. I expect the map display when i come to the page the first time.

Edit: It seems to work properly on Edge. but not in Firefox & Chrome so, there is the css for my map div maybe should be helpful.

#map {
  height: 600px;
  width: 100%;
}
Fxdpt
  • 41
  • 5

1 Answers1

0

It looks like this is happening because you're using a variable in your script that loads the Maps API, but this is HTML. What you can do is load the script using JavaScript. There's a good example in related thread dynamically set googleapi key

In any case, your API key is a browser key that will still be publicly visible but that's fine and it can't be avoided. You should restrict it to your own domain though. Follow Google's guide to properly secure the key with HTTP referrer restrictions.

Also see related What steps should I take to protect my Google Maps API Key?

Hope this helps you.

evan
  • 5,443
  • 2
  • 11
  • 20