Android adding google maps

Android adding google maps

Android Google Maps Tutorial

November 10, 2017

Google maps can be integrated into your android application using Google maps Android API which is part of Google play services API. For that, you need to include Google play services client library in your project and use Google maps Android API to implement maps feature in your app.

On the android device, Google maps Android API in your app interacts with back ground service which is part of Google play service APK and runs on OS to provide maps feature. Android devices come with Google play service APK. If Google makes any change to Google play service APK, it will be automatically updated on user device via Google play store. So this way, you can use latest maps API in your app without needing to worry about whether the user devices support the feature or not as Google play store delivers latest Google play service APK as soon as it is available.

This post covers how to add Google play services API or library to your project, enable Google maps android API in developer console, add API key to project, use Google play services maps API to show maps in your app with an example, and shows using zoom, adding marker, custom marker, circle, ploylines, polygon, info window and ground overlay to map.

Before you continue with this example, you may want to learn android and latest features with examples. Please visit android tutorials for all android concepts, components and libraries with examples which uses latest components and API.

Google Play Services SDK in Android Studio

Google Play Services SDK needs to be installed in Android Studio so that you can add to your project the library related to Google maps API. So, the first step in using Google maps Android API is to make sure that Google play service SDK is installed in android studio by opening Android SDK window and checking Google Repository under Support Repository as shown in the screen shot below. You can open Android SDK window by going to Tools > Android > SDK Manager > SDK Tools.

Adding Google maps Android API or Library to Your Project

You can add play services library which contains all Google play service APIs to your project. But, it is better to use selective API libraries so that method limitation issue will not come into picture.

Since we are going to use Google maps Android API in this example project, we will add play-services-maps to build. gradle file.

Enabling Google Maps Android API in Developers Console

To use Google maps android API in your android app, you need to enable google maps API for your project. To do that, first go to Google developer console at https://console.developers.google.com/apis/, login using your Google account, create a project by clicking create project button, then click enable APIs and services link, click Google maps android api and click enable. Below screen shot shows Google developers console dashboard where you can see create project button and enable APIs and services link.

After enabling the API, you need to create credentials. To create credentials, click credentials link in the left navigation on the Google developer console dashboard (above screen) and then click create credentials button. Copy the key to add it to your android project.

Adding API Key to Android Project

Once you followed above instructions to enable API and create API key, copy the key and add it to your android project’s manifest file by adding meta-data element as child of application element. The meta-data element name attribute should be com.google.android.geo.API_KEY and value is the key as shown below.

And also, you need to add Google play services version to android manifest file using meta-data tag with name as com.google.android.gms.version and value as version as shown below.

Google play services add the required permissions such as android.permission.INTERNET and android.permission.ACCESS_NETWORK_STATE. But if your app needs other permissions, you have to add them to manifest file, for example location permission.

Android Google Maps Example

After setup described aboved is done, you can use Google maps android API in your application. First you need to add com.google.android.gms.maps.SupportMapFragment fragment to layout. Then create map activity which implements OnMapReadyCallback interface. The interface has one method onMapReady in which you can configure GoogleMap object. In onCreate method of the activity, add map-ready-callback to map fragment.

Below example displays Google maps with a marker which identifies a location.

Layout

Activity

Android Google Maps Example Output

Android Google Maps Testing

To test your app that uses Google play services API, you can use emulator or device with any of recent versions of android and Google play store.

Android Google Maps Zoom

You can set minimum and maximum zoom on GoogleMap object by calling setMinZoomPreference and setMaxZoomPreference methods.

Android Google Maps Circle

Circle can be added to map by creating CircleOptions object and setting various configuration such as radius, fill color, stroke and latitude and longitude coordinate etc as shown below.

Android Google Maps Polyline

You can draw a line on map joining two or more locations. This is mainly used for showing routes or directions. To draw polyline on the map, you need to instantiate PolylineOptions object, add coordinates you want to join and set various options such as color, geodesic, startCap, endCap, width, and jointType etc. And add the PolylineOptions object to GoogleMap object by calling addPolyline method on it.

Читайте также:  Fahrenheit indigo prophecy для android

Android Google Maps Polygon

You can add polygon shape by defining PolygonOptions and adding it to GoogleMap by calling addPolygon method on it as shown below and screen shot show polygon on map. Polygon shape is used to represent area on map.

Android Google Maps Custom Marker

You can customize marker using MarkerOptions by adding icon and setting other attributes as shown below.

Map Types

You can display different types of Google maps in your application by calling setMapType and passing map type such as MAP_TYPE_HYBRID, MAP_TYPE_NORMAL, MAP_TYPE_SATELLITE or MAP_TYPE_TERRAIN.

Android Google Maps Ground Overlay

Ground overlay, which you can add to map, is an image tied to earth surface. The difference between marker and ground overlay is that marker is tied to screen and its orientation is not changed on rotating or tilting the map. Whereas ground overlay image changes its orientation on rotating or tilting the map.

Below screen shot shows google map in hybrid mode with ground overlay.

If you have multiple images which cover large area, you can use tile overlay.

Android Google Maps Info Window

In response to touch events of marker, you can show info window and hide info window by calling hideInfoWindow and showInfoWindow methods on Marker object. By default, info window displays title added to MarkerOptions object.

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

Google MAPs API в android или как работать с картами быстрее

Принцип работы Google MAPs API

Вся документация для работы с картами приведена на (логично) официальном сайте google maps api. Сегодня я рассматриваю только Directions API (документация). Для того что бы получить какую-либо информацию от большого числа, вам необходимо сделать запрос. Ответ прийдет в формате JSON.

Общий вид запроса:

Пример: https://maps.googleapis.com/maps/api/directions/json?origin=55.754724,%2037.621380&destination=55.728466,%2037.604155&key=»Your MAPs API key»

В качестве ответа нам (ожидаемо) пришел JSON с большим набором разных точек с координатами и названиями этих мест.

А как вообще работать с этой страшной штукой?

Если вы только начинаете работать с Android, то советую вам почитать про такую замечательную библиотеку Retrofit, которая превращает работу с запросами в код из 2 строк. Рассматривать сейчас я её не буду.

Но я сегодня хочу рассмотреть пример использования библиотеки Java Client for Google Maps Services. Библиотека как по мне замечательная, освобождает от необходимости писать (пусть даже очень короткие) запросы вручную и отлично подходит в случаях когда нужно писать очень быстро, как например на хакатоне. Я хочу показать живой пример использования данной библиотеки на примере работы с Directions API.

Подключение библиотеки

Для начала нам потребуется получить ключ для нашего приложения. Топаем на оф. сайт, находим сверху кнопку «получить ключ», создаем новый проект, нажимаем далее и готово!
UPD: теперь бесплатно получить нельзя. С лета 2018 года Google обновили план и необходимо ввести данные своей карты для получения 200$ для запросов каждый месяц бесплатно. Этого должно хватать, но конечно тенденция не радует.

Firebase
Для правильной работы приложения нам необходимо получить файл google-service.json. Идем на firebase выбираем наш проект и добавляем его. Далее нам нужно выбрать Android проект, ввести название пакета, регистрируем приложение. Скачиваем файл и перетаскиваем в папку app. К слову её не будет видно в дереве проекта, для этого надо в Android Studio поменять отображение с Android на Project или залезть в наш проект через файловый менеджер. Далее следуем инструкциям где какой код писать.

Включаем в консоли
Так же нам необходимо включить Directions API (или любую другую необходимую вам API) в консоли, для этого идем сюда, выбираем наше приложение и включаем Directions API.

Gradle
В Gradle файлы так же необходимо добавить еще пару строк. В итоге новые строки выглядят вот так:

Обязательно проверяйте, актуальная ли это сейчас версия!

Встраиваем карту в приложение

Google map в андроид реализовывается как фрагмент (или как MapView, но об этом в другой раз, нам сейчас особой разницы нет). Просто встраиваем его в наш layout. В нашем классе, который работает с картой, необходимо найти эту карту и заимплементить интерфейс.

Код для фрагмента выглядит вот так. Я буду работать с MainActivity, соответственно если вы используете другой класс вам необходимо поменять контекст.

Отлично, фрагмент встроили, Android Studio на нас не ругается, едем дальше. Переходим в MainActivity.class и имплементим интерфейс OnMapReadyCallback.

В onCreate пишем

Так же идем в Manifests и прописываем вот такие штуки внутри тэга application

Где вместо @string/google_maps_key должен подставиться ваш ключ для карт, который мы получили ранее. Соответственно вам нужно создать нужный ресурс в файле string.

Пишем всякие интересности

Отлично, карта у нас есть, давайте наконец напишем хоть что-нибудь интересное. Пусть нашей целью будет нарисовать маршрут по Москве через несколько точек:

  • Гум (55.754724, 37.621380)
  • Большой театр (55.760133, 37.618697)
  • Патриаршие пруды (55.764753, 37.591313)
  • Парк культуры (55.728466, 37.604155)

Кладу все наши места в List и делаю это как глобальную переменную.

Для начала создадим по маркеру на каждое место. Маркер это просто объект, которому передаются координаты, а затем они накладываются на карту. Код:

Далее мы пишем вот такой код все в том же методе onMapReady

При запуске приложения мы получили вот такую картину:

Хм, Москва, конечно, весьма запутанная, но не настолько же. Почему же такой странный маршрут нам вернул Google? Потому что он построил маршрут для автомобилей, который идет по умолчанию, но мы можем это изменить. Чтобы построить маршрут для пешеходов, меняем код на:

Теперь наш маршрут выглядит вот так

Существует еще множество настроек, о всех них можно прочитать в документации. Просто мы все параметры будем добавлять не в сырой запрос, а в код, поскольку методы библиотеки имеют те же названия что и просто в запросах.

Источник

Adding Maps to an Android App with Google Play Services

In the past, traveling to a new or unfamiliar location typically required you to carry around a local map and/or ask locals for directions. Getting lost is becoming a thing of the past, as we can conveniently carry in our pockets a map of not just the whole planet, but one that will show you where you are, give directions to where you want to go, the estimated time it will take to get there, let you mark points of interest and save them for later, enable you to search for places that are close by and much more.

Читайте также:  Android close this application

In this article, we’ll look at the Google Maps Android API which enables you to add maps based on Google Maps to your application. The API automatically handles access to Google Maps servers, data downloading, map display, and response to map gestures. You can use the API calls to add markers, polygons, and overlays to a basic map and to change the user’s view of a particular map area. These objects provide additional information for map locations and allow user interaction with the map.

We’ll create an application that will show some of the features available in the API. We won’t cover everything as that would take several posts, but we will cover common features like adding a map to the view, changing the map type, adding a marker to the map to mark a location and configuring the camera which will affect how the user sees a map.

The completed project can be downloaded here.

Get an API Key

To use the Google Maps Android API, you must register your app project on the Google Developers Console and get a Google API key to add your app.

The API key is based on a short form of your app’s digital certificate, known as its SHA-1 fingerprint. While you’re developing and testing, you should use a debug certificate (which we’ll cover shortly), but when publishing the app, you have to use a release certificate (you can find instructions for generating a release certificate here).

The Android SDK tools generate a debug certificate automatically when creating a debug build for the first time, so all we have to do is retrieve it. The file is named debug.keystore and by default, it’s stored in the same directory as your Android Virtual Device (AVD) files:

    OS X and Linux:

/.android/

  • Windows: C:\Users\yourusername.android\
  • To see details of the certificate, run the following:

    Linux or OS X

    Windows

    The Terminal will show the MD5 and SHA1 certificate fingerprints, we want the SHA1. Keep the Terminal window open and head over to the to the Google Developer Console. Click the Create Project button to create a new project and name it SP Map Demo .

    You will be taken to the project’s dashboard, in the center of the screen click ‘Use Google APIs’.

    Select Google Maps Android API and click the Enable API button that appears on the next page.

    After the API is enabled, click Go to Credentials, from the left panel.

    From the Add Credentials menu , select API Key.

    Select Android Key.

    In the next dialog, you can change the key name but I left it as the default Android key 1

    Use the Add package name and fingerprint button to add your app’s package name (I used com.echessa.mapdemo01 ) and your SHA1 fingerprint. After clicking the Create button, you will be shown an API key that we will use in our app.

    In Android Studio, create a new project, I named mine MapDemo01. Make sure it has a package name that corresponds with what you used when generating a key on the Google Developer Console, otherwise you will have to edit the package name in the Developer Console to match your app.

    Select API 15 as the Minimum SDK version. In the next window, select Empty Activity (Blank Activity if you are using Android Studio version 1.3 or earlier). Leave the last window as default and click Finish.

    Adding a Map

    Add the following to the build.gradle (Module: app) file and sync gradle.

    In the manifest file, add the following as a child of the application tag. Replace your API key in the value attribute.

    Add the following as a child of the manifest element in the manifest file.

    The Google Maps Android API uses OpenGL ES version 2 to render the map. If OpenGL ES version 2 is not installed, your map will not appear. It’s recommended to include the above code in the manifest file which notifies external services of the requirement. In particular, it prevents the Google Play Store from displaying your app on devices that don’t support OpenGL ES version 2.

    Note: In previous versions of the Google Play Services API, you had to include external storage and internet permissions in the manifest file, this is no longer the case.

    If you’re targeting version 8.3 or later of the Google Play services SDK, you no longer need the WRITE_EXTERNAL_STORAGE permission to use the Google Maps Android API.

    If you’re targeting earlier versions of the Google Play services SDK, you must request the android.permission.WRITE_EXTERNAL_STORAGE permission.

    If your app is targeting API level 23 (Android 6.0), which requires the use of runtime permissions, you should target version 8.3 or later of the Google Play services SDK.

    The following permissions are defined in the Google Play services manifest, and are automatically merged into your app manifest at build time. You don’t need to add them explicitly to your manifest:

    • android.permission.INTERNET : Used by the API to download map tiles from Google Maps servers.
    • android.permission.ACCESS_NETWORK_STATE : Allows the API to check the connection status to determine whether data can be downloaded.

    Maps are represented in the API by the GoogleMap and MapFragment classes.

    To add a map to your app, add a Fragment object to the Activity that will handle the map. You can do this in code or XML layout files. We’ll use the latter method.

    Change activity_main.xml as below:

    Above we added a fragment to the activity and set its android:name attribute to com.google.android.gms.maps.MapFragment . This attaches a MapFragment to the activity. If you need to support older devices, instead use com.google.android.gms.maps.SupportMapFragment from the support library.

    Run the app and you should see a map embedded on the view.

    The default map view shows a view of the earth with the camera centered at the equator and perpendicular to the surface. You can configure the initial state of the map, changing settings such as the camera position (including: location, zoom, bearing and tilt), the map type, including the zoom or compass buttons on screen, the gestures a user can use to manipulate the camera, whether lite mode is enabled (a bitmap image of a map that supports a subset of the functionality supplied by the full API).

    You can configure the initial state of the map either via XML or programmatically.

    Update the fragment in activity_main.xml:

    Run the app to see the changes to the initial state of the map.

    Читайте также:  Android уведомления день рождения

    Above we included settings for the camera position such as location, zoom, bearing and tilt. cameraBearing sets the direction in which a vertical line on the map points, measured in degrees clockwise from north. cameraTargetLat and cameraTargetLng sets the location of the center of the map. cameraTilt sets the camera’s position on an arc between directly over the map’s center position and the surface of the Earth. cameraZoom determines the scale of the map, at larger zoom levels more detail can is on the screen, while at smaller zoom levels more of the world is on the screen.

    We set the mapType to normal which is the default map type. The other available options are outlined below.

    • Normal: Typical road map. Roads, some man-made features, and important natural features such as rivers are shown. Road and feature labels are also visible.
    • Hybrid: Satellite photograph data with road maps added. Road and feature labels are visible.
    • Satellite: Satellite photograph data. Road and feature labels are not visible.
    • Terrain: Topographic data. The map includes colors, contour lines and labels and perspective shading. Some roads and labels are also visible.
    • None: No tiles. The map is rendered as an empty grid with no tiles loaded.

    The last set of settings determine whether the compass and zoom control appear on the screen and enable/disable some gestures.

    The last attribute tools:ignore=»MissingPrefix» is not part of the MapView settings, but it gets rid of an error message (Unexpected namespace prefix map found for tag fragment) Android Studio shows for attributes that begin with the map: property. The project will still build and run despite Android Studio showing an error. According to this Gmaps bug report page, the problem seems to be a bug with the Android Lint tool. You can disable Lint checking, but since it’s useful in finding bugs, a better solution is to ignore the lint issue for specific tags, like we do for the fragment tag. The tools:ignore attribute can be set on any XML element, and is a comma separated list of lint issue ID’s to ignore on this element or any of its children, recursively.

    Setting the Map State Programmatically

    We’ve seen how to set the initial state of the map using the XML layout files, next we’ll look at how to do the same in code.

    Change activity_main.xml as shown below to only include the basic MapFragment . We’ll add more configuration to the map in code.

    In MainActivity , we’ll implement the OnMapReadyCallback interface and use the onMapReady callback method to get a handle to the GoogleMap object. The GoogleMap object is the internal representation of the map itself. To set the view options for a map, change its GoogleMap object.

    Change the class definition:

    Add the onMapReady callback method.

    The above gets the GoogleMap object and sets the map type and the camera position, then it moves the camera to that position.

    Add the following to the end of onCreate() . We call getMapAsync() on the fragment to register the callback.

    Run the app and you should see the map with the configuration set.

    You can use animateCamera() instead of moveCamera() to get a nice effect of the camera moving into place as the map loads.

    Adding Markers on the Map

    You can add markers to the map to show single locations. You can customize the markers by changing the default color, or replacing the marker icon with a custom image. You can also add info windows which provide additional context to a marker.

    Add the following to onMapReady() after the statement that initializes the CameraPosition object.

    Here, we’ve created three markers. The first has a custom icon while the rest will have the default icon. The second marker uses snippet() to display more data in the Info Window when the marker is tapped. The other two will only display the title text.

    Run the app to see the changes. I commented out the statement that sets the map type, so that it defaults to normal .

    Showing the User’s Current Location

    Your app might need to show a user’s location on the map. You can do this either by using the Google Play services Location API or by using the ‘My Location’ layer and the ‘My Location’ button to display the user’s current location on the map.

    The ‘My Location’ layer provides a simple way to display a device’s location on the map. To use this, you need location permission.

    Add the following permission to the manifest file.

    Here we ask for coarse location data, but for more accuracy you can ask for fine data.

    For Android Marshmallow support, you need to use the runtime location permission. To keep this article short, we won’t go into runtime permissions, but the link above shows how to do that.

    Add the following to onMapReady() after the code that creates the markers.

    Run the app and you should see the My Location button on the top right corner of the map view. On tapping the button, the camera centers the map on the current location of the device, if known. The location is indicated on the map by a small blue dot if the device is stationary, or as a chevron if the device is moving.

    The My Location layer does not return any data. If you wish to access location data programmatically, you should use the Google Play Services Location API.

    The Google Play services Location API is the preferred method for adding location awareness to your Android application. It has other functionality not provided by the ‘My Location’ layer that lets you:

    • Determine the device location.
    • Listen for location changes.
    • Determine the mode of transportation, if the device is moving.
    • Create and monitor predefined geographical regions, known as geofences.

    We have already covered how to use the Google Play Services Location API, so won’t cover it here.

    Conclusion

    We’ve just touched on the capability of the Google Maps API, there are plenty more features it offers, including displaying heatmaps, drawing shapes on the map, converting KML (an extension of the XML data format) objects into geographical shapes and rendering them as a layer on top of a map and much more. For more on the API, check out the documentation.

    Источник

    Оцените статью