Android google map get markers

Содержание
  1. Маркеры
  2. Примеры кода
  3. Введение
  4. Начало работы с маркерами
  5. Добавление маркера
  6. Kotlin
  7. Отображение дополнительной информации о маркере
  8. Связь данных с маркером
  9. Kotlin
  10. Как сделать маркер перетаскиваемым
  11. Kotlin
  12. Персонализация маркера
  13. Kotlin
  14. Изменение цвета маркера
  15. Kotlin
  16. Изменение прозрачности маркера
  17. Kotlin
  18. Персонализация значка маркера
  19. Kotlin
  20. Создание плоского маркера
  21. Kotlin
  22. Вращение маркера
  23. Kotlin
  24. Z-индекс для маркера
  25. Kotlin
  26. Обработка событий маркера
  27. События кликов по маркеру
  28. События перетаскивания маркера
  29. GoogleMap
  30. Developer Guide
  31. Nested Class Summary
  32. Constant Summary
  33. Public Method Summary
  34. Inherited Method Summary
  35. Constants
  36. public static final int MAP_TYPE_HYBRID
  37. public static final int MAP_TYPE_NONE
  38. public static final int MAP_TYPE_NORMAL
  39. public static final int MAP_TYPE_SATELLITE
  40. public static final int MAP_TYPE_TERRAIN
  41. Public Methods
  42. public Circle addCircle (CircleOptions options)
  43. public GroundOverlay addGroundOverlay (GroundOverlayOptions options)
  44. public Marker addMarker (MarkerOptions options)
  45. public Polygon addPolygon (PolygonOptions options)
  46. public Polyline addPolyline (PolylineOptions options)
  47. public TileOverlay addTileOverlay (TileOverlayOptions options)
  48. public void animateCamera (CameraUpdate update)
  49. public void animateCamera (CameraUpdate update, GoogleMap.CancelableCallback callback)
  50. public void animateCamera (CameraUpdate update, int durationMs, GoogleMap.CancelableCallback callback)
  51. public void clear ()
  52. public CameraPosition getCameraPosition ()
  53. public IndoorBuilding getFocusedBuilding ()
  54. public int getMapType ()
  55. public float getMaxZoomLevel ()
  56. public float getMinZoomLevel ()
  57. public Location getMyLocation ()
  58. public Projection getProjection ()
  59. public UiSettings getUiSettings ()
  60. public boolean isBuildingsEnabled ()
  61. public boolean isIndoorEnabled ()
  62. public boolean isMyLocationEnabled ()
  63. public boolean isTrafficEnabled ()
  64. public void moveCamera (CameraUpdate update)
  65. public void resetMinMaxZoomPreference ()
  66. public void setBuildingsEnabled (boolean enabled)
  67. public void setContentDescription (String description)
  68. public boolean setIndoorEnabled (boolean enabled)
  69. public void setInfoWindowAdapter (GoogleMap.InfoWindowAdapter adapter)
  70. public void setLatLngBoundsForCameraTarget (LatLngBounds bounds)
  71. public void setLocationSource (LocationSource source)
  72. public boolean setMapStyle (MapStyleOptions style)
  73. public void setMapType (int type)
  74. public void setMaxZoomPreference (float maxZoomPreference)
  75. public void setMinZoomPreference (float minZoomPreference)
  76. public void setMyLocationEnabled (boolean enabled)

Маркеры

Маркеры обозначают отдельные местоположения на карте. Маркеры можно настраивать, например менять их цвета или значки. Информационные окна могут содержать дополнительную информацию об отмеченных точках.

Примеры кода

Хранилище ApiDemos на сайте GitHub содержит пример, где демонстрируются различные свойства маркера:

Java

  • MapWithMarker: простая карта с маркером. О том, как ее добавить, читайте в руководстве.
  • MarkerDemoActivity: использование маркеров на карте, включая параметры и прослушиватели.

Kotlin

  • MapWithMarker: простая карта с маркером. О том, как ее добавить, читайте в руководстве.
  • MarkerDemoActivity: использование маркеров на карте, включая параметры и прослушиватели.

Введение

Маркеры указывают местоположения на карте. По умолчанию используется стандартный значок, знакомый вам по работе с Google Картами. С помощью API можно изменить цвет значка, его изображение или точку привязки. Маркеры (объекты Marker ) добавляются на карту с помощью метода GoogleMap.addMarker(markerOptions) .

Маркеры – это интерактивные элементы. По умолчанию они принимают события click и часто используются с прослушивателями событий для вывода информационных окон. Установка для свойства маркера draggable значения true позволяет пользователю изменять положение маркера на карте. Возможность перемещения маркера активируется долгим нажатием.

По умолчанию когда пользователь касается маркера, в правом нижнем углу карты отображается панель инструментов, которая предоставляет быстрый доступ к мобильному приложению «Google Карты». Ее можно отключить. Дополнительные сведения вы можете найти в руководстве по элементам управления.

Начало работы с маркерами

В этом эпизоде Maps Live рассказывается об основах добавления маркеров на карту с использованием Maps SDK for Android.

Добавление маркера

В следующем примере демонстрируется добавление маркера на карту. Маркер создается в точке с координатами -33.852,151.211 (Сидней, Австралия), а при нажатии на него появляется строка «Marker in Sydney» в информационном окне.

Kotlin

Отображение дополнительной информации о маркере

Когда пользователь касается маркера на карте, должна выводиться дополнительная информация о месте или местоположении. Дополнительные сведения вы можете найти в руководстве по информационным окнам.

Связь данных с маркером

В маркере можно сохранить объект произвольных данных, используя метод Marker.setTag() , и извлечь этот объект данных с помощью метода Marker.getTag() . В приведенном ниже примере кода показано, как с помощью тегов подсчитать количество кликов, которые получил маркер.

Kotlin

Примеры случаев, когда вам может понадобиться сохранение или получение данных через маркеры:

  • Ваше приложение может обрабатывать различные типы маркеров, и вам нужно, чтобы они обрабатывались по-разному, когда пользователь нажимает на них. Для этого сохраните в маркере объект String с указанием типа.
  • Вы работаете с интерфейсом к системе, в которой имеются уникальные идентификаторы записей и каждый маркер соответствует одной записи в этой системе.
  • В данных маркера записан приоритет, который определяет значение параметра z-index для этого маркера.

Как сделать маркер перетаскиваемым

Чтобы маркер можно было перемещать после его добавления на карту, задайте для свойства draggable значение true . Перетаскивание маркера активируется долгим нажатием. Когда пользователь уберет палец с экрана, маркер останется в этом месте.

По умолчанию возможность перетаскивания маркеров отключена. Вы должны явно включить эту возможность с помощью метода MarkerOptions.draggable(boolean) до добавления маркера на карту или же с помощью метода Marker.setDraggable(boolean) , когда маркер уже добавлен. Вы можете прослушивать события перетаскивания для маркера.

В приведенном ниже фрагменте кода перетаскиваемый маркер устанавливается для города Перт, Австралия.

Kotlin

Персонализация маркера

В этом видеоролике рассказывается, как использовать маркеры для визуального представления различных мест на карте.

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

Маркеры поддерживают настройку с использованием следующих свойств:

Position (Положение; обязательно) Значение параметра LatLng для положения маркера на карте. Это единственное обязательное свойство объекта Marker . Anchor (Привязка) Точка на изображении, которое будет размещено в месте, указанном параметром маркера LatLng (широта и долгота). По умолчанию устанавливается по центру в нижней части изображения. Alpha (Альфа-канал) Свойство, определяющее прозрачность маркера. Значение по умолчанию – 1.0. Title (Заголовок) Строка, которая отображается в информационном окне, когда пользователь касается маркера. Snippet (Фрагмент) Дополнительный текст, отображаемый под названием. Icon (Значок) Картинка в битовом формате, которая отображается вместо значка по умолчанию. Draggable (Перетаскиваемость) Задайте значение true , если хотите, чтобы пользователи могли перетаскивать значок. Значение по умолчанию – false . Visible (Видимость) Измените значение этого свойства на false , чтобы сделать маркер невидимым. Значение по умолчанию – true . Flat или Billboard (свойства ориентации) По умолчанию ориентация маркеров рассчитывается относительно экрана. Они не вращаются и не наклоняются при изменении ракурса. Плоские маркеры ориентированы по земной поверхности и вращаются или наклоняются вместе с камерой. Маркеры обоих типов не меняют размер при масштабировании. Если вам необходим этот эффект, используйте наложения (GroundOverlay). Rotation (Вращение) Поворот маркера по часовой стрелке в градусах. Для плоских маркеров направление по умолчанию может изменяться. По умолчанию плоский маркер направлен на север. Остальные маркеры по умолчанию расположены перпендикулярно земной поверхности и при вращении обращены в сторону камеры.

Ниже представлен код, который позволяет создать простой маркер со стандартным значком.

Kotlin

Изменение цвета маркера

Чтобы изменить цвет стандартного изображения маркера, необходимо передать объект BitmapDescriptor в метод icon(). Вы можете использовать набор предварительно установленных цветов в объекте BitmapDescriptorFactory или задать конкретный цвет маркера с помощью метода BitmapDescriptorFactory.defaultMarker(float hue) . Параметр hue (тон) должен содержать значение от 0 до 360, представляющее собой точку на цветовом круге.

Kotlin

Изменение прозрачности маркера

Для изменения прозрачности маркера можно использовать метод MarkerOptions.alpha(). Непрозрачность следует указывать как число с плавающей запятой от 0,0 до 1,0, где 0 – полная прозрачность, а 1 – полная непрозрачность.

Kotlin

Персонализация значка маркера

Значок маркера по умолчанию можно заменить любым другим изображением. Собственные значки всегда устанавливаются в виде объекта BitmapDescriptor и определяются с использованием одного из методов в классе BitmapDescriptorFactory .

Читайте также:  Как увеличить жизнь батареи android

fromAsset(String assetName) Создает собственный маркер, используя название битового изображения в каталоге ресурсов. fromBitmap(Bitmap image) Создает собственный маркер из битового изображения. fromFile(String fileName) Создает собственный значок, используя название битового файла, который хранится во внутренней памяти устройства. fromPath(String absolutePath) Создает собственный маркер, используя абсолютный путь к битовому файлу. fromResource(int resourceId) Создает собственный маркер, используя идентификатор ресурса битового изображения.

В приведенном ниже фрагменте показано создание маркера с пользовательским значком.

Kotlin

Создание плоского маркера

Положение значка маркера обычно рассчитывается относительно экрана. Масштабирование, повороты и наклоны камеры не влияют на его ориентацию. Однако можно сделать так, чтобы значок лежал на земной поверхности, вращался и наклонялся вместе с картой. Размер плоского маркера не меняется при приближении и отдалении.

Чтобы изменить ориентацию маркера, установите для свойства flat значение true .

Kotlin

Вращение маркера

Маркер можно вращать вокруг точки привязки с помощью метода Marker . setRotation() . Значение измеряется относительно исходного положения в градусах по часовой стрелке. Если маркер плоский, он по умолчанию ориентирован на север. Остальные маркеры по умолчанию расположены перпендикулярно земной поверхности и при вращении обращены в сторону камеры.

В приведенном ниже примере маркер поворачивается на 90°. При установке для точки привязки значения 0.5,0.5 маркер будет вращаться вокруг своего центра, а не вокруг основания.

Kotlin

Z-индекс для маркера

Параметр Z-index указывает порядок расположения маркера относительно других маркеров на карте. Маркер с высоким Z-индексом отображается поверх маркеров с меньшими значениями этого параметра. По умолчанию Z-индекс равен 0 .

Установите Z-индекс для объекта параметров маркера, вызвав метод MarkerOptions.zIndex() , как показано в следующем примере кода:

Kotlin

Получить Z-индекс можно с помощью метода Marker.getZIndex() , а изменить его – с помощью метода Marker.setZIndex() .

Маркеры всегда отображаются поверх фрагментов карты и прочих не поддерживающих маркеры наложений (наземных наложений, ломаных линий, многоугольников и других фигур). Это не зависит от Z-индекса других наложений. Фактически у маркеров свое пространство Z-индексов, отдельное от Z-индексов других наложений.

Обработка событий маркера

Maps API позволяет прослушивать события маркера и реагировать на них. Для этого необходимо назначить объекту GoogleMap , к которому относятся маркеры, соответствующий прослушиватель. Если для одного из маркеров карты возникает событие, соответствующий объект Marker , передаваемый в виде параметра, выполняет обратный вызов прослушивателя. Чтобы сопоставить этот объект Marker с вашей собственной ссылкой на Marker , используйте метод equals() , а не оператор == .

Можно прослушивать следующие события:

События кликов по маркеру

Чтобы отслеживать события кликов по маркеру, используйте прослушиватель OnMarkerClickListener . Чтобы добавить его на карту, вызовите GoogleMap.setOnMarkerClickListener(OnMarkerClickListener) . Когда пользователь нажимает на маркер, выполняется вызов onMarkerClick(Marker) , а маркер передается в виде аргумента. Этот метод возвращает логическое значение, указывающее, было ли событие принято (т. е. нужно ли подавлять поведение по умолчанию). Если возвращается значение false , поведение по умолчанию выполняется параллельно с персонализированным. Поведение по умолчанию для события клика по маркеру – отображение его информационного окна (если оно доступно) и перемещение камеры таким образом, чтобы маркер находился в центре карты.

Влияние Z-индекса на события кликов:

  • Когда пользователь нажимает на кластер маркеров, событие клика назначается маркеру с наивысшим Z-индексом.
  • В большинстве случаев каждый клик запускает одно событие. Другими словами, клик не передается маркерам или иным наложениям с более низкими значениями Z-индекса.
  • Нажатие на кластер маркеров вызывает последующий цикл кликов внутри кластера. Каждый маркер выбирается по очереди. Порядок в цикле имеет приоритет прежде всего по Z-индексу, и только затем – по расстоянию до точки нажатия.
  • Если пользователь нажимает на карту за пределами кластера, API пересчитывает кластер и переопределяет состояние цикла кликов, запуская его с начала.
  • Событие клика переходит от кластера маркеров на другие фигуры и наложения, прежде чем цикл начнется снова.
  • Фактически маркеры располагаются в группе значений Z-индекса, которая отделена от других наложений и фигур (ломаных линий, многоугольников, кругов, наземных наложений), какими бы ни были значения Z-индекса этих объектов. Если несколько маркеров, наложений или фигур перекрывают друг друга, то клики сначала циклически распределяются по кластеру маркеров, а затем применяются для других доступных для нажатия наложений или фигур в зависимости от значений их Z-индекса.

События перетаскивания маркера

Чтобы отслеживать события перетаскивания маркера, используйте прослушиватель OnMarkerDragListener . Чтобы добавить его на карту, вызовите GoogleMap.setOnMarkerDragListener . Функция перетаскивания активируется долгим нажатием на маркер. Когда пользователь уберет палец с экрана, маркер останется в этом месте. В начале перетаскивания вызывается метод onMarkerDragStart(Marker) , во время перетаскивания – onMarkerDrag(Marker) (он вызывается непрерывно), а по окончании – onMarkerDragEnd(Marker) . Положение маркера можно в любое время запросить с помощью метода Marker.getPosition() .

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.

Источник

GoogleMap

This is the main class of the Google Maps SDK for Android and is the entry point for all methods related to the map. You cannot instantiate a GoogleMap object directly, rather, you must obtain one from the getMapAsync() method on a MapFragment or MapView that you have added to your application.

Note: Similar to a View object, a GoogleMap can only be read and modified from the Android UI thread. Calling GoogleMap methods from another thread will result in an exception.

You can adjust the viewpoint of a map by changing the position of the camera (as opposed to moving the map). You can use the map’s camera to set parameters such as location, zoom level, tilt angle, and bearing. For more information, see Camera and View.

Developer Guide

To get started, read the Google Maps SDK for Android developer guide.

Nested Class Summary

interface GoogleMap.CancelableCallback A callback interface for reporting when a task is complete or canceled.
interface GoogleMap.InfoWindowAdapter Provides views for customized rendering of info windows.
interface GoogleMap.OnCameraChangeListener This interface is deprecated. Replaced by GoogleMap.OnCameraMoveStartedListener , GoogleMap.OnCameraMoveListener and GoogleMap.OnCameraIdleListener . The order in which the deprecated onCameraChange method will be called in relation to the methods in the new camera change listeners is undefined.
interface GoogleMap.OnCameraIdleListener Callback interface for when camera movement has ended.
interface GoogleMap.OnCameraMoveCanceledListener Callback interface for when the camera’s motion has been stopped or when the camera starts moving for a new reason.
interface GoogleMap.OnCameraMoveListener Callback interface for when the camera changes position.
interface GoogleMap.OnCameraMoveStartedListener Callback interface for when the camera motion starts.
interface GoogleMap.OnCircleClickListener Callback interface for when a circle is clicked.
interface GoogleMap.OnGroundOverlayClickListener Callback interface for when a ground overlay is clicked.
interface GoogleMap.OnIndoorStateChangeListener A listener for when the indoor state changes.
interface GoogleMap.OnInfoWindowClickListener Callback interface for click/tap events on a marker’s info window.
interface GoogleMap.OnInfoWindowCloseListener Callback interface for close events on a marker’s info window.
interface GoogleMap.OnInfoWindowLongClickListener Callback interface for when the user long presses on a marker’s info window.
interface GoogleMap.OnMapClickListener Callback interface for when the user taps on the map.
interface GoogleMap.OnMapLoadedCallback Callback interface for when the map has finished rendering.
interface GoogleMap.OnMapLongClickListener Callback interface for when the user long presses on the map.
interface GoogleMap.OnMarkerClickListener Defines signatures for methods that are called when a marker is clicked or tapped.
interface GoogleMap.OnMarkerDragListener Callback interface for drag events on markers.
interface GoogleMap.OnMyLocationButtonClickListener Callback interface for when the My Location button is clicked.
interface GoogleMap.OnMyLocationChangeListener This interface is deprecated. Use com.google.android.gms.location.FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the «My Location» blue dot. See the Select Current Place tutorial, which uses the FusedLocationProviderApi, or the Location Developer Guide.
interface GoogleMap.OnMyLocationClickListener Callback interface for when the My Location dot (which signifies the user’s location) is clicked.
interface GoogleMap.OnPoiClickListener A listener for POI taps.
interface GoogleMap.OnPolygonClickListener Callback interface for when a polygon is clicked.
interface GoogleMap.OnPolylineClickListener Callback interface for when a polyline is clicked.
interface GoogleMap.SnapshotReadyCallback Callback interface to notify when the snapshot has been taken.
Читайте также:  Прошивка для модуля связи андроид

Constant Summary

int MAP_TYPE_HYBRID Satellite maps with a transparent layer of major streets.
int MAP_TYPE_NONE No base map tiles.
int MAP_TYPE_NORMAL Basic maps.
int MAP_TYPE_SATELLITE Satellite maps with no labels.
int MAP_TYPE_TERRAIN Terrain maps.

Public Method Summary

Inherited Method Summary

Constants

public static final int MAP_TYPE_HYBRID

Satellite maps with a transparent layer of major streets.

public static final int MAP_TYPE_NONE

No base map tiles.

public static final int MAP_TYPE_NORMAL

public static final int MAP_TYPE_SATELLITE

Satellite maps with no labels.

public static final int MAP_TYPE_TERRAIN

Public Methods

public Circle addCircle (CircleOptions options)

Add a circle to this map.

Parameters
options A circle options object that defines how to render the Circle
Returns
  • The Circle object that is added to the map

public GroundOverlay addGroundOverlay (GroundOverlayOptions options)

Adds an image to this map.

Parameters
options A ground-overlay options object that defines how to render the overlay. Options must have an image (AnchoredBitmap) and position specified.
Returns
  • The GroundOverlay that was added to the map.
Throws
IllegalArgumentException if either the image or the position is unspecified in the options.

public Marker addMarker (MarkerOptions options)

Adds a marker to this map.

The marker’s icon is rendered on the map at the location Marker.position. Clicking the marker centers the camera on the marker. If Marker.title is defined, the map shows an info box with the marker’s title and snippet. If the marker is draggable, long-clicking and then dragging the marker moves it.

Parameters
options A marker options object that defines how to render the marker.
Returns
  • The Marker that was added to the map.

public Polygon addPolygon (PolygonOptions options)

Adds a polygon to this map.

Parameters
options A polygon options object that defines how to render the Polygon.
Returns
  • The Polygon object that is added to the map.

public Polyline addPolyline (PolylineOptions options)

Adds a polyline to this map.

Parameters
options A polyline options object that defines how to render the Polyline.
Returns
  • The Polyline object that was added to the map.

public TileOverlay addTileOverlay (TileOverlayOptions options)

Adds a tile overlay to this map. See TileOverlay for more information.

Note that unlike other overlays, if the map is recreated, tile overlays are not automatically restored and must be re-added manually.

Parameters
options A tile-overlay options object that defines how to render the overlay. Options must have a TileProvider specified, otherwise an IllegalArgumentException will be thrown.
Returns
  • The TileOverlay that was added to the map.
Throws
IllegalArgumentException if the TileProvider is unspecified in the options.

public void animateCamera (CameraUpdate update)

Animates the movement of the camera from the current position to the position defined in the update. During the animation, a call to getCameraPosition() returns an intermediate location of the camera.

See CameraUpdateFactory for a set of updates.

Parameters
update The change that should be applied to the camera.

public void animateCamera (CameraUpdate update, GoogleMap.CancelableCallback callback)

Animates the movement of the camera from the current position to the position defined in the update and calls an optional callback on completion. See CameraUpdateFactory for a set of updates.

During the animation, a call to getCameraPosition() returns an intermediate location of the camera.

Parameters
update The change that should be applied to the camera.
callback The callback to invoke from the Android UI thread when the animation stops. If the animation completes normally, onFinish() is called; otherwise, onCancel() is called. Do not update or animate the camera from within onCancel() .

public void animateCamera (CameraUpdate update, int durationMs, GoogleMap.CancelableCallback callback)

Moves the map according to the update with an animation over a specified duration, and calls an optional callback on completion. See CameraUpdateFactory for a set of updates.

If getCameraPosition() is called during the animation, it will return the current location of the camera in flight.

Parameters
update
durationMs The duration of the animation in milliseconds. This must be strictly positive, otherwise an IllegalArgumentException will be thrown.
callback An optional callback to be notified from the Android UI thread when the animation stops. If the animation stops due to its natural completion, the callback will be notified with onFinish() . If the animation stops due to interruption by a later camera movement or a user gesture, onCancel() will be called. The callback should not attempt to move or animate the camera in its cancellation method. If a callback isn’t required, leave it as null .

public void clear ()

Removes all markers, polylines, polygons, overlays, etc from the map.

public CameraPosition getCameraPosition ()

Gets the current position of the camera.

The CameraPosition returned is a snapshot of the current position, and will not automatically update when the camera moves.

For more information about changing the camera’s position, see Camera and View.

Returns
  • The current position of the Camera.

public IndoorBuilding getFocusedBuilding ()

Gets the currently focused building.

Returns
  • The current focused building or null if no building is focused.

public int getMapType ()

Gets the type of map that’s currently displayed. See MAP_TYPE_NORMAL , MAP_TYPE_SATELLITE , MAP_TYPE_TERRAIN for possible values.

Returns

public float getMaxZoomLevel ()

Returns the maximum zoom level for the current camera position. This takes into account what map type is currently being used, e.g., satellite or terrain may have a lower max zoom level than the base map tiles.

For more information about changing the camera’s zoom level, see Camera and View.

Returns
  • The maximum zoom level available at the current camera position.

public float getMinZoomLevel ()

Returns the minimum zoom level. This is the same for every location (unlike the maximum zoom level) but may vary between devices and map sizes.

For more information about changing the camera’s zoom level, see Camera and View.

Returns
  • The minimum zoom level available.

public Location getMyLocation ()

This method is deprecated.
use com.google.android.gms.location.FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the «My Location» blue dot. See the MyLocationDemoActivity in the sample applications folder for example code, or the Location Developer Guide.

Returns the currently displayed user location, or null if there is no location data available.

Returns
Throws
IllegalStateException if the my-location layer is not enabled.

public Projection getProjection ()

Returns a Projection object that you can use to convert between screen coordinates and latitude/longitude coordinates.

The Projection returned is a snapshot of the current projection, and will not automatically update when the camera moves. As this operation is expensive, you should get the projection only once per screen. Google Maps uses the Mercator projection to create its maps from geographic data and convert points on the map into geographic coordinates.

Returns
  • The Projection of the map in its current state.
Читайте также:  Андроид как удалить рабочий стол планшет

public UiSettings getUiSettings ()

Gets the user interface settings for the map.

Returns

public boolean isBuildingsEnabled ()

Returns whether 3D buildings layer is enabled.

Returns
  • true if buildings are enabled; false otherwise.

public boolean isIndoorEnabled ()

Gets whether indoor maps are currently enabled.

Returns
  • true if indoor maps are enabled; false if indoor maps are disabled;

public boolean isMyLocationEnabled ()

Gets the status of the my-location layer.

Returns
  • true if the my-location layer is enabled; false otherwise.

public boolean isTrafficEnabled ()

Checks whether the map is drawing traffic data. This is subject to the availability of traffic data.

Returns
  • true if traffic data is enabled; false otherwise.

public void moveCamera (CameraUpdate update)

Repositions the camera according to the instructions defined in the update. The move is instantaneous, and a subsequent getCameraPosition() will reflect the new position. See CameraUpdateFactory for a set of updates.

Parameters
update The change that should be applied to the camera.

public void resetMinMaxZoomPreference ()

Removes any previously specified upper and lower zoom bounds.

public void setBuildingsEnabled (boolean enabled)

Turns the 3D buildings layer on or off.

Parameters
enabled true to enable the 3D buildings layer; false to disable 3D buildings.

public void setContentDescription (String description)

Sets a contentDescription for the map.

This is used to provide a spoken description of the map in accessibility mode. The default value is «Google Map»

Parameters
description a string to use as a description.

public boolean setIndoorEnabled (boolean enabled)

Sets whether indoor maps should be enabled. Currently, indoor maps can only be shown on one map at a time and by default, this is the first map added to your application. To enable indoor maps on another map, you must first disable indoor maps on the original map. If you try to enable indoor maps when it is enabled on another map, nothing will happen and this will return false . When Indoor is not enabled for a map, all methods related to indoor will return null , or false .

Parameters
enabled true to try to enable indoor maps; false to disable indoor maps.
Returns
  • whether it was possible to enable indoor maps.

public void setInfoWindowAdapter (GoogleMap.InfoWindowAdapter adapter)

Sets a custom renderer for the contents of info windows.

Like the map’s event listeners, this state is not serialized with the map. If the map gets re-created (e.g., due to a configuration change), you must ensure that you call this method again in order to preserve the customization.

Parameters
adapter The adapter to use for info window contents, or null to use the default content rendering in info windows.

public void setLatLngBoundsForCameraTarget (LatLngBounds bounds)

Specifies a LatLngBounds to constrain the camera target, so that when users scroll and pan the map, the camera target does not move outside these bounds.

Set to null to clear the bounding box completely. The new bounds replaces any previously specified bounding box.

When the LatLngBounds changes, the SDK adjusts all later camera updates to respect those bounds if possible. Note that there are technical considerations that may prevent the SDK from keeping the camera target strictly within the bounds. For example, floating point precision rounding errors or a very low zoom level.

Parameters
bounds The bounds to constrain the camera target within.

public void setLocationSource (LocationSource source)

Replaces the location source of the my-location layer.

Parameters
source A location source to use in the my-location layer. Set to null to use the default location source.

public boolean setMapStyle (MapStyleOptions style)

Sets the styling of the base map.

Using the style options, you can apply custom styles to features and elements on the map. See MapStyleOptions for style definition details.

Set to null to clear any previous custom styling.

Parameters
Returns
  • true if the style was successfully parsed; false if problems were detected with the MapStyleOptions , including, e.g. unparsable styling JSON, unrecognized feature type, unrecognized element type, or invalid styler keys. If the return value is false , the current style is left unchanged.

public void setMapType (int type)

Sets the type of map tiles that should be displayed. The allowable values are:

  • MAP_TYPE_NORMAL : Basic map.
  • MAP_TYPE_SATELLITE : Satellite imagery.
  • MAP_TYPE_HYBRID : Satellite imagery with roads and labels.
  • MAP_TYPE_TERRAIN : Topographic data.
  • MAP_TYPE_NONE : No base map tiles.
Parameters
type The type of map to display.

public void setMaxZoomPreference (float maxZoomPreference)

Sets a preferred upper bound for the camera zoom.

When the maximum zoom changes, the SDK adjusts all later camera updates to respect that maximum if possible. Note that there are technical considerations that may prevent the SDK from allowing users to zoom too deep into the map. For example, satellite or terrain may have a lower maximum zoom than the base map tiles.

The SDK resolves any conflicts in the minimum and maximum values. If you set the minimum zoom to a higher zoom level than the current maximum, then the SDK uses the new minimum value for both minimum and maximum. If you set the maximum zoom to a lower zoom level than the minimum, the SDK uses the new maximum value for both minimum and maximum. For example: Assume the current minimum zoom is 8 and the maximum is 14. Then you set the maximum zoom to 6. The SDK uses a minimum zoom of 6 and a maximum zoom of 6.

Parameters
maxZoomPreference The preferred upper bound.

public void setMinZoomPreference (float minZoomPreference)

Sets a preferred lower bound for the camera zoom.

When the minimum zoom changes, the SDK adjusts all later camera updates to respect that minimum if possible. Note that there are technical considerations that may prevent the SDK from allowing users to zoom too low.

The SDK resolves any conflicts in the minimum and maximum values. If you set the minimum zoom to a higher zoom level than the current maximum, then the SDK uses the new minimum value for both minimum and maximum. If you set the maximum zoom to a lower zoom level than the minimum, the SDK uses the new maximum value for both minimum and maximum. For example: Assume the current minimum zoom is 8 and the maximum is 14. Then you set the minimum zoom to 16. The SDK uses a minimum zoom of 16 and a maximum zoom of 16.

Parameters
minZoomPreference The preferred lower bound.

public void setMyLocationEnabled (boolean enabled)

Enables or disables the my-location layer.

While enabled and the location is available, the my-location layer continuously draws an indication of a user’s current location and bearing, and displays UI controls that allow a user to interact with their location (for example, to enable or disable camera tracking of their location and bearing).

In order to use the my-location-layer feature you need to request permission for either ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION unless you have set a custom location source.

If you have set a custom location source via setLocationSource(LocationSource) the Google Maps SDK for Android will not check whether the above permissions have been granted. However, you still need to make sure that the user has granted all the permissions required for your custom location source.

Источник

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