Generate Google Map Api Key Android

Posted on by
Generate Google Map Api Key Android Rating: 3,6/5 8168 votes

Jul 05, 2018  This is the first video of a series of tutorials using the Google Maps API in Android. In this video we focus on getting an API key and putting a map on the phone screen. Generate Google Maps. Aug 27, 2017  Create Google Maps API Key Go to the Google Developers Console Click Create Project (If you don’t already have one, otherwise it defaults to an existing project). If you have an existing project, but want to create a new one, click the drop down, then the + button.

  1. Google Api Key Generator
  2. Generate Google Map Api Key Android Download
  3. Free Google Api Key
  4. Generate Google Map Api Key Android Free
  5. Create Google Maps Api Key Android
-->

Using the Maps application is great, but sometimes you want to includemaps directly in your application. In addition to the built-in mapsapplication, Google also offers anative mapping API for Android.The Maps API is suitable for cases where you want to maintain morecontrol over the mapping experience. Things that are possible with theMaps API include:

  • Programmatically changing the viewpoint of the map.
  • Adding and customizing markers.
  • Annotating a map with overlays.

Unlike the now-deprecated Google Maps Android API v1, Google MapsAndroid API v2 is part ofGoogle Play Services.A Xamarin.Android app must meet some mandatory prerequisites beforeit is possible to use the Google Maps Android API.

Google Maps API prerequisites

Several steps need to be taken before you can use the Maps API, including:

Obtain a Google Maps API Key

The first step is to get a Google Maps API key (note that you cannotreuse an API key from the legacy Google Maps v1 API). For information abouthow to obtain and use the API key with Xamarin.Android, seeObtaining A Google Maps API Key.

Install the Google Play Services SDK

Google Play Services is a technology from Google that allows Androidapplications to take advantage of various Google features such asGoogle+, In-App Billing, and Maps. These features are accessible onAndroid devices as background services, which are contained in theGoogle Play Services APK.

Android applications interact with Google Play Services through theGoogle Play Services client library. This library contains theinterfaces and classes for the individual services such as Maps. Thefollowing diagram shows the relationship between an Android applicationand Google Play Services:

The Android Maps API is provided as a part of Google Play Services.Before a Xamarin.Android application can use the Maps API, the GooglePlay Services SDK must be installed using the Android SDK Manager. The followingscreenshot shows where in the Android SDK Manager the Google Playservices client can be found:

Note

The Google Play services APK is a licensed productthat may not be present on all devices. Website auto traffic generator ultimate v6 1 activation key. If it is not installed, thenGoogle Maps will not work on the device.

Install the Xamarin.GooglePlayServices.Maps package from NuGet

The Xamarin.GooglePlayServices.Maps package contains the Xamarin.Android bindings for the Google Play Services Maps API.To add the Google Play Services Map package, right-click theReferences folder of your project in the Solution Explorer andclick Manage NuGet Packages..:

This opens the NuGet Package Manager. Click Browse and enterXamarin Google Play Services Maps in the search field. SelectXamarin.GooglePlayServices.Maps and click Install. (Ifthis package had been installed previously, click Update.):

Notice that the following dependency packages are also installed:

  • Xamarin.GooglePlayServices.Base
  • Xamarin.GooglePlayServices.Basement
  • Xamarin.GooglePlayServices.Tasks

Specify the required permissions

Apps must identify the hardware and permission requirements in order to use the Google Maps API. Some permissions are automatically granted by the Google Play Services SDK, and it is not necessary for a developer to explicitly add them to AndroidManfest.XML:

  • Access to the Network State – The Maps API must be able to checkif it can download the map tiles.

  • Internet Access – Internet access is necessary to download themap tiles and communicate with the Google Play Servers for APIaccess.

The following permissions and features must be specified in theAndroidManifest.XML for the Google Maps Android API:

  • OpenGL ES v2 – The application must declare the requirement forOpenGL ES v2.

  • Google Maps API Key – The API key is used to confirm that theapplication is registered and authorized to use Google PlayServices. SeeObtaining a Google Maps API Keyfor details about this key.

  • Request the legacy Apache HTTP client – Apps that target Android 9.0 (API level 28) or above must specify that the legacy Apache HTTP client is an optional library to use.

  • Access to the Google Web-based Services – The application needspermissions to access Google's web services that back the AndroidMaps API.

  • Permissions for Google Play Services Notifications – Theapplication must be granted permission to receive remotenotifications from Google Play Services.

  • Access to Location Providers – These are optional permissions.They will allow the GoogleMap class to display the location of thedevice on the map.

In addition, Android 9 has removed the Apache HTTP client library from the bootclasspath, and so it isn't available to applications that target API 28 or higher. The following line must be added to the application node of your AndroidManifest.xml file to continue using the Apache HTTP client in applications that target API 28 or higher:

Note

Very old versions of the Google Play SDK required an app to request the WRITE_EXTERNAL_STORAGE permission. This requirement is no longer necessary with the recent Xamarin bindings for Google Play Services.

The following snippet is an example of the settings that must be added to AndroidManifest.XML:

In addition to requesting the permissions AndroidManifest.XML, an app must also perform runtime permission checks for the ACCESS_COARSE_LOCATION and the ACCESS_FINE_LOCATION permissions. See the Xamarin.Android Permissions guide for more information about performing run-time permission checks.

Create an Emulator with Google APIs

In the event that a physical Android device with Google Play services is not installed, it is possible to create an emulator image for development. For more information see the Device Manager.

The GoogleMap Class

Once the prerequisites are satisfied, it is time to startdeveloping the application and use the Android Maps API. TheGoogleMapclass is the main API that a Xamarin.Android application will use todisplay and interact with a Google Maps for Android. This class has thefollowing responsibilities:

  • Interacting with Google Play services to authorize the applicationwith the Google web service.

  • Downloading, caching, and displaying the map tiles.

  • Displaying UI controls such as pan and zoom to the user.

  • Drawing markers and geometric shapes on maps.

The GoogleMap is added to an Activity in one of two ways:

  • MapFragment - TheMapFragmentis a specialized Fragment that acts as host for the GoogleMapobject. The MapFragment requires Android API level 12 or higher.Older versions of Android can use theSupportMapFragment. This guide will focus on using the MapFragment class.

  • MapView - TheMapViewis a specialized View subclass, which can act as a host for aGoogleMap object. Users of this class must forward all of theActivity lifecycle methods to the MapView class.

Each of these containers exposes a Map property that returns aninstance of GoogleMap. Preference should be given to theMapFragmentclass as it is a simpler API that reduces the amount boilerplate codethat a developer must manually implement.

Adding a MapFragment to an Activity

The following screenshot is an example of a simple MapFragment:

Similar to other Fragment classes, there are two ways to add aMapFragment to an Activity:

  • Declaratively - The MapFragment can be added via the XMLlayout file for the Activity. The following XML snippet shows anexample of how to use the fragment element:

  • Programmatically - The MapFragment can be programmatically instantiated using the MapFragment.NewInstance method and then added to an Activity. This snippet shows the simplest way to instantiate a MapFragment object and add to an Activity:

    It is possible to configure the MapFragment object by passing a GoogleMapOptions object to NewInstance. This is discussed in the section GoogleMap properties that appears later on in this guide.

The MapFragment.GetMapAsync method is used to initialize the GoogleMap that is hosted by the fragment and obtain a reference to the map object that is hosted by the MapFragment. This method takes an object that implements the IOnMapReadyCallback interface.

This interface has a single method, IMapReadyCallback.OnMapReady(MapFragment map) that will be invoked when it is possible for the app to interact with the GoogleMap object. The following code snippet shows how an Android Activity can initialize a MapFragment and implement the IOnMapReadyCallback interface:

Map types

There are five different types of maps available from the Google MapsAPI:

  • Normal - This is the default map type. It shows roads andimportant natural features along with some artificial points ofinterest (such as buildings and bridges).

  • Satellite - This map shows satellite photography.

  • Hybrid - This map shows satellite photography and road maps.

  • Terrain - This primarily shows topographical features with someroads.

  • None - This map does not load any tiles, it is rendered as anempty grid.

The image below shows three of the different types of maps, fromleft-to-right (normal, hybrid, terrain):

The GoogleMap.MapType property is used to set or change which type ofmap is displayed. The following code snippet shows how to display asatellite map.

GoogleMap properties

GoogleMap defines several properties that can control the functionalityand the appearance of the map. One way to configure the initial stateof a GoogleMap is to pass aGoogleMapOptionsobject when creating a MapFragment. The following code snippet is oneexample of using a GoogleMapOptions object when creating a MapFragment:

The other way to configure a GoogleMap is by manipulating properties on theUiSettingsof the map object. The next code sample shows how to configure aGoogleMap to display the zoom controls and a compass:

Interacting with the GoogleMap

The Android Maps API provides APIs that allow an Activity to changethe viewpoint, add markers, place custom overlays, or draw geometricshapes. This section will discuss how to accomplish some of these tasksin Xamarin.Android.

Changing the Viewpoint

Maps are modelled as a flat plane on the screen, based on the Mercatorprojection. The map view is that of a camera looking straight down onthis plane. The position of the camera can be controlled by changingthe location, zoom, tilt, and bearing. TheCameraUpdateclass is used to move the camera location. CameraUpdate objects are notdirectly instantiated, instead the Maps API provides theCameraUpdateFactoryclass.

Once a CameraUpdate object has been created, it is passed as aparameter to either theGoogleMap.MoveCameraorGoogleMap.AnimateCameramethods. The MoveCamera method updates the map instantly while theAnimateCamera method provides a smooth, animated transition.

This code snippet is a simple example of how to use theCameraUpdateFactory to create a CameraUpdate that will incrementthe zoom level of the map by one zoom level:

The Maps API provides aCameraPositionwhich will aggregate all of the possible values for the cameraposition. An instance of this class can be provided to theCameraUpdateFactory.NewCameraPositionmethod which will return a CameraUpdate object. The Maps API alsoincludes theCameraPosition.Builderclass that provides a fluent API for creating CameraPosition objects.The following code snippet shows an example of creating a CameraUpdatefrom a CameraPosition and using that to change the camera position on aGoogleMap:

In the previous code snippet, a specific location on the map isrepresented by theLatLngclass. The zoom level is set to 18, which is an arbitrary measure of zoom used by Google Maps. The bearing is the compassmeasurement clockwise from North. The Tilt property controls theviewing angle and specifies an angle of 25 degrees from thevertical. The following screenshot shows the GoogleMap after executingthe preceding code:

Drawing on the Map

The Android Maps API provides API's for drawing the following items on a map:

  • Markers - These are special icons that are used to identify a single location on a map.

  • Overlays - This is an image that can be used to identify a collection of locations or area on the map.

  • Lines, Polygons, and Circles - These are APIs that allow Activities to add shapes to a map.

Markers

The Maps API provides aMarkerclass which encapsulates all of the data about a single location on amap. By default the Marker class uses a standard icon provided by Google Maps. It ispossible to customize the appearance of a marker and to respond to userclicks.

Adding a Marker

To add a marker to a map, it is necessary create a newMarkerOptions object and then call theAddMarkermethod on a GoogleMap instance. This method will return aMarkerobject.

The title of the marker will be displayed in an info window when theuser taps on the marker. The following screenshot shows what thismarker looks like:

Customizing A Marker

It is possible to customize the icon used by the marker by calling theMarkerOptions.InvokeIcon method when adding the marker to the map.This method takes aBitmapDescriptorobject containing the data necessary to render the icon. TheBitmapDescriptorFactoryclass provides some helper methods to simplify the creation of aBitmapDescriptor. The following list introduces some of these methods:

  • DefaultMarker(float colour) – Use the default Google Mapsmarker, but change the colour.

  • FromAsset(string assetName) – Use a custom icon from thespecified file in the Assets folder.

  • FromBitmap(Bitmap image) – Use the specified bitmap as theicon.

  • FromFile(string fileName) – Create the custom icon from thefile at the specified path.

  • FromResource(int resourceId) – Create a custom icon fromthe specified resource.

    If you haven't already configured a KMS host, seefor steps to set one up.If you are converting a computer from a KMS host, MAK, or retail edition ofWindows to a KMS client, install the applicable setup key (GVLK) from thefollowing tables. Windows server 2008 enterprise price To use the keys listed here (which are GVLKs), you must first have a KMS hostrunning in your deployment. To install a client setup key, open an administrative commandprompt on the client, type slmgr /ipk and then press Enter. NoteIn the tables that follow, 'LTSC' stands for 'Long-Term Servicing Channel,' while 'LTSB' refers to the 'Long-Term Servicing Branch.'

The following code snippet shows an example of creating a cyan coloureddefault marker:

Info windows

Info windows are special windows that popup to display information tothe user when they tap a specific marker. By default the info windowwill display the contents of the marker's title. If the title has notbeen assigned, then no info window will appear. Only one info windowmay be shown at a time.

It is possible to customize the info window by implementing theGoogleMap.IInfoWindowAdapterinterface. There are two important methods on this interface:

  • public View GetInfoWindow(Marker marker) – This method is calledto get a custom info window for a marker. If it returns null ,then the default window rendering will be used. If this methodreturns a View, then that View will be placed inside the info windowframe.

  • public View GetInfoContents(Marker marker) – This method willonly be called if GetInfoWindow returns null . This method canreturn a null value if the default rendering of the info windowcontents is to be used. Otherwise, this method should return a Viewwith the contents of the info window.

An info window is not a live view - instead Android will convert theView to a static bitmap and display that on the image. This means thatan info window cannot respond to any touch events or gestures, nor willit automatically update itself. To update an info window, it isnecessary to call theGoogleMap.ShowInfoWindowmethod.

The following image shows some examples of some customized infowindows. The image on the left has its contents customized, while theimage on the right has its window and contents customized with rounded corners:

GroundOverlays

Unlike markers, which identify a specific location on a map, aGroundOverlayis an image that is used to identify a collection of locations or an areaon the map.

Adding a GroundOverlay

Adding a ground overlay to a map is similar to adding a marker toa map. First, aGroundOverlayOptionsobject is created. This object is then passed as a parameter to theGoogleMap.AddGroundOverlay method, which will return aGroundOverlay object. This code snippet is an example of adding aground overlay to a map:

The following screenshot shows this overlay on a map:

Lines, Circles, and Polygons

There are three simple types of geometric figures that can be added to a map:

  • Polyline - This is a series of connected line segments. It canmark a path on a map or create a geometric shape.

  • Circle - This will draw a circle on the map.

  • Polygon - This is a closed shape for marking areas on a map.

Google Api Key Generator

Polylines

A Polylineis a list of consecutive LatLng objects which specify the vertices ofeach line segment. A polyline is created by first creating aPolylineOptions object and adding the points to it. ThePolylineOption object is then passed to a GoogleMap object by callingthe AddPolyline method.

Circles

Circles are created by first instantiating aCircleOptionobject which will specify the center and the radius of the circle inmetres. The circle is drawn on the map by callingGoogleMap.AddCircle.The following code snippet shows how to draw a circle:

Polygons

Polygons are similar to Polylines, however they are not openended. Polygons are a closed loop and have their interior filled in.Polygons are created in the exact same manner as a Polyline, except theGoogleMap.AddPolygonmethod invoked.

Unlike a Polyline, a Polygon is self-closing. The polygon will be closed off by the AddPolygon method by drawing a line which connects the first and last points. The following codesnippet will create a solid rectangle over the same area as theprevious code snippet in the Polyline example.

Responding to user events

There are three types of interactions a user may have with a map:

  • Marker Click - The user clicks on a marker.

  • Marker Drag - The user has long-clicked on a mparger

  • Info Window Click - The user has clicked on an info window.

Each of these events will be discussed in more detail below.

Marker click events

The MarkerClicked event is raised when the user taps on a marker. This event accepts a GoogleMap.MarkerClickEventArgs object as a parameter. This classcontains two properties:

  • GoogleMap.MarkerClickEventArgs.Handled – This property should beset to true to indicate that the event handler has consumed theevent. If this is set to false then the default behaviour willoccur in addition to the custom behaviour of the event handler.

  • Marker – This property is a reference to the markerthat raised the MarkerClick event.

This code snippet shows an example of a MarkerClick that will changethe camera position to a new location on the map:

Marker Drag events

This event is raised when the user wishes to drag the marker. Bydefault, markers are not draggable. A marker can be set as draggable bysetting the Marker.Draggable property to true or by invoking theMarkerOptions.Draggable method with true as a parameter.

Generate Google Map Api Key Android Download

To drag the marker, the user must first long-click on the marker and then their finger must remain on the map. When the user's finger is dragged around on the screen, themarker will move. When the user's finger lifts off the screen, themarker will remain in place.

Free Google Api Key

The following list describes the various events that will be raisedfor a draggable marker:

  • GoogleMap.MarkerDragStart(object sender, GoogleMap.MarkerDragStartEventArgs e) –This event is raised when the user first drags the marker.

  • GoogleMap.MarkerDrag(object sender, GoogleMap.MarkerDragEventArgs e) –This event is raised as the marker is being dragged.

  • GoogleMap.MarkerDragEnd(object sender, GoogleMap.MarkerDragEndEventArgs e) –This event is raised when the user is finished dragging the marker.

Each of the EventArgs contains a single property called P0 that is areference to the Marker object being dragged.

Info Window Click events

Only one info window can be displayed at a time. When the user clickson an info window in a map, the map object will raise anInfoWindowClick event. The following code snippet shows how to wireup a handler to the event:

Recall that an info window is a static View which is rendered as animage on the map. Any widgets such as buttons, check boxes, or textviews that are placed inside the info window will be inert and cannotrespond to any of their integral user events.

Related Links

-->

To use the Google Maps functionality in Android, you need toregister for a Maps API key with Google. Until you do this, you willjust see a blank grid instead of a map in your applications. You mustobtain a Google Maps Android API v2 key - keys from the older GoogleMaps Android API key v1 will not work.

Obtaining a Maps API v2 key involves the following steps:

  1. Retrieve the SHA-1 fingerprint of the keystore that is used to sign the application.
  2. Create a project in the Google APIs console.
  3. Obtaining the API key.

Obtaining your Signing Key Fingerprint

To request a Maps API key from Google, you need to know theSHA-1 fingerprint of the keystore that is used to sign the application.Typically, this means you will have to determine the SHA-1 fingerprintfor the debug keystore, and then the SHA-1 fingerprint for the keystorethat is used to sign your application for release.

By default the keystore that is used to sign debug versions of aXamarin.Android application can be found at the following location:

C:Users[USERNAME]AppDataLocalXamarinMono for Androiddebug.keystore

Information about a keystore is obtained by running the keytoolcommand from the JDK. This tool is typically found in the Java bindirectory:

C:Program FilesAndroidjdkmicrosoft_dist_openjdk_[VERSION]binkeytool.exe

By default the keystore that is used to sign debug versions of aXamarin.Android application can be found at the following location:

/Users/[USERNAME]/.local/share/Xamarin/Mono for Android/debug.keystore

Generate google map api key for android

Information about a keystore is obtained by running the keytoolcommand from the JDK. This tool is typically found in the Java bindirectory:

/System/Library/Java/JavaVirtualMachines/[VERSION].jdk/Contents/Home/bin/keytool

Run keytool using the following command (using the file paths shownabove):

Debug.keystore Example

For the default debug key (which is automatically created for you fordebugging), use this command:

Generate Google Map Api Key Android Free

Production Keys

Create Google Maps Api Key Android

When deploying an app to Google Play, it must besigned with a private key.The keytool will need to be run with the private key details, and theresulting SHA-1 fingerprint used to create a production Google Maps APIkey. Remember to update the AndroidManifest.xml file with thecorrect Google Maps API key before deployment.

Keytool Output

You should see something like the following output in your consolewindow:

You will use the SHA-1 fingerprint (listed after SHA1) later in this guide.

Creating an API project

After you have retrieved the SHA-1 fingerprint of the signing keystore, it is necessary to create a new project in the Google APIs console (or add the Google Maps Android API v2 service to an existing project).

  1. In a browser, navigate to the Google Developers Console API & Services Dashboard and click Select a project. Click on a project name or create a new one by clicking NEW PROJECT:

  2. If you created a new project, enter the project name in the New Project dialog that is displayed. This dialog will manufacture a unique project ID that is based on your project name. Next, click the Create button as shown in this example:

  3. After a minute or so, the project is created and you are taken to the Dashboard page of the project. From there, click ENABLE APIS AND SERVICES:

  4. From the API Library page, click Maps SDK for Android. On the next page, click ENABLEto turn on the service for this project:

At this point the API project has been created and Google Maps Android API v2 has been added to it. However, you cannot use this API in your project until you create credentials for it. The next section explains how to create an API key and white-list a Xamarin.Android application so that it is authorized to use this key.

Obtaining the API Key

After the Google Developer Console API project has been created, it is necessary to create an Android API key. Xamarin.Android applications must have an API key before they are granted access to Android Map API v2.

  1. In the Maps SDK for Android page that is displayed (after clicking ENABLE in the previous step), go to the Credentials tab and click the Create credentials button:

  2. Click API key:

  3. After this button is clicked, the API key is generated. Next it is necessary to restrict this key so that only your app can call APIs with this key. Click RESTRICT KEY:

  4. Change the Name field from API Key 1 to a name that will help you remember what the key is used for (XamarinMapsDemoKey is used in this example). Next, click the Android apps radio button:

  5. To add the SHA-1 fingerprint, click + Add package name and fingerprint:

  6. Enter your app's package name and enter the SHA-1 certificate fingerprint (obtained via keytool as explained earlier in this guide). In the following example, the package name for XamarinMapsDemo is entered, followed by the SHA-1 certificate fingerprint obtained from debug.keystore:

  7. Note that, in order for your APK to access Google Maps, you must include SHA-1 fingerprints and package names for every keystore (debug and release) that you use to sign your APK. For example, if you use one computer for debug and another computer for generating the release APK, you should include the SHA-1 certificate fingerprint from the debug keystore of the first computer and the SHA-1 certificate fingerprint from the release keystore of the second computer. Click + Add package name and fingerprint to add another fingerprint and package name as shown in this example:

  8. Click the Save button to save your changes. Next, you are returned to the list of your API keys. If you have other API keys that you have created earlier, they will also be listed here. In this example, only one API key (created in the previous steps) is listed:

Connect the project to a billable account

Beginning June,11 2018, the API key will not work if the project is not connected to a billable account (even if the service is still free for mobile apps).

  1. Click the hamburger menu button and select the Billing page:

  2. Link the project to a billing account by clicking Link a billing account followed by CREATE BILLING ACCOUNT on the displayed popup (if you don't have an account, you will be guided to create a new one):

Adding the Key to Your Project

Finally, add this API key to the AndroidManifest.XML file of your Xamarin.Android app. In the following example, YOUR_API_KEY is to be replaced with the API key generated in the previous steps:

Related Links