-->

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:

Generate a Google maps API key. In order to use Google maps on your site, you need an API key. Let’s see how we can get one. Navigate to the Google API Console you will see this. Select whether you want to receive updates on the product or not, check the terms radio button and click the Agree and continue button. Next is the Credentials screen. Demonstrates how to get a Google Maps API key for Android app development using Windows 7 and Eclipse. I recommend you watch this in ADDITION to the Android-Google. Aug 27, 2017 If you want to use Google Maps in your Xamarin.Android app, you will need to obtain an API key. It’s easy to generate an API Key, but we will also want to restrict it’s usage, so that only your app can use it. This alleviates the security concern of placing the API Key in your. These are the steps I am following to generate my map key for android: 1-) I execute this command: keytool -list -v -alias androiddebugkey -keystore /.android/debug.keystore -storepass android. Nov 23, 2018  Android Studio would automatically generate an XML file named with googlemapsapi.xml You would get debug SHA1 key here (at line number 10 of the XML file) Generate Key Hash for Facebook.

  • 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. Sucuri won't generate free api key.

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. 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

Can i generate private key from certificate. 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.

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.

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.

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.

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

Android provides facility to integrate Google map in our application. Google map displays your current location, navigate location direction, search location etc. We can also customize Google map according to our requirement.

Android Google Map Generate Key File

Types of Google Maps

There are four different types of Google maps, as well as an optional to no map at all. Each of them gives different view on map. These maps are as follow:

  1. Normal: This type of map displays typical road map, natural features like river and some features build by humans.
  2. Hybrid: This type of map displays satellite photograph data with typical road maps. It also displays road and feature labels.
  3. Satellite: Satellite type displays satellite photograph data, but doesn't display road and feature labels.
  4. Terrain: This type displays photographic data. This includes colors, contour lines and labels and perspective shading.
  5. None: This type displays an empty grid with no tiles loaded.

Syntax of different types of map

Methods of Google map

Google map API provides several methods that help to customize Google map. These methods are as following:

MethodsDescription
addCircle(CircleOptions options)This method add circle to map.
addPolygon(PolygonOptions options)This method add polygon to map.
addTileOverlay(TileOverlayOptions options)This method add tile overlay to the map.
animateCamera(CameraUpdate update)This method moves the map according to the update with an animation.
clear()This method removes everything from the map.
getMyLocation()This method returns the currently displayed user location.
moveCamera(CameraUpdate update)This method reposition the camera according to the instructions defined in the update.
setTrafficEnabled(boolean enabled)This method set the traffic layer on or off.
snapshot(GoogleMap.SnapshotReadyCallback callback)This method takes a snapshot of the map.
stopAnimation()This method stops the camera animation if there is any progress.

Example of Google Map

Let's create an example of Google map integrating within our app. For doing this we select Google Maps Activity.

Copy the URL from google_map_api.xml file to generate Google map key.

Paste the copied URL at the browser. It will open the following page.

Click on Create API key to generate API key.

After clicking on Create API key, it will generate our API key displaying the following screen.

Copy this generated API key in our google_map_api.xml file

activity_maps.xml

MapsActivity.java

To get the GoogleMap object in our MapsActivity.java class we need to implement the OnMapReadyCallback interface and override the onMapReady() callback method.

Required Permission

Android Google Map Key Generation

Add the following user-permission in AndroidManifest.xml file.

AndroidManifest.xml

build.gradel

Add the following dependencies in build.gradel file.

Google Maps App For Android

Output

Generate Google Map Key For Android Apps