androidgoogle-mapsandroid-mapviewandroid-maps-v2

How to give map api key dynamically in android


I have a use-case in my android app that users of my application have to give API key so that they can use the map.

but I see that I have to give the API key in the manifest file. which I can't edit at the runtime.

is there any other ways to give the map API key dynamically to the google map (I'm using MapView) or any ways to change the meta-data values dynamically


Solution

  • Unfortunately, this does not seem possible at all.

    Google documentation

    https://developers.google.com/maps/documentation/android-sdk/get-api-key#add_key strictly talks about the manifest and how to add the key to the local.properties:

    Open the local.properties in your project level directory, and then add the following code. Replace YOUR_API_KEY with your API key.

    MAPS_API_KEY=YOUR_API_KEY

    and then referencing it from the Manifest:

    In your AndroidManifest.xml file, go to com.google.android.geo.API_KEY and update the android:value attribute as follows:

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="${MAPS_API_KEY}" />
    

    Deprecated and since removed constructor

    Apparently, a long time ago there was indeed a way of injecting the key when instantiating the MapView object manually (i.e. not with a layout xml): https://stackoverflow.com/a/11739039

    mMapView = new MapView(this, mapApiKey);
    

    However, this constructor was removed since and you cannot give the API key anymore: https://developers.google.com/maps/documentation/android-sdk/reference/com/google/android/libraries/maps/MapView?hl=en#public-constructor-summary

    MapView(Context context)
    MapView(Context context, AttributeSet attrs)
    MapView(Context context, AttributeSet attrs, int defStyle)
    MapView(Context context, GoogleMapOptions options)