fawmi / vue-google-maps

Reactive Vue 3 components for Google maps
https://vue-map.netlify.app
MIT License
195 stars 99 forks source link

Giving the api key from the backend #146

Open cyhnkckali opened 1 year ago

cyhnkckali commented 1 year ago

Hi @fawmi, my request is as follows, Map's api key comes to me from backend. Is there a way to give this incoming key on page opening? It would be great if there was such a feature. I'm sorry for my bad english,

Thank you

swilla commented 1 year ago

The way I've always done this was create a JS window variable on the frontend and pass it to that. As long as that is on the page before your JS bundle you should have access to that variable.

Here is an example from a laravel app:

<!DOCTYPE html>
<html id="main-project" lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title inertia>{{ config('app.name', 'Laravel') }}</title>

        <!-- Fonts -->
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">

        <script>
            window.google_maps_js_key = config("services.google.key");
        </script>

        <!-- Scripts -->
        @routes
        @vite('resources/js/app.js')
        @inertiaHead
    </head>
    <body class="font-sans antialiased">
        @inertia
    </body>
</html>
cyhnkckali commented 1 year ago

@swilla 'window.google_maps_js_key config("services.google.key");' The result displayed for undefined. For this reason, can't a property like 'api_key' be added in dynamic approaches?

swilla commented 1 year ago

This example was Laravel, the config helper would loaded from the PHP backend. You would need to setup the services.php config file like this:

    'google_maps' => [
        'key' => env('GOOGLE_MAPS_JS_KEY'),
        'api_url' => env('GOOGLE_MAPS_API_URL'),
    ],
jamisonbryant commented 4 months ago

Apologies for commenting on a 2-year-old ticket, but the ability to dynamically inject a GMaps API key is something our app also needs. Each tenant in our app has their own API key, and it is fetched from an API endpoint so it is not available when Vue is mounted. The API request is fired from within the component that needs to use Google Maps.

Did anyone ever come up with a solution to dynamically inject the API key? Thanks in advance.