- Customizing InfoWindow Contents in Google Map Android API V2 using InfoWindowAdapter
- Info window in android
- About
- Информационные окна
- Примеры кода
- Введение
- Добавление информационного окна
- Kotlin
- Отображение и скрытие информационного окна
- Kotlin
- Персонализация информационных окон
- События информационных окон
- Kotlin
- Android Google Map Custom Info Window Button Click Example
- Output Of Info Window
- Necessary Thing
- Step 1. Making New Activity
- Step 2. Write API Key At Right Place
- Step 3. Lion Image
- Step 4. Custom Layout For Info window
- Step 5. Adapter class Info Window
- Step 6. Changing Default Activity
- Attending the above code
- Related Map Tutorials
- Download Source Code For Android Google Map Custom Info Window
- One thought on “Android Google Map Custom Info Window Button Click Example”
Customizing InfoWindow Contents in Google Map Android API V2 using InfoWindowAdapter
In this article we will create an Android application that displays a customized info-window in GoogleMap Android API V2 using InfoWindowAdapter interface.
For developing this application, we are using Eclipse 4.2.1 with ADT plugin ( 21.0.0 ) and Android SDK ( 21.0.0 ) and testing in a real device with Android 2.3.6 ( GingerBread ).
1. Download and configure Google Play Services Library in Eclipse
Please follow the given below link to setup Google Play Service library in Eclipse.
2. Create a new Android Application Project namely “LocationCustomInfoContents”
Figure 1 : Create a new Android application project titled “LocationCustomInfoContents”
3. Configure Android Application Project
Figure 2 : Configure the project
4. Design Application Launcher Icon
Figure 3 : Design application launcher icon
5. Create a blank activity
Figure 4 : Create a blank activity
6. Enter Main Activity Details
Figure 5 : Enter MainActivity Details
7. Add Google Play Services Library to this project
Figure 6 : Add Google Play Services Library
8. Get the API key for Google Maps Android API v2
We need to get an API key from Google to use Google Maps in Android application. Please follow the given below link to get the API key for Google Maps Android API v2.
9. Add Android Support library to this project
By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :
- Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
- Right click this project
- Then from popup window, Click “Android Tools -> Add Support Library “
10. Update the file AndroidManfiest.xml
11. Update the file res/values/strings.xml
12. Update the layout file res/layout/activity_main.xml
13. Update the layout file res/layout/info_window_layout.xml
14. Update the file src/in/wptrafficanalyzer/locationcustominfocontents/MainActivity.java
14. Screenshot of the application in execution
Figure 7 : Showing CustomInfoWindowContents in the Google Map
Источник
Info window in android
InteractiveInfoWindowAndroid by Appolica
InteractiveInfoWindowAndroid is (suprisingly :D) an Android library which gives you the opportunity to show interactive info windows on your google map. The library is developed and maintained by Appolica. The UI of your window is encapsulated in your own fragment with its own lifecycle. You just pass it to the InfoWindowManager and display it above whichever marker you want.
Add it to your Android project
And then use it in your code
First you need to add our map fragment to your layout. It embeds the SupportMapFragment and all the magic which makes this library to work and provides its API.
Then you obtain an instance of it and basically you are ready to go:
Listen when an InfoWindow is hiding or showing by implementing InfoWindowManager.WindowShowListener:
You can get an instance of the GoogleMap by calling mapInfoWindowFragment.getMapAsync(onMapReadyCallback) .
If you don’t want to use our fragment it’s okay but it’s not that straight-forward. You have to bind the InfoWindowManager to your Activity/Fragment and add TouchInterceptFrameLayout as a parent of your map. Take a look at this example.
- public void getMapAsync(OnMapReadyCallback onMapReadyCallback) — Use this method to get the GoogleMap object asynchronously from our fragment.
- public InfoWindowManager infoWindowManager() — Get an instance of InfoWindowManager to control your InfoWindow.
- public void toggle(@NonNull final InfoWindow infoWindow, final boolean animated) — Shows or hides the given InfoWindow with or without animation.
- public void show(@NonNull final InfoWindow infoWindow, final boolean animated) — Shows the given InfoWindow with or without animation.
- public void hide(@NonNull final InfoWindow infoWindow, final boolean animated) — Hides the given InfoWindow with or without animation.
- public void setWindowShowListener(WindowShowListener windowShowListener) — Listen for InfoWindow show/hide events.
- public void setShowAnimation(Animation showAnimation) — Set your own InfoWindow show animation.
- public void setHideAnimation(Animation hideAnimation) — Set your own InfoWindow hide animation.
- public void setContainerSpec(ContainerSpecification containerSpec) — Set the container specification for your InfoWindow container. The ContainerSpecification class wraps (at least for now) only the backgorund drawable of the container view. You can change the background from here.
public InfoWindow(Marker marker, MarkerSpecification markerSpec, Fragment fragment) —
- marker — The marker which determines the window’s position on the screen
- markerSpec — Provides the marker’s offsetX and offsetY
- fragment — The actual window that is displayed on the screen
public InfoWindow(LatLng position, MarkerSpecification markerSpec, Fragment fragment) —
- position — The LatLng position which determines the window’s position on the screen.
- markerSpec — Provides the marker’s offsetX and offsetY
- fragment — The actual window that is displayed on the screen
public MarkerSpecification(int offsetX, int offsetY) — Create marker specification by providing InfoWindow’s x and y offsets from marker’s screen location.
Note: By default offsetX will be ignored, so in order for it to take effect, you must call setCenterByX(false).
Also if you want to use dp, you should convert the values to px by yourself. The constructor expects absolute pixel values.
The following listener settters are a copy of GoogleMap’s setters. Use these methods instead of the original ones.
- public void setOnMapClickListener(GoogleMap.OnMapClickListener onMapClickListener)
- public void setOnCameraIdleListener(GoogleMap.OnCameraIdleListener onCameraIdleListener)
- public void setOnCameraMoveStartedListener(final GoogleMap.OnCameraMoveStartedListener onCameraMoveStartedListener)
- public void setOnCameraMoveListener(final GoogleMap.OnCameraMoveListener onCameraMoveListener)
- public void setOnCameraMoveCanceledListener(final GoogleMap.OnCameraMoveCanceledListener onCameraMoveCanceledListener)
The InfoWindow lags when you fling the map. However if you want to hide it instead of moving it with the map, you can use InfoWindowManager.setHideOnFling(final boolean hideOnFling) . We are open to suggestions how to fix this.
Copyright 2016 Appolica Ltd.
Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
About
Library project, developed and maintained by Appolica, offering an interactive info window for Google maps on Android.
Источник
Информационные окна
Информационные окна отображаются поверх карты и содержат текст или изображения. Каждое такое окно привязывается к маркеру и по умолчанию открывается при нажатии на него.
Примеры кода
Хранилище ApiDemos на сайте GitHub содержит пример, который демонстрирует все свойства информационных окон:
- MarkerDemoActivity (Java): настройка информационных окон и использование прослушивателей для них.
- MarkerDemoActivity (Kotlin): настройка информационных окон и использование прослушивателей для них.
Введение
Информационные окна содержат описания отдельных маркеров и открываются при нажатии на них. Одновременно может быть открыто только одно окно. Если пользователь нажмет на другой маркер, первое окно закроется, а второе откроется. Обратите внимание: если пользователь коснется маркера, для которого уже показывается информационное окно, оно закроется и откроется снова.
Ориентация информационного окна соответствует ориентации устройства, а его центр располагается выше соответствующего маркера. По умолчанию оно содержит заголовок, выделенный полужирным шрифтом, и необязательный текст под ним.
Добавление информационного окна
Самый простой способ добавить информационное окно – настроить для соответствующего маркера методы title() и snippet() . При каждом нажатии на этот маркер будет открываться информационное окно.
Kotlin
Отображение и скрытие информационного окна
Информационные окна появляются, когда пользователь нажимает на экран. Однако вы можете настроить и открытие программным способом, вызывая метод showInfoWindow() для целевого маркера. Чтобы скрыть окно, необходимо вызвать метод hideInfoWindow() .
Kotlin
Вы также можете создавать информационные окна для отдельных кластеризованных маркеров. Ознакомьтесь с руководством, где описано, как это делать.
Персонализация информационных окон
Содержание и внешний вид информационных окон можно изменить. Для этого создайте конкретную реализацию интерфейса InfoWindowAdapter и вызовите метод GoogleMap.setInfoWindowAdapter() . Интерфейс содержит два метода: getInfoWindow(Marker) и getInfoContents(Marker) . API сначала вызывает метод getInfoWindow(Marker) . Если возвращается значение null , то вызывается метод getInfoContents(Marker) . Если и он возвращает null , используется информационное окно по умолчанию.
Метод getInfoWindow() определяет внешний вид всего окна. Метод getInfoContents() отвечает только за персонализацию содержания окна; рамка и фон не меняются.
Ниже показаны информационное окно по умолчанию, окно с персонализированным содержанием и окно с измененными рамкой и фоном.
События информационных окон
Пример MarkerDemoActivity содержит код регистрации и управления событиями информационного окна.
Чтобы обнаруживать события кликов в информационных окнах, используйте прослушиватель OnInfoWindowClickListener . Чтобы добавить его на карту, вызовите метод GoogleMap.setOnInfoWindowClickListener(OnInfoWindowClickListener) . Когда пользователь нажимает на информационное окно, вызывается метод onInfoWindowClick(Marker) и окно выделяется цветом, выбранным по умолчанию, то есть серым.
Kotlin
Вы также можете отслеживать длительные нажатия с помощью интерфейса OnInfoWindowLongClickListener , который можно настроить с помощью метода GoogleMap.setOnInfoWindowCloseListener(OnInfoWindowCloseListener) . Этот прослушиватель работает так же, как прослушиватель обычных кликов. При обнаружении долгого нажатия инициируется метод обратного вызова onInfoWindowClose(Marker) .
Чтобы получать оповещения при закрытии информационного окна, используйте интерфейс OnInfoWindowCloseListener . Чтобы установить его, вызовите метод GoogleMap.setOnInfoWindowCloseListener(OnInfoWindowCloseListener) . Вы получите обратный вызов onInfoWindowClose(Marker) .
Примечание об обновлении информационного окна. Событие onInfoWindowClose() активируется, если пользователь обновляет информационное окно, нажимая на маркер уже открытого окна. Но если вызвать метод Marker.showInfoWindow() для открытого информационного окна программным способом, событие onInfoWindowClose() не активируется. Такое поведение основано на предположении, что вам известно, что информационное окно закроется и откроется снова.
Как уже упоминалось в предыдущем разделе, информационное окно не является интерактивным объектом View. Представление прорисовывается на карте в виде изображения. В результате прослушиватели, добавленные к объекту View, игнорируются, что мешает распознавать события кликов в разных частях окна. Рекомендуем не размещать интерактивные компоненты (такие как кнопки, флажки или текстовые поля) внутри настраиваемого информационного окна.
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 Map Custom Info Window Button Click Example
Android Google Map Custom Info Window Button Click Example is written here.
In this tutorial, I will explain how to create custom info window layout in google map.
Info window is something like a pop up rectangle that gives some information about the marker on google map.
It is mostly useful when you want to provide quick lines about the place. You can also provide an example image of the particular marker or place.
I will teach you how to hide this info window on the button click.
We will also consider how you can implement the button click of the info window on google map in android.
Output Of Info Window
Necessary Thing
Before you start making this example, you need to have google API Key.
This API key is necessary to integrate the google map in your android app.
For generating this API Key, you need to create one app in the Google Developer Console.
This tutorial has mainly two parts :
- Work At Google Developer Console (follow this part only)
- Work On Android Studio
You should follow all the steps of first part only. After this you will have your Google API Key. Now follow all the below steps to create info window on google map marker.
Step 1. Making New Activity
First of all, create a new project in the android studio.
In this process, you will be asked to choose activity type right after you entered project name, directory and SDK Version.
Following image shows to select default activity.
Step 2. Write API Key At Right Place
After creating project with Maps Activity, you will have one xml file called “google_maps_api.xml”
Compiler automatically creates this file at res->values directory.
Source Code for this file is as the following
As you can see in the above code, last lines holds the tags. Enter your Google API Key between these tags.
Step 3. Lion Image
As I have already said, we will add one image in our info window. So for this purpose, we have to add one image in the drawable folder.
Download a lion image by clicking the below link and copy it in drawable directory.
[sociallocker]Download a lion image[/sociallocker]
Step 4. Custom Layout For Info window
We need create one xml layout file. This file will work as a custom file for info window.
Info window will represent a layout generated by this file. So make a new xml layout file in res->layout directory.
Name of this file should be “gir_forest.xml.”
Add the below coding lines in “gir_forest.xml.”
- I have added one image view and two text views in the above file.
- Image view represent the sample image of the place and two text views are providing basic information about the place or marker.
Step 5. Adapter class Info Window
Create a new Java class named “InfoWindowAdapter.java”
Copy the below code in it.
This class provides data to text views. Object of this class will create display view for info window.
Step 6. Changing Default Activity
You have selected Map activity as a default activity in step 1. So you should have two files
First is activity_maps.xml and second one is MapsActivity.java
Write the below Source code in activity_maps.xml
- One button and one fragment is present in the above code.
- Compiler will load the google map in the fragment.
- When the user will click the button, compiler will hide the info window.
Write down the following coding lines in MapsActivity.java
Attending the above code
Now let us one by one see what above code is doing.
- First read the below code
- It is the code for button. Info window will be hidden when the user click the button.
See the below code
- Compiler will start the process to create the google map with the help of the above code.
Following code is run when map is ready to be loaded in the fragment.
- Compiler will first add the marker in the map.
- Then it will create an object of the InfoWindowAdapter class. After this, compiler will generate the info window with help of an object of the InfoWindowAdapter class.
Consider the below code
- Above code will be run when the user click on the Info Window.
Related Map Tutorials
Following are useful tutorials for android google maps.
Download Source Code For Android Google Map Custom Info Window
One thought on “Android Google Map Custom Info Window Button Click Example”
Hello thanks for that it really helped me, but i want to add more markers and for each of them to have their own custom info window, I tried a lot of things but it didn’t work, so if you could help me that would be great. Thanks
Источник