Android using google maps

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? Потому что он построил маршрут для автомобилей, который идет по умолчанию, но мы можем это изменить. Чтобы построить маршрут для пешеходов, меняем код на:

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

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

Источник

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

Читайте также:  Witcher trainer silver mod rus android

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.

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.

Источник

Getting Started With Google Maps for Android: Basics

Introduction

Without a doubt, maps are one of the most useful tools for users when included in an app. This tutorial is the first in a series going over Google Maps v2 for Android. It will cover setting up the Google Maps API through the Google Developer Console, including a map fragment in your applications, displaying the user’s location, adding markers, drawing on the map, and some general methods that will add utility to your app. All code for this tutorial can be found on GitHub.

1. Setting Up the Developer Console

In order to use the Google Maps API, you must register your application on the Google Developer Console and enable the API. To do this, start by going to the Google Developer Console. If you already have a project created, you can skip the next section. If not, you can follow along and create a new project for your maps application.

Читайте также:  Power master для андроид

Step 1: Creating a Project

To create a new project, click on the blue Create Project button in the top left corner of the screen. If you don’t see a Create Project button, then look for a button labeled Create an empty project.

This presents you with a dialog that asks for a project name. For this tutorial, I have created a project called TutsPlusMaps. There are some restrictions on what you can name your project as only letters, numbers, quotes, hyphens, spaces, and exclamation points are allowed characters.

Once you hit Create, a dialog appears in the lower right corner of the page with a loading indicator while the project is being created.

Step 2: Enabling the Maps API

When the project has been created, or you have selected an existing project, you are taken to the project Overview screen. From here you will want to expand the APIs & auth item in the left navigation panel and click on APIs.

While there’s a search box on this screen, you’ll notice that Google placed the Maps API items at the top of the center column for developers to access. For this tutorial, click on the item titled Google Maps Android API under the Google Maps APIs heading.

This takes you to a screen where you can click on the blue Enable API button in order to enable the Maps API for your project.

Step 3: Creating an Android API Key

After you’ve enabled the Maps API, click on the Credentials item under APIs & auth in the side navigation to get a key to access the Maps API in your application. When you are presented with the Credentials dialog, press the blue Add Credentials button and select API Key.

Since this is an Android application, you need to select Android Key in the next dialog. If you were to create the same application using maps on different platforms, you could create a key for each platform.

On the next screen, click Add package name and fingerprint. This provides two fields, one for adding a package name and another for adding the SHA1 from your application signing key.

For this tutorial, I will use the package name com.tutsplus.mapsdemo. To get the SHA1 signature, you need to open a terminal or command prompt and navigate to the location of your application’s signing key. This can be either your release key or debug.keystore. You can generate the SHA1 with the following command:

After you have created your SHA1 key and entered it into the text field, click on the blue Create button. You are then presented with a dialog containing the API key that you need to add to your Android app to access the Maps API.

2. Setting Up the Android Project

At this point, you can create the initial Android project with the same package name that you used for creating the API key. Once your project is created, open the build.gradle file. You need to import the Play Services library for maps. In this example, you also need to import the locations Play Services library in order to set an initial position for your map. Place the following lines into the dependencies node of the build.gradle file.

Once you have your libraries imported, you can close build.gradle and open your AndroidManifest.xml file. Above the application node, you need to declare that the application uses OpenGL ES 2.0 and define the permissions needed by your application.

Note that the ACCESS_FINE_LOCATION permission is only required for this demo in order to get the user’s location for defining where the map should initially display. If you have a known location in your own app, there’s no need to use the user’s location.

Within the application node, you need to add two pieces of metadata. The first informs the application that Play Services are used and the second binds the Maps API key with your application. In the following code snippet, @string/google_api_key is a string reference to the key from the Google Developer Console.

Once you’ve finished updating AndroidManifest.xml, go ahead and close the file. Next, you need to create a new Java class, called MapFragment , which extends SupportMapFragment . SupportMapFragment is used here rather than com.google.android.gms.maps.MapFragment in order to add backwards compatibility before API 12.

If your app does not need to support devices running older versions of Android, then it is fine to use com.google.android.gms.maps.MapFragment . Once you have the base fragment created, you need to implement the six interfaces that we will use for this demo.

  • ConnectionCallbacks and OnConnectionFailedListener are designed to monitor the state of the GoogleApiClient , which is used in this application for getting the user’s current location.
  • OnInfoWindowClickListener is triggered when the user clicks on the info window that pops up over a marker on the map.
  • OnMapLongClickListener and OnMapClickListener are triggered when the user either taps or holds down on a portion of the map.
  • OnMarkerClickListener is called when the user clicks on a marker on the map, which typically also displays the info window for that marker.

When prompted, click on the red lightbulb that appears next to the class name to add the methods required for these interfaces.

Once you have the initial fragment built, you need to let MainActivity know that it should use this fragment. Open activity_main.xml from your resources folder and change it so that it includes the fragment as a view.

After updating your activity layout, you should be able to run your application and view a map of Earth that is fully zoomed out and focused on latitude 0, longitude 0.

3. Initializing the Map

Step 1: Declaring Map Types

Returning to our MapFragment class, you need to define some global values at the top of the class for use in your application.

Here mGoogleApiClient and mCurrentLocation are used for getting the user’s location for initializing the map camera. MAP_TYPES and curMapTypeIndex are used in the sample code for switching between different map display types. Each of the map types serves a different purpose, so one or more may be suitable for your own applications.

GoogleMap.MAP_TYPE_SATELLITE displays a satellite view of the area without street names or labels.

GoogleMap.MAP_TYPE_NORMAL shows a generic map with street names and labels.

Читайте также:  Как усилить сигнал андроид своими руками

GoogleMap.MAP_TYPE_HYBRID combines satellite and normal mode, displaying satellite images of an area with all labels.

GoogleMap.MAP_TYPE_TERRAIN is similar to a normal map, but textures are added to display changes in elevation in the environment. These textures are most visible when the map is angled with a two-finger drag.

GoogleMap.MAP_TYPE_NONE is similar to a normal map, but doesn’t display any labels or coloration for the type of environment in an area. It does allow for displaying traffic and other overlays on the map.

Step 2: Creating the API Client

Next, you need to create your GoogleApiClient and initiate LocationServices in order to get your user’s current location. As I mentioned before, if you have a set location that you want to display rather than focusing on the user, you can skip using LocationServices .

The initListeners method binds the interfaces that you declared at the top of the class with the GoogleMap object associated with SupportMapFragment . This is what the implementation looks like:

You may have noticed that the GoogleApiClient and listeners are created and bound from onViewCreated rather than the typical onCreate . This is because the GoogleMap object has not been initialized when onCreate is called, so we need to wait until the view is fully created before trying to call getMap in order to avoid a NullPointerException .

Step 3: Configuring the Map

Since you will set up the map camera after the user’s location has been found through Play Services, we will use the Play Services lifecycle to drive initializing our map. You can connect the GoogleApiClient in onStart . When the client has connected, you can grab the user’s most recently retrieved location and use that for aiming the map camera.

In the initCamera method, you initialize the camera and some basic map properties. You start by creating a CameraPosition object through the CameraPosition.Builder , with a target set for the latitude and longitude of your user and a set zoom level.

Tilt and bearing are used here at their default values to illustrate that they are available options. Once you have a CameraPosition object, you can animate the map camera to that position using the CameraUpdateFactory .

At the end of this method, you’ll notice the last four lines set some properties for the map. You set the map type, as described earlier in this tutorial, and enable live traffic flow overlays in the first two lines. setMyLocationEnabled adds a button to the top right corner of the MapFragment that automatically moves the camera to your user’s location when pressed.

Finally calling setZoomControlsEnabled adds + and buttons in the lower right corner, allowing the user to change the map zoom level without having to use gestures. There’s a few more interesting things that you can set using UiSettings , such as adding a compass or disabling gestures, which you can find in the Android reference documentation.

4. Marking Locations

One of the most used map features involves indicating locations with markers. Since a latitude and longitude are needed for adding a marker, you need to use the OnMapClickListener to allow the user to pick a spot on the map to place a Marker object.

This method creates a generic red marker where the user has tapped. Additional options, such as setting a marker as draggable, can be set through the MarkerOptions object. You can find additional attributes in the official Android reference documentation. If you want to change the color of the marker, you can call BitmapDescriptorFactory.defaultMarker when adding an icon to the MarkerOptions . The defaultMarker method accepts a float value that defines the hue. The hue can either be set manually or as a predefined static value from BitmapDescriptorFactory . It should be noted that addMarker returns a Marker object, which can be stored for manually removing specific markers if needed.

If you want to avoid using the generic colored pins for your location markers, you can set a bitmap as the icon on the MarkerOptions object. To demonstrate this, you override the onMapLongClick method so that it uses the app icon from the resources folder as a Marker when your user long-presses the map.

You’ve probably noticed that the getAddressFromLatLng method is being used in both click methods. This is a helper method that takes a LatLng and runs it through a Geocoder to get a street address. In the last two examples, we are using this method to display a street address when a marker is tapped.

5. Drawing on the Map

The GoogleMap object has a set of methods that make it easy to draw shapes and place images onto the map. To draw a simple circle, you only need to create a CircleOptions object, set a radius and center location, and define the stroke/fill colors and size.

Once you have a CircleOptions object, you can call addCircle to draw the defined circle on top of the map. Just like when placing markers, objects that are drawn on the map return an object of the drawn item type so it can be referenced later if needed.

To draw a different closed-off shape, you can take multiple LatLng points and create a PolygonOptions object. As you can see below, PolygonOptions are created in a similar fashion to CircleOptions . Instead of using a center and radius method, you use add with a list of points. You can then call addPolygon to draw the shape. For this example, you simply draw a triangle onto the map.

The final type of drawing you will learn about is adding an image as an overlay on the map. Overlays can be handy if you have a drawn map for an area that you want to display on top of a normal map type. This can be achieved by creating a GroundOverlayOptions with a set location, width and height, and the image that you want to use as a BitmapDescriptor .

In the following method, you draw the launcher icon for the app as an overlay on the map tiles.

Conclusion

In this tutorial, you have learned how to create an API key and enable Google Maps for Android. You also learned about the MapFragment class and some of the basic features you can activate for a map.

You’ve learned how to place markers, listen for interactions with the map, and how to draw on the map to display additional information.

In the next tutorial of this series, you will learn how to overlay a View over the MapFragment , how to interact with indoor level maps, and how to show a street view to your users.

Источник

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