- Google MAPs API в android или как работать с картами быстрее
- Принцип работы Google MAPs API
- А как вообще работать с этой страшной штукой?
- Подключение библиотеки
- Встраиваем карту в приложение
- Пишем всякие интересности
- Setup Instructions
- Download the library with dependencies
- Android
- Google App Engine
- Servlet
- Generic Java
- Generated libraries for Google APIs
- Maven
- Modules
- google-api-client
- google-api-client-android
- google-api-client-servlet
- google-api-client-appengine
- google-api-client-gson
- google-api-client-jackson2
- google-api-client-java6
- google-api-client-protobuf
- google-api-client-xml
- Android google api jar
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? Потому что он построил маршрут для автомобилей, который идет по умолчанию, но мы можем это изменить. Чтобы построить маршрут для пешеходов, меняем код на:
Теперь наш маршрут выглядит вот так
Существует еще множество настроек, о всех них можно прочитать в документации. Просто мы все параметры будем добавлять не в сырой запрос, а в код, поскольку методы библиотеки имеют те же названия что и просто в запросах.
Источник
Setup Instructions
If you are not using a generated library, you can download the Google API Client Library for Java and its dependencies in a zip file, or you can use Maven.
Also see the ProGuard setup instructions that are part of the Google HTTP Client Library for Java documentation.
Download the library with dependencies
Download the latest zip file, which you can find on the downloads page, and extract it on your computer. This zip file contains the client library class jar files and the associated source jar files for each artifact and its dependencies. You can find dependency graphs and licenses for the different libraries in the dependencies folder. For more details about the contents of the download, see the readme.html file.
Android
If you are developing for Android, and the Google API you want to use is included in the Google Play Services library, use the Google Play Services library for the best performance and experience.
If you are using the Google API Client Library for Java with Android, it is important to know which dependencies are compatible with Android, specifically which Android SDK level. Android applications require the following jar files, or newer compatible versions, from the libs folder:
Google App Engine
Google App Engine applications require the following jar files, or newer compatible versions, from the libs folder:
- google-api-client-1.32.1.jar
- google-api-client-appengine-1.32.1.jar
- google-api-client-servlet-1.32.1.jar
- google-oauth-client-1.31.5.jar
- google-oauth-client-appengine-1.31.5.jar
- google-oauth-client-servlet-1.31.5.jar
- google-http-client-1.39.2.jar
- google-http-client-appengine-1.39.2.jar
- gson-2.8.7.jar
- jackson-core-2.12.4.jar
- jdo2-api-2.3-eb.jar
- jsr305-3.0.2.jar
- protobuf-java-3.17.2.jar
- transaction-api-1.1.jar
- xpp3-1.1.4c.jar
Servlet
Servlet applications require the following jar files, or newer compatible versions, from the libs folder:
- google-api-client-1.32.1.jar
- google-api-client-servlet-1.32.1.jar
- google-oauth-client-1.31.5.jar
- google-oauth-client-servlet-1.31.5.jar
- google-http-client-1.39.2.jar
- commons-logging-1.2.jar
- gson-2.8.7.jar
- httpclient-4.5.13.jar
- httpcore-4.4.12.jar
- jackson-core-2.12.4.jar
- jdo2-api-2.3-eb.jar
- jsr305-3.0.2.jar
- protobuf-java-3.17.2.jar
- transaction-api-1.1.jar
- xpp3-1.1.4c.jar
Generic Java
General purpose Java applications require the following jar files, or newer compatible versions, from the libs folder:
- google-api-client-1.32.1.jar
- google-oauth-client-1.31.5.jar
- google-http-client-1.39.2.jar
- google-http-client-jackson2-1.39.2.jar
- commons-logging-1.2.jar
- gson-2.8.7.jar
- httpclient-4.5.13.jar
- httpcore-4.4.12.jar
- jackson-core-2.12.4.jar
- jsr305-3.0.2.jar
- protobuf-java-3.17.2.jar
- xpp3-1.1.4c.jar
Generated libraries for Google APIs
Maven
The Google API Client Library for Java is in the central Maven repository. The Maven groupId for all artifacts for this library is com.google.api-client . Specific Maven instructions are given for each module (below).
Modules
This library is composed of nine modules:
google-api-client
The Google API Client Library for Java (google-api-client) is designed to be compatible with all supported Java platforms, including Android.
On Android, you will need to explicitly exclude unused dependencies:
google-api-client-android
Extensions to the Google API Client Library for Java (google-api-client-android) support Java Google Android (only for SDK >= 2.1) applications. This module depends on google-api-client and google-http-client-android.
google-api-client-servlet
Servlet and JDO extensions to the Google API Client Library for Java (google-api-client-servlet) support Java servlet web applications. This module depends on google-api-client and google-oauth-client-servlet.
google-api-client-appengine
Google App Engine extensions to the Google API Client Library for Java (google-api-client-appengine) support Java Google App Engine applications. This module depends on google-api-client, google-api-client-servlet, google-oauth-client-appengine and google-http-client-appengine.
google-api-client-gson
GSON extensions to the Google API Client Library for Java (google-api-client-gson). This module depends on google-api-client and google-http-client-gson.
google-api-client-jackson2
Jackson2 extensions to the Google API Client Library for Java (google-api-client-jackson2). This module depends on google-api-client and google-http-client-jackson2.
google-api-client-java6
Java 6 (and higher) extensions to the Google API Client Library for Java (google-api-client-java6). This module depends on google-api-client and google-oauth-client-java6.
google-api-client-protobuf
Protocol buffer extensions to the Google API Client Library for Java (google-api-client-protobuf). This module depends on google-http-client-protobuf and google-api-client.
google-api-client-xml
XML extensions to the Google API Client Library for Java (google-api-client-xml). This module depends on google-api-client and google-http-client-xml.
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.
Источник
Android google api jar
Google Drive API with Android
There are many ways to upload images and files. Also, there are many places from which to uploads files: Dropbox, local storage on the device, Google Drive and other services. In this tutorial, we are going to take a look at how to upload and create a file in Google Drive. To do so we need to Google Drive SDK and Google Authentication Base on Google Drive Rest API we are going to do that.
Okay, it’s enough to talk about it 😎 Let’s get into it,
Start a new Android Studio project from the startup screen or New Project then select Empty Activity’ from the Choose Project` box.
Enter the name drive-rest-sample company domain and a project location. Make sure to Choose Language Java.
And Click Finish .
Registering for Google Drive
As we discuss we need to Google Drive SDK, So in order to use it, we need to enable that API. Okay don’t worry we will move forward step by step
- Go to Google Console.
- Sign up for a developer account if We don’t have or then sign in.
- Create a project Or Select and click continue from below,
- After creating a project we have Dashboard like below,
- Now, Select Library on the left-hand side to go to the Search screen
- Type “Google Drive” and select Google Drive API.
- Select Enable. Then It looks like below,
- Back to Dashboard, from Dashboard left-hand side go to Credentials. Create Credential by selecting the OAuth client ID like below
Tt navigates to the Create OAuth client ID page. Select our Application Type Android .
- Now we need your SHA-1 Signing-certificate fingerprint key. Do so follow below steps
- Copy the keytool text (press the Copy icon) and paste it into a terminal.
- Change the path-to-debug-or-production-keystore to your default debug keystore location:
- On Mac or Linux,
/.android/debug.keystore .
Notes: If throwing error to generate singing key then it might be keystore not found.
I used an alternative command for my machine MAC OS .
If everything works correctly, you should see something like this:
- Copy the SHA1 value from the terminal into the text field and press Create. The Client ID dialog will appear. Press OK.
- Finally, enter a name and the package name that we used to create our app . Although the hint refers to the package name in AndroidManifest.xml , it has to match the applicationId in build.gradle instead — otherwise, the login flow will fail.
- We don’t need to complete the form that appears, it’s optional so press Save and move on.
Optional, Now, In the Credentials page. Authorization on Android uses the SHA1 fingerprint and package name to identify your app , so you don’t have to download any JSON file or copy any API key or secret to our project.
It about lots man, Don’t worry! Now, are in the fun part 😎 .
Let’s Back to — Android Studio
1.Add those permission in ‘AndroidManifest.xml’ file
2.update build.gradle file
3.create ‘DriveServiceHelper.java’ helper class
The returned list will only contain files visible to this app, i.e. those which were * created by this app. To perform operations on files not created by the app, the project must * request Drive Full Scope in the Google * Developer’s Console and be submitted to Google for verification.
- Now open up ‘activity_main.xml’ file
👌 Congratulations!. & Thank You! If you have any issues and queries,Feel Free To Comment.
Источник