What is google maps android api

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

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

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

Источник

Обзор Maps SDK для Android

С помощью Maps SDK for Android можно добавлять в приложения для Android, в том числе с Wear OS, карты на основе данных сервиса «Google Карты», а также настраивать их внешний вид и реакцию на жесты. Кроме того, вы можете опубликовать дополнительные сведения о местах на карте и обеспечить возможность взаимодействия с этими данными, добавив маркеры, многоугольники и наложения.

SDK поддерживает языки Kotlin и Java, а также библиотеки и расширения с дополнительными функциями и технологиями.

Что дальше

Как создать и настроить первое приложение:

Краткое руководство: как добавить карту Создайте простое приложение для Android, в котором есть карта. Как получить ключ API и включить возможность оплаты Узнайте, как включить возможность оплаты и получить ключ API. Оба эти действия необходимы для добавления карты в приложение. Как настроить существующий проект Android Studio Настройте существующий проект, чтобы использовать в нем Maps SDK для Android. Статистика использования и оплата Узнайте, как задать цены и лимиты на использование для SDK. Условия использования Ознакомьтесь с Условиями использования платформы Google Карт и убедитесь, что ваше приложение соответствует юридическим требованиям для работы с SDK.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Google Maps Android API v2

Integration of Google Maps with your app

Now that most of you are done with basic task in the challenge, it’s time to score the bonus points . You need to show the location data that you received from the user on the map. Alternatively, you can just open the map, let the user pinpoint the location and save the latitude & longitude of that location. So how to accomplish this ? Google provides via Google play a library for using Google Maps in your application.

First of all, let’s see what an API is —

API, an abbreviation of application program interface, is a set of routines, protocols, and tools for building software applications. The API specifies how software components should interact and are used when programming graphical user interface (GUI) components.

Before delving into the implementation details we need to make sure we have the appropriate SDKs installed to connect to Google Play Services and get the API key for Google Maps.

Читайте также:  Android как узнать трафик

1. Installing Required SDK Components

Under the Extras section in the Android SDK Manager , check if you have installed the following packages. If not , then download them.

  • Google Play Services
  • Google Repository

2. Setting Up Google Play Services

Once these packages have been installed, we must add the Google Play Services dependency to our projects build.gradle file. Open up the build.gradle file present within the module directory. Under the dependencies section add the latest version of the google-play-services library. At the time of writing, this is 6.1.71. You can find out the latest version number of the plugin, as well as many others here

3. Creating an API key for the app

  • Navigate to https://console.developers.google.com/project. Click on “Create Project”. Enter the project name and id of your choice.
  • Click on the “APIs & auth” menu on the left, and from the submenu select APIs. From the list of APIs that appear, scroll down and ensure that Google Maps Android API v2 is set to “On”.
  • Now under the same menu on the left, select “Credentials” . Under the Public API access heading, click “Create New Key”, and then “Android Key”.
  • Run the following command in your command prompt to generate your developer certificates SHA1 fingerprint key:

For Windows Users

For Mac OS or Linux Users

Take your SHA1 key, and append the apps package name to the end of it, separated by a semicolon. Paste this into the textbox and click Create.

  • You’ll see an API generated and displayed on the page. Copy the android api key to your clipboard.

4. Adding the API key in our app

In your project, open up AndroidManifest.xml. Just before the tag add the following lines of code.

5. Adding a few Permissions

Now we need to specify the permissions that our app needs. In order to use mapping functionality, we need to add the following permissions:

Google Maps Components

The map object

The key class when working with a map object is the GoogleMap class. GoogleMap models the map object within your application. Within your UI, a map will be represented by either a MapFragment or MapView object.

MapFragment

MapFragment, a subclass of the Android Fragment class, allows you to place a map in an Android fragment. MapFragment objects act as containers for the map, and provide access to the GoogleMap object.

Unlike a View, a Fragment represents a behavior or a portion of user interface in an activity. Refer to the Android documentation on Fragments to learn more.

Mapview

MapView, a subclass of the Android View class, allows you to place a map in an Android View. Much like a MapFragment, the MapView acts as a container for the map, exposing core map functionality through the GoogleMap object.

Users of this class must forward all the activity life cycle methods — such as onCreate() , onDestroy() , onResume() , and onPause() — to the corresponding methods in the MapView class.

Marker

Markers identify locations on the map. The default marker uses a standard icon, common to the Google Maps look and feel. It’s possible to change the icon’s color, image or anchor point via the API. Markers are objects of type Marker, and are added to the map with the googleMap.addMarker(markerOptions) method.

Implementation Specifics

Using the below code snippets, try to complete the task.

Adding a Map to the view

Open the xml file for the activity in which you want to view the map. Just after the basic layout opening tag add the following code.

Initialising the Map

Declare a GoogleMap object.

Now in the OnCreate( ) method of the activity, use the below code to initialise the GoogleMap instance.

Читайте также:  Как установить андроид файлы через компьютер

Setting a listener on Map Click

Remember to save the data for the clicked location. This also needs to be done in the OnCreate( ) method of the activity.

Adding a Marker

The marker is added on the location whose latitude and location are x and y respectively.

Changing Map Type

A map’s type governs the overall representation of the map. The Google Maps Android API offers four types of maps, as well as an option to have no map at all:

  • 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 also 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 will be rendered as an empty grid with no tiles loaded.

The map type can be changed by using the googleMap.setMapType() method. Here the googleMap is an instance of GoogleMap class.

Conclusion

This completes our discussion on Google Maps Android API v2 . Feel free to post any sort of doubts in the comments below or on our Facebook Group. For more resources and detailed explanation you can always refer to the following links:

Источник

Overview

Introduction

The Places SDK for Android allows you to build location-aware apps that respond contextually to the local businesses and other places near the user’s device. This means you can build rich apps based on places that mean something to the user, to complement the straightforward geographic-based services offered by the Android location services.

Concepts

The following interfaces provide the primary entry points to the Places SDK for Android:

  • Places provides programmatic access to Google’s database of local place and business information, as well as the device’s current place.
  • Autocomplete provides pre-made widgets to return place predictions in response to user search queries.

A place is defined as a physical space that has a name. Another way of thinking about a place is that it’s anything you can find on a map. Examples include local businesses, points of interest, and geographic locations. In the API, a place is represented by the Place interface. It includes information such as the name of the place and its address, geographical location, place ID, phone number, place type, website URL, and more.

API overview

Help your customers explore where they are and what’s around them:

  • Place Autocomplete automatically fills in the name and/or address of a place as users type.
  • Current Place returns a list of places where the user’s device is last known to be located along with an indication of the relative likelihood for each place.
  • Place Details return and display more detailed information about a place.
  • Place Photos returns high-quality images of a place.
  • Place IDs stores the unique ID for one or more places for retrieval of place information on demand.

Note: Google gathers anonymous usage statistics.

Policies and Terms

All applications that use the Places SDK for Android must adhere to the requirements described in the Google Maps Platform Terms of Service, Usage and Billing, and Displaying Attributions.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

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