- Карты Google и Просмотр улиц (StreetView)
- Запуск приложения для работы с картами при помощи намерения
- Просмотр улиц (Google StreetView)
- Google Maps Intents for Android
- Overview
- Intent requests
- Kotlin
- Kotlin
- Kotlin
- URL encoded query strings
- Kotlin
- Displaying a map
- Kotlin
- Searching for a location
- Categorical search
- Kotlin
- Kotlin
- Location search
- Kotlin
- Kotlin
- Kotlin
- Kotlin
- Kotlin
- Launching turn-by-turn navigation
- Kotlin
- Kotlin
- Kotlin
- Kotlin
- Displaying a Street View panorama
- Kotlin
Карты Google и Просмотр улиц (StreetView)
На большинстве стандартных телефонов и планшетов есть программа Карты Google. Мы можем из своего приложения запустить эту программу с различными настройками.
Если вы будете тестировать примеры на эмуляторе, то вам необходимо использовать виртуальное устройство с поддержкой Google APIs.
Запуск приложения для работы с картами при помощи намерения
Запускается программа стандартным способом через намерение. Допустим, у нас есть кнопка и код для щелчка будет следующим:
Приложение Карты Google понимает специальный формат:
Первая строчка принимает два параметра: широту и долготу. Вторая строчка дополнительно имеет параметр масштабирования от 2 до 23 (2 — четверть планеты, 23 — максимальное приближение, например, крыша дома, на которой встречаются коты и кошки).
В нашем примере для широты использовалось значение 0 — это экватор. Про долготу рассказывать не буду — не надо было в школе прогуливать уроки географии.
Имея нужные данные и зная необходимый формат, мы можем сформировать задание на запуск приложения для работы с картами. Как правило, на Android-телефонах это программа Карты (Maps). Если у вас на телефоне установлены и другие карты (Яндекс.Карты, iGo), то сначала появится диалоговое окно, где пользователю будет предложено выбрать в каком приложении должна быть показана заданная точка.
Запустив приложение и нажав на кнопку, который отвечает за данный код, мы запустим приложение, отвечающее за карты, и окажемся в нужном месте где-то в районе Ховрино (Москва).
Говорят, коты имеют встроенный GPS и им легко разобраться в координатах. Недаром они так ловко находят дорогу домой, даже если их потеряли за сотни километров. Но мы с вами такими способностями не обладаем и точно сказать координаты своего дома не можем.
Впрочем, совсем не обязательно знать точные координаты местоположения объекта. Можно поступить проще. Существует ещё один формат:
В этом случае мы можем не указывать координаты, а просто попросить у карт найти такую-то точку. Предположим, мы решили найти Бельгию и с перепугу дали запрос на французском языке:
Карты достаточно умны, чтобы понять ваш запрос и покажет территорию Бельгии. Впрочем, на русском он тоже понимает. Как видите, в этом случае мы передаём нулевые координаты и добавляем к ним запрос ?q=.
Также можно указать и уровень масштабирования:
Хотите увидеть Париж и умереть? Можете попросить показать кофейни рядом с Парижем.
Впрочем, хватит писать на заморском языке. Давайте лучше поищем какой-нибудь театр кошек в Москве:
Запускаем приложение и видим нужное место. Удобно, не правда ли?
Просмотр улиц (Google StreetView)
Кроме карт, у Google есть приложение Просмотр улиц (StreetView), интегрированное в Карты. Запуск программы ничем не отличается от запуска карт, только нужно использовать другой формат:
По этим параметрам выводится набережная канала Грибоедова в Питере.
Сам формат выглядит следующим образом:
- lat — широта
- lng — долгота
- yaw — центр панорамы в градусах по часовой стрелке с севера. Обязательно используйте две запятые.
- pitch — центр обзора панорамы в градусах от -90 (взор вверх) до 90 (взгляд вниз)
- zoom — масштаб панорамы. 1.0 = нормальный, 2.0 = приближение в 2 раза, 3.0 = в 4 раза и так далее
- mapZoom — масштабирование места карты, связанное с панорамой. Это значение используется при переходе на Карты.
Также можно внедрить карты в своё приложение. Но это уже совсем другая история.
Если вам попадутся коты на картах, то присылайте мне свои находки.
Источник
Google Maps Intents for Android
The Google Maps app for Android exposes several intents that you can use to launch Google Maps in display, search, navigation, or Street View modes. If you want to embed a map in your app, please refer to the Google Maps Android API Getting Started Guide.
Note: Maps URLs let you build a universal, cross-platform URL to launch Google Maps and perform searches, get directions, display map views, and display panoramic images. It is recommended that you use the cross-platform Maps URLs to launch Google Maps, since these universal URLs allow for broader handling of the maps requests no matter which platform the user is on. You should only use the Android-specific Maps Intents for features that may only be functional on a mobile platform (for example, turn-by-turn navigation).
Overview
Intents let you start an activity in another app by describing a simple action you’d like to perform (such as «display a map» or «show directions to the airport») in an Intent object. The Google Maps app for Android supports several different intents, allowing you to launch the Google Maps app and perform one of four actions:
- Display a map at a specified location and zoom level.
- Search for locations or places, and display them on a map.
- Request directions from one location to another. Directions can be returned for three modes of transportation: driving, walking, bicycling.
- Display panorama imagery in Google Street View.
This page describes the intents that you can use with Google Maps app for Android. For more information on Intents and Intent Filters, or Intents common to the Android platform, refer to the Android developer documentation.
Intent requests
In order to launch Google Maps with an intent you must first create an Intent object, specifying its action, URI and package.
- Action: All Google Maps intents are called as a View action — ACTION_VIEW .
- URI: Google Maps intents use URL encoded that specify a desired action, along with some data with which to perform the action.
- Package: Calling setPackage(«com.google.android.apps.maps») will ensure that the Google Maps app for Android handles the Intent. If the package isn’t set, the system will determine which apps can handle the Intent . If multiple apps are available, the user may be asked which app they would like to use.
After creating the Intent , you can request that the system launch the related app in a number of ways. A common method is to pass the Intent to the startActivity() method. The system will launch the necessary app — in this case Google Maps — and start the corresponding Activity .
Kotlin
If the system cannot identify an app that can respond to the intent, your app may crash. For this reason, you should first verify that a receiving application is installed before you present one of these intents to a user.
To verify that an app is available to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it’s safe to call startActivity() . If the result is null , you should not use the intent and, if possible, you should disable the feature that invokes the intent.
Kotlin
For example, to display a map of San Francisco, you can use the following code:
Kotlin
URL encoded query strings
All strings passed to the Google Maps Intents must be URI encoded. For example, the string «1st & Pike, Seattle» should become 1st%20%26%20Pike%2C%20Seattle . Spaces in the string can be encoded with %20 or replaced with the plus sign (+).
You can use the android.net.Uri parse() method to encode your strings. For example:
Kotlin
Displaying a map
Use the geo: intent to display a map at a specified location and zoom level.
Parameters
- latitude and longitude set the center point of the map.
- z optionally sets the initial zoom level of the map. Accepted values range from 0 (the whole world) to 21 (individual buildings). The upper limit can vary depending on the map data available at the selected location.
Examples
Kotlin
Searching for a location
Use this intent to display search queries within a specified viewport. When the query has a single result, you can use this intent to display a pin at a particular place or address, such as a landmark, business, geographic feature, or town.
Parameters
In addition to the parameters used to display a map, Search supports the following parameters:
q defines the place(s) to highlight on the map. The q parameter is required for all Search requests. It accepts a location as either a place name or address. The string should be URL-encoded, so an address such as «City Hall, New York, NY» should be converted to City+Hall,New+York,NY.
label lets you set a custom label at a place identified on the map. The label must be specified as a String.
Categorical search
If you pass a general search term, Google Maps will attempt to find a location near the lat/lng you specified that matches your criteria. If no location is specified, Google Maps will try to find nearby listings. For example:
Kotlin
You can further bias the search results by specifying a zoom parameter along with the query string. In the below example, adding a zoom of 10 will attempt to find restaurants at a city level instead of nearby.
Kotlin
Location search
Searching for a specific address will display a pin at that location.
Kotlin
The above example sets a lat/lng of 0 , 0 , but passes an address as a query string. When searching for a very specific location, the latitude and longitude are not required. However, if you do not know the exact address, you can attempt to bias the results of the search by specifying a coordinate. For example, performing an address search for ‘Main Street’ will return too many results.
Kotlin
Adding a lat/lng to the intent URI will bias the results towards a particular area:
Kotlin
When you know your search will return a single value, you may wish to pass an optional label. Labels must be specified as a String, and will appear under the map marker. Note that labels are only available when q is specified as a lat/lng coordinate.
Kotlin
As an alternative to a street address or a latitude/longitude, you can display a pin at a known location using a plus code.
Kotlin
Launching turn-by-turn navigation
Use this intent to launch Google Maps navigation with turn-by-turn directions to the address or coordinate specified. Directions are always given from the user’s current location.
Parameters
q : Sets the end point for navigation searches. This value can be latitude, longitude coordinates or a query formatted address. If it is a query string that returns more than one result, the first result will be selected.
mode sets the method of transportation. Mode is optional, and can be set to one of:
- d for driving (default)
- b for bicycling
- l for two-wheeler
- w for walking
avoid sets features the route should try to avoid. Avoid is optional and can be set to one or more of:
Examples
The below Intent will request turn-by-turn navigation to Taronga Zoo, in Sydney Australia:
Kotlin
If you prefer not to pay tolls or ride a ferry, you can request routing that tries to avoid those things.
Kotlin
If you’d prefer a bit of exercise, you can request bicycling directions instead.
Kotlin
If you’d prefer taking a motorized two-wheeler, you can request that the directions include narrow roads and trails unavailable to cars. The below intent returns a route in India.
Kotlin
Displaying a Street View panorama
Use the google.streetview intent to launch Google Street View. Google Street View provides panoramic views from designated locations throughout its coverage area. User contributed Photospheres, and Street View special collections are also available.
Parameters
All google.streetview URIs must include either a cbll or a panoid parameter.
cbll accepts a latitude and a longitude as comma-separated values ( 46.414382,10.013988 ). The app will display the panorama photographed closest to this location. Because Street View imagery is periodically refreshed, and photographs may be taken from slightly different positions each time, it’s possible that your location may snap to a different panorama when imagery is updated.
panoid is a specific panorama ID. Google Maps will use the panorama ID if both a panoid and a cbll are specified. Panorama IDs are available to an Android app from the StreetViewPanoramaLocation object.
cbp is an optional parameter that adjusts the initial orientation of the camera. The cbp parameter takes 5 comma-separated values, all of which are optional. The most significant values are the second, fourth and fifth which set the bearing, zoom and tilt respectively. The first and third values are not supported, and should be set to 0 .
- bearing : indicates the compass heading of the camera in degrees clockwise from North. True north is 0, east is 90, south is 180, west is 270. Values passed to bearing will wrap; that is, 0°, 360° and 720° all point in the same direction. Bearing is defined as the second of five comma-separated values.
- zoom : Sets the zoom level of the camera. The default zoom level is set at 0. A zoom of 1 would double the magnification. The zoom is clamped between 0 and the maximum zoom level for the current panorama. This means that any value falling outside this range will be set to the closest extreme that falls within the range. For example, a value of -1 will be set to 0. Zoom is the fourth of five comma-separated values.
- tilt : specifies the angle, up or down, of the camera. The range is -90 through 0 to 90, with 90 looking straight down, 0 centered on the horizon, and -90 looking straight up.
Examples
Below are some examples of using the Street View intent.
Kotlin
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.
Источник