Cómo controlar eventos de clic
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Selecciona la plataforma:
Android
iOS
JavaScript
Puedes hacer que una capa de componentes responda a los eventos click
del usuario para obtener el ID de lugar y el tipo de componente del límite en el que se hizo clic. En el siguiente mapa de ejemplo, se muestran los límites de la capa País y un controlador de eventos que define el diseño del polígono en el que se hace clic asociado al país seleccionado.
Escribe un controlador de eventos de clic
Cuando se produce un evento de clic en una capa de entidades, el SDK de Maps para Android pasa un objeto FeatureClickEvent
al controlador de eventos. Usa FeatureClickEvent
para obtener las coordenadas de latitud y longitud del clic, y una lista de las entidades afectadas por el clic.
Cómo controlar eventos de la capa de entidades
Sigue estos pasos para controlar los eventos en una capa de componentes. En este ejemplo, definirás un controlador de eventos de clic para la capa de entidades Country con el objetivo de aplicar un relleno rojo al polígono que representa el país seleccionado.
Cuando llamas a FeatureLayer.setFeatureStyle()
, la función de fábrica de diseño establece el diseño en todos los componentes de la capa de componentes. Para actualizar el diseño de un componente en el controlador de eventos, debes llamar a FeatureLayer.setFeatureStyle()
para establecer el diseño actualizado en todos los componentes.
Si aún no lo hiciste, sigue los pasos que se indican en Cómo comenzar para crear un ID y un diseño de mapa nuevos. Asegúrate de habilitar la capa del componente País.
Asegúrate de que tu clase implemente FeatureLayer.OnFeatureClickListener
.
Registra un controlador de eventos para los eventos de clic en componentes llamando a FeatureLayer.addOnFeatureClickListener()
.
Java
private FeatureLayer countryLayer;
@Override
public void onMapReady(GoogleMap map) {
// Get the COUNTRY feature layer.
countryLayer = map.getFeatureLayer(new FeatureLayerOptions.Builder()
.featureType(FeatureType.COUNTRY)
.build());
// Register the click event handler for the Country layer.
countryLayer.addOnFeatureClickListener(this);
// Apply default style to all countries on load to enable clicking.
styleCountryLayer();
}
// Set default fill and border for all countries to ensure that they respond
// to click events.
private void styleCountryLayer() {
FeatureLayer.StyleFactory styleFactory = (Feature feature) -> {
return new FeatureStyle.Builder()
// Set the fill color for the country as white with a 10% opacity.
.fillColor(Color.argb(0.1, 0, 0, 0))
// Set border color to solid black.
.strokeColor(Color.BLACK)
.build();
};
// Apply the style factory function to the country feature layer.
countryLayer.setFeatureStyle(styleFactory);
}
Kotlin
private var countryLayer: FeatureLayer? = null
override fun onMapReady(googleMap: GoogleMap) {
// Get the COUNTRY feature layer.
countryLayer = googleMap.getFeatureLayer(FeatureLayerOptions.Builder()
.featureType(FeatureType.COUNTRY)
.build())
// Register the click event handler for the Country layer.
countryLayer?.addOnFeatureClickListener(this)
// Apply default style to all countries on load to enable clicking.
styleCountryLayer()
}
// Set default fill and border for all countries to ensure that they respond
// to click events.
private fun styleCountryLayer() {
val styleFactory = FeatureLayer.StyleFactory { feature: Feature ->
return@StyleFactory FeatureStyle.Builder()
// Set the fill color for the country as white with a 10% opacity.
.fillColor(Color.argb(0.1f, 0f, 0f, 0f))
// Set border color to solid black.
.strokeColor(Color.BLACK)
.build()
}
// Apply the style factory function to the country feature layer.
countryLayer?.setFeatureStyle(styleFactory)
}
Aplica un color de relleno rojo al país seleccionado. Solo se puede hacer clic en los componentes visibles.
Java
@Override
// Define the click event handler.
public void onFeatureClick(FeatureClickEvent event) {
// Get the list of features affected by the click using
// getPlaceIds() defined below.
List<String> selectedPlaceIds = getPlaceIds(event.getFeatures());
if (!selectedPlaceIds.isEmpty()) {
FeatureLayer.StyleFactory styleFactory = (Feature feature) -> {
// Use PlaceFeature to get the placeID of the country.
if (feature instanceof PlaceFeature) {
if (selectedPlaceIds.contains(((PlaceFeature) feature).getPlaceId())) {
return new FeatureStyle.Builder()
// Set the fill color to red.
.fillColor(Color.RED)
.build();
}
}
return null;
};
// Apply the style factory function to the feature layer.
countryLayer.setFeatureStyle(styleFactory);
}
}
// Get a List of place IDs from the FeatureClickEvent object.
private List<String> getPlaceIds(List<Feature> features) {
List<String> placeIds = new ArrayList<>();
for (Feature feature : features) {
if (feature instanceof PlaceFeature) {
placeIds.add(((PlaceFeature) feature).getPlaceId());
}
}
return placeIds;
}
Kotlin
// Define the click event handler.
override fun onFeatureClick(event: FeatureClickEvent) {
// Get the list of features affected by the click using
// getPlaceIds() defined below.
val selectedPlaceIds = getPlaceIds(event.getFeatures())
if (!selectedPlaceIds.isEmpty()) {
val styleFactory = FeatureLayer.StyleFactory { feature: Feature ->
// Use PlaceFeature to get the placeID of the country.
if (feature is PlaceFeature) {
if (selectedPlaceIds.contains((feature as PlaceFeature).getPlaceId())) {
return@StyleFactory FeatureStyle.Builder()
// Set the fill color to red.
.fillColor(Color.RED)
.build()
}
}
return@StyleFactory null
}
// Apply the style factory function to the feature layer.
countryLayer?.setFeatureStyle(styleFactory)
}
}
// Get a List of place IDs from the FeatureClickEvent object.
private fun getPlaceIds(features: List<Feature>): List<String> {
val placeIds: MutableList<String> = ArrayList()
for (feature in features) {
if (feature is PlaceFeature) {
placeIds.add((feature as PlaceFeature).getPlaceId())
}
}
return placeIds
}
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-08-31 (UTC)
[null,null,["Última actualización: 2025-08-31 (UTC)"],[[["\u003cp\u003eLearn how to make a feature layer respond to user click events, retrieving place ID and feature type.\u003c/p\u003e\n"],["\u003cp\u003eThis guide provides steps and code examples to create a click event handler for styling clicked boundaries.\u003c/p\u003e\n"],["\u003cp\u003eSee how to register an event handler for feature click events and apply custom styles to selected features.\u003c/p\u003e\n"],["\u003cp\u003eCode samples demonstrate retrieving the latitude/longitude of a click and a list of affected features.\u003c/p\u003e\n"],["\u003cp\u003eUnderstand how to implement a feature click event listener and style a clicked polygon with a red fill.\u003c/p\u003e\n"]]],[],null,["# Handle click events\n\nSelect platform: [Android](/maps/documentation/android-sdk/dds-boundaries/handle-events \"View this page for the Android platform docs.\") [iOS](/maps/documentation/ios-sdk/dds-boundaries/handle-events \"View this page for the iOS platform docs.\") [JavaScript](/maps/documentation/javascript/dds-boundaries/handle-events \"View this page for the JavaScript platform docs.\")\n\n\u003cbr /\u003e\n\nYou can make a feature layer respond to user `click` events to get the place\nID and feature type for the boundary that was clicked. The\nfollowing example map shows the boundaries for the Country layer, and\nshows an event handler that styles the clicked polygon associated with the\nselected country.\n\nWrite a click event handler\n---------------------------\n\nWhen a click event occurs on a feature layer, the Maps SDK for Android passes a\n[`FeatureClickEvent`](/android/reference/com/google/android/gms/maps/model/FeatureClickEvent)\nobject to the event handler. Use the `FeatureClickEvent` to get the latitude\nand longitude coordinates of the click and a list of features affected by the\nclick.\n\nHandle feature layer events\n---------------------------\n\nTake the following steps to handle events on a feature layer. In this example,\nyou define a click event handler for the Country feature layer to apply a red\nfill to the polygon representing the selected country.\n\nWhen you call\n[`FeatureLayer.setFeatureStyle()`](/android/reference/com/google/android/gms/maps/model/FeatureLayer#setFeatureStyle(com.google.android.gms.maps.model.FeatureLayer.StyleFactory)),\nthe style factory function sets the style on all features in the\nfeature layer. To update the style of a feature in the event handler, you must\ncall `FeatureLayer.setFeatureStyle()` to set the updated style on all\nfeatures.\n\n1. If you haven't already done so, follow the steps in\n [Get Started](/maps/documentation/android/dds-boundaries/start)\n to create a new map ID and map style. Be sure to enable the **Country**\n feature layer.\n\n2. Make sure your class implements\n [`FeatureLayer.OnFeatureClickListener`](/android/reference/com/google/android/gms/maps/model/FeatureLayer.OnFeatureClickListener).\n\n3. Register an event handler for feature click events by calling\n [`FeatureLayer.addOnFeatureClickListener()`](/android/reference/com/google/android/gms/maps/model/FeatureLayer#addOnFeatureClickListener(com.google.android.gms.maps.model.FeatureLayer.OnFeatureClickListener)).\n\n ### Java\n\n\n ```java\n private FeatureLayer countryLayer;\n\n @Override\n public void onMapReady(GoogleMap map) {\n\n // Get the COUNTRY feature layer.\n countryLayer = map.getFeatureLayer(new FeatureLayerOptions.Builder()\n .featureType(FeatureType.COUNTRY)\n .build());\n\n // Register the click event handler for the Country layer.\n countryLayer.addOnFeatureClickListener(this);\n\n // Apply default style to all countries on load to enable clicking.\n styleCountryLayer();\n }\n\n // Set default fill and border for all countries to ensure that they respond\n // to click events.\n private void styleCountryLayer() {\n FeatureLayer.StyleFactory styleFactory = (Feature feature) -\u003e {\n return new FeatureStyle.Builder()\n // Set the fill color for the country as white with a 10% opacity.\n .fillColor(Color.argb(0.1, 0, 0, 0))\n // Set border color to solid black.\n .strokeColor(Color.BLACK)\n .build();\n };\n\n // Apply the style factory function to the country feature layer.\n countryLayer.setFeatureStyle(styleFactory);\n }\n ```\n\n \u003cbr /\u003e\n\n ### Kotlin\n\n\n ```java\n private var countryLayer: FeatureLayer? = null\n\n override fun onMapReady(googleMap: GoogleMap) {\n // Get the COUNTRY feature layer.\n countryLayer = googleMap.getFeatureLayer(FeatureLayerOptions.Builder()\n .featureType(FeatureType.COUNTRY)\n .build())\n\n // Register the click event handler for the Country layer.\n countryLayer?.addOnFeatureClickListener(this)\n\n // Apply default style to all countries on load to enable clicking.\n styleCountryLayer()\n }\n\n // Set default fill and border for all countries to ensure that they respond\n // to click events.\n private fun styleCountryLayer() {\n val styleFactory = FeatureLayer.StyleFactory { feature: Feature -\u003e\n return@StyleFactory FeatureStyle.Builder()\n // Set the fill color for the country as white with a 10% opacity.\n .fillColor(Color.argb(0.1f, 0f, 0f, 0f))\n // Set border color to solid black.\n .strokeColor(Color.BLACK)\n .build()\n }\n\n // Apply the style factory function to the country feature layer.\n countryLayer?.setFeatureStyle(styleFactory)\n }\n ```\n\n \u003cbr /\u003e\n\n4. Apply a fill color of red to the selected country. Only visible features are\n clickable.\n\n ### Java\n\n\n ```java\n @Override\n // Define the click event handler.\n public void onFeatureClick(FeatureClickEvent event) {\n\n // Get the list of features affected by the click using\n // getPlaceIds() defined below.\n List\u003cString\u003e selectedPlaceIds = getPlaceIds(event.getFeatures());\n\n if (!selectedPlaceIds.isEmpty()) {\n FeatureLayer.StyleFactory styleFactory = (Feature feature) -\u003e {\n // Use PlaceFeature to get the placeID of the country.\n if (feature instanceof PlaceFeature) {\n if (selectedPlaceIds.contains(((PlaceFeature) feature).getPlaceId())) {\n return new FeatureStyle.Builder()\n // Set the fill color to red.\n .fillColor(Color.RED)\n .build();\n }\n }\n return null;\n };\n\n // Apply the style factory function to the feature layer.\n countryLayer.setFeatureStyle(styleFactory);\n }\n }\n\n // Get a List of place IDs from the FeatureClickEvent object.\n private List\u003cString\u003e getPlaceIds(List\u003cFeature\u003e features) {\n List\u003cString\u003e placeIds = new ArrayList\u003c\u003e();\n for (Feature feature : features) {\n if (feature instanceof PlaceFeature) {\n placeIds.add(((PlaceFeature) feature).getPlaceId());\n }\n }\n return placeIds;\n }\n ```\n\n \u003cbr /\u003e\n\n ### Kotlin\n\n\n ```java\n // Define the click event handler.\n override fun onFeatureClick(event: FeatureClickEvent) {\n\n // Get the list of features affected by the click using\n // getPlaceIds() defined below.\n val selectedPlaceIds = getPlaceIds(event.getFeatures())\n if (!selectedPlaceIds.isEmpty()) {\n val styleFactory = FeatureLayer.StyleFactory { feature: Feature -\u003e\n // Use PlaceFeature to get the placeID of the country.\n if (feature is PlaceFeature) {\n if (selectedPlaceIds.contains((feature as PlaceFeature).getPlaceId())) {\n return@StyleFactory FeatureStyle.Builder()\n // Set the fill color to red.\n .fillColor(Color.RED)\n .build()\n }\n }\n return@StyleFactory null\n }\n\n // Apply the style factory function to the feature layer.\n countryLayer?.setFeatureStyle(styleFactory)\n }\n }\n\n // Get a List of place IDs from the FeatureClickEvent object.\n private fun getPlaceIds(features: List\u003cFeature\u003e): List\u003cString\u003e {\n val placeIds: MutableList\u003cString\u003e = ArrayList()\n for (feature in features) {\n if (feature is PlaceFeature) {\n placeIds.add((feature as PlaceFeature).getPlaceId())\n }\n }\n return placeIds\n }\n ```\n\n \u003cbr /\u003e"]]