Mit dem Maps SDK for Android kannst du Ereignisse auf der Karte erfassen.
Codebeispiele
Das ApiDemos-Repository auf GitHub enthält Beispiele für Ereignisse und Listener:
Java
- EventsDemoActivity: Ereignisse durch Kartenklick und Kameraänderung
- CameraDemoActivity: Ereignisse durch Kameraänderung
- CircleDemoActivity: Ereignisse durch Klicken auf und Ziehen von Markierungen
- GroundOverlayDemoActivity: Boden-Overlay-Klickereignisse
- IndoorDemoActivity: Ereignisse in Bezug auf Indoor-Karten
- MarkerDemoActivity: Ereignisse in Bezug auf Markierungen und Infofenster
- PolygonDemoActivity: Ereignisse in Bezug auf Polygone
Kotlin
- EventsDemoActivity: Ereignisse durch Kartenklick und Kameraänderung
- CameraDemoActivity: Ereignisse durch Kameraänderung
- CircleDemoActivity: Ereignisse durch Klicken auf und Ziehen von Markierungen
- GroundOverlayDemoActivity: Boden-Overlay-Klickereignisse
- IndoorDemoActivity: Ereignisse in Bezug auf Indoor-Karten
- MarkerDemoActivity: Ereignisse in Bezug auf Markierungen und Infofenster
- PolygonDemoActivity: Ereignisse in Bezug auf Polygone
Ereignisse in Bezug auf das Klicken auf eine Karte/lange Klickereignisse
Mithilfe des OnMapClickListener
-Elements kann auf das Tippen auf einen Punkt der Karte reagiert werden. Du kannst es auf der Karte festlegen, indem du GoogleMap.setOnMapClickListener(OnMapClickListener)
aufrufst. Wenn ein Nutzer auf der Karte auf eine beliebige Stelle klickt oder tippt, empfängst du ein onMapClick(LatLng)
-Ereignis, das den entsprechenden Punkt auf der Karte angibt. Wenn du die entsprechende Position auf dem Bildschirm in Pixeln benötigst, kannst du eine Projection
aus der Karte abrufen. Damit lassen sich die Koordinaten aus dem Breiten- und Längengrad in Bildschirmpixel umrechnen und umgekehrt.
Lange Klickereignisse lassen sich mit dem OnMapLongClickListener
-Element erfassen, das du durch Aufrufen von GoogleMap.setOnMapLongClickListener(OnMapLongClickListener)
auf der Karte festlegen kannst.
Dieser Listener funktioniert ähnlich wie der Klick-Listener. Er wird bei langen Klickereignissen über einen onMapLongClick(LatLng)
-Callback benachrichtigt.
Klickereignisse im Lite-Modus deaktivieren
Um Klickereignisse auf einer Karte im Lite-Modus zu deaktivieren, kannst du in der Ansicht, die die MapView
oder das MapFragment
enthält, setClickable()
aufrufen. Das ist vor allem dann hilfreich, wenn eine oder mehrere Karten in einer Listenansicht dargestellt werden, in der mit dem Klickereignis eine Aktion aufgerufen werden soll, die in keinem Zusammenhang mit der Karte steht.
Die Option zum Deaktivieren von Klickereignissen ist nur im Lite-Modus verfügbar. Das Deaktivieren von Klickereignissen führt auch dazu, dass Markierungen nicht anklickbar sind. Es wirkt sich jedoch nicht auf andere Steuerelemente auf der Karte aus.
Für eine MapView
:
Java
MapView mapView = findViewById(R.id.mapView); mapView.setClickable(false);
Kotlin
val mapView = findViewById<MapView>(R.id.mapView) mapView.isClickable = false
Für ein MapFragment
:
Java
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); View view = mapFragment.getView(); view.setClickable(false);
Kotlin
val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment val view = mapFragment.view view?.isClickable = false
Ereignisse durch Kameraänderung
Die Kartenansicht wird so modelliert, als wäre eine Kamera auf eine ebene Fläche ausgerichtet. Du kannst die Eigenschaften der Kamera bearbeiten, um den Zoomfaktor, den Viewport und die Perspektive der Karte zu ändern. Weitere Informationen findest du in der Anleitung zur Kamera. Nutzer können die Kamera auch durch Touch-Gesten beeinflussen.
Mit Listenern zu Kameraänderungen lassen sich Bewegungen der Kamera erfassen. Deine App kann Benachrichtigungen für Ereignisse zu Beginn, während und am Ende einer Kamerabewegung erhalten. Weiterhin lässt sich erkennen, warum sich die Kamera bewegt und ob die Bewegung durch Nutzergesten, integrierte API-Animationen oder entwicklergesteuerte Bewegungen veranlasst wurde.
Im Beispiel unten sind alle verfügbaren Kameraereignis-Listener dargestellt:
Java
// Copyright 2020 Google LLC // // 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // 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. package com.example.mapdemo; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.CompoundButton; import android.widget.SeekBar; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.CancelableCallback; import com.google.android.gms.maps.GoogleMap.OnCameraIdleListener; import com.google.android.gms.maps.GoogleMap.OnCameraMoveCanceledListener; import com.google.android.gms.maps.GoogleMap.OnCameraMoveListener; import com.google.android.gms.maps.GoogleMap.OnCameraMoveStartedListener; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PolylineOptions; /** * This shows how to change the camera position for the map. */ public class CameraDemoActivity extends AppCompatActivity implements OnCameraMoveStartedListener, OnCameraMoveListener, OnCameraMoveCanceledListener, OnCameraIdleListener, OnMapReadyCallback { private static final String TAG = CameraDemoActivity.class.getName(); /** * The amount by which to scroll the camera. Note that this amount is in raw pixels, not dp * (density-independent pixels). */ private static final int SCROLL_BY_PX = 100; public static final CameraPosition BONDI = new CameraPosition.Builder().target(new LatLng(-33.891614, 151.276417)) .zoom(15.5f) .bearing(300) .tilt(50) .build(); public static final CameraPosition SYDNEY = new CameraPosition.Builder().target(new LatLng(-33.87365, 151.20689)) .zoom(15.5f) .bearing(0) .tilt(25) .build(); private GoogleMap map; private CompoundButton animateToggle; private CompoundButton customDurationToggle; private SeekBar customDurationBar; private PolylineOptions currPolylineOptions; private boolean isCanceled = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.camera_demo); animateToggle = findViewById(R.id.animate); customDurationToggle = findViewById(R.id.duration_toggle); customDurationBar = findViewById(R.id.duration_bar); updateEnabledState(); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override protected void onResume() { super.onResume(); updateEnabledState(); } @Override public void onMapReady(GoogleMap googleMap) { map = googleMap; map.setOnCameraIdleListener(this); map.setOnCameraMoveStartedListener(this); map.setOnCameraMoveListener(this); map.setOnCameraMoveCanceledListener(this); // We will provide our own zoom controls. map.getUiSettings().setZoomControlsEnabled(false); map.getUiSettings().setMyLocationButtonEnabled(true); // Show Sydney map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.87365, 151.20689), 10)); } /** * When the map is not ready the CameraUpdateFactory cannot be used. This should be called on * all entry points that call methods on the Google Maps API. */ private boolean checkReady() { if (map == null) { Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show(); return false; } return true; } /** * Called when the Go To Bondi button is clicked. */ public void onGoToBondi(View view) { if (!checkReady()) { return; } changeCamera(CameraUpdateFactory.newCameraPosition(BONDI)); } /** * Called when the Animate To Sydney button is clicked. */ public void onGoToSydney(View view) { if (!checkReady()) { return; } changeCamera(CameraUpdateFactory.newCameraPosition(SYDNEY), new CancelableCallback() { @Override public void onFinish() { Toast.makeText(getBaseContext(), "Animation to Sydney complete", Toast.LENGTH_SHORT) .show(); } @Override public void onCancel() { Toast.makeText(getBaseContext(), "Animation to Sydney canceled", Toast.LENGTH_SHORT) .show(); } }); } /** * Called when the stop button is clicked. */ public void onStopAnimation(View view) { if (!checkReady()) { return; } map.stopAnimation(); } /** * Called when the zoom in button (the one with the +) is clicked. */ public void onZoomIn(View view) { if (!checkReady()) { return; } changeCamera(CameraUpdateFactory.zoomIn()); } /** * Called when the zoom out button (the one with the -) is clicked. */ public void onZoomOut(View view) { if (!checkReady()) { return; } changeCamera(CameraUpdateFactory.zoomOut()); } /** * Called when the tilt more button (the one with the /) is clicked. */ public void onTiltMore(View view) { if (!checkReady()) { return; } CameraPosition currentCameraPosition = map.getCameraPosition(); float currentTilt = currentCameraPosition.tilt; float newTilt = currentTilt + 10; newTilt = (newTilt > 90) ? 90 : newTilt; CameraPosition cameraPosition = new CameraPosition.Builder(currentCameraPosition) .tilt(newTilt).build(); changeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } /** * Called when the tilt less button (the one with the \) is clicked. */ public void onTiltLess(View view) { if (!checkReady()) { return; } CameraPosition currentCameraPosition = map.getCameraPosition(); float currentTilt = currentCameraPosition.tilt; float newTilt = currentTilt - 10; newTilt = (newTilt > 0) ? newTilt : 0; CameraPosition cameraPosition = new CameraPosition.Builder(currentCameraPosition) .tilt(newTilt).build(); changeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } /** * Called when the left arrow button is clicked. This causes the camera to move to the left */ public void onScrollLeft(View view) { if (!checkReady()) { return; } changeCamera(CameraUpdateFactory.scrollBy(-SCROLL_BY_PX, 0)); } /** * Called when the right arrow button is clicked. This causes the camera to move to the right. */ public void onScrollRight(View view) { if (!checkReady()) { return; } changeCamera(CameraUpdateFactory.scrollBy(SCROLL_BY_PX, 0)); } /** * Called when the up arrow button is clicked. The causes the camera to move up. */ public void onScrollUp(View view) { if (!checkReady()) { return; } changeCamera(CameraUpdateFactory.scrollBy(0, -SCROLL_BY_PX)); } /** * Called when the down arrow button is clicked. This causes the camera to move down. */ public void onScrollDown(View view) { if (!checkReady()) { return; } changeCamera(CameraUpdateFactory.scrollBy(0, SCROLL_BY_PX)); } /** * Called when the animate button is toggled */ public void onToggleAnimate(View view) { updateEnabledState(); } /** * Called when the custom duration checkbox is toggled */ public void onToggleCustomDuration(View view) { updateEnabledState(); } /** * Update the enabled state of the custom duration controls. */ private void updateEnabledState() { customDurationToggle.setEnabled(animateToggle.isChecked()); customDurationBar .setEnabled(animateToggle.isChecked() && customDurationToggle.isChecked()); } private void changeCamera(CameraUpdate update) { changeCamera(update, null); } /** * Change the camera position by moving or animating the camera depending on the state of the * animate toggle button. */ private void changeCamera(CameraUpdate update, CancelableCallback callback) { if (animateToggle.isChecked()) { if (customDurationToggle.isChecked()) { int duration = customDurationBar.getProgress(); // The duration must be strictly positive so we make it at least 1. map.animateCamera(update, Math.max(duration, 1), callback); } else { map.animateCamera(update, callback); } } else { map.moveCamera(update); } } @Override public void onCameraMoveStarted(int reason) { if (!isCanceled) { map.clear(); } String reasonText = "UNKNOWN_REASON"; currPolylineOptions = new PolylineOptions().width(5); switch (reason) { case OnCameraMoveStartedListener.REASON_GESTURE: currPolylineOptions.color(Color.BLUE); reasonText = "GESTURE"; break; case OnCameraMoveStartedListener.REASON_API_ANIMATION: currPolylineOptions.color(Color.RED); reasonText = "API_ANIMATION"; break; case OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION: currPolylineOptions.color(Color.GREEN); reasonText = "DEVELOPER_ANIMATION"; break; } Log.d(TAG, "onCameraMoveStarted(" + reasonText + ")"); addCameraTargetToPath(); } @Override public void onCameraMove() { // When the camera is moving, add its target to the current path we'll draw on the map. if (currPolylineOptions != null) { addCameraTargetToPath(); } Log.d(TAG, "onCameraMove"); } @Override public void onCameraMoveCanceled() { // When the camera stops moving, add its target to the current path, and draw it on the map. if (currPolylineOptions != null) { addCameraTargetToPath(); map.addPolyline(currPolylineOptions); } isCanceled = true; // Set to clear the map when dragging starts again. currPolylineOptions = null; Log.d(TAG, "onCameraMoveCancelled"); } @Override public void onCameraIdle() { if (currPolylineOptions != null) { addCameraTargetToPath(); map.addPolyline(currPolylineOptions); } currPolylineOptions = null; isCanceled = false; // Set to *not* clear the map when dragging starts again. Log.d(TAG, "onCameraIdle"); } private void addCameraTargetToPath() { LatLng target = map.getCameraPosition().target; currPolylineOptions.add(target); } }
Kotlin
/* * Copyright 2018 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * 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. */ package com.example.kotlindemos import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.View import android.widget.CompoundButton import android.widget.SeekBar import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.maps.CameraUpdate import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.GoogleMap.CancelableCallback import com.google.android.gms.maps.GoogleMap.OnCameraIdleListener import com.google.android.gms.maps.GoogleMap.OnCameraMoveCanceledListener import com.google.android.gms.maps.GoogleMap.OnCameraMoveListener import com.google.android.gms.maps.GoogleMap.OnCameraMoveStartedListener import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.PolylineOptions /** * This shows how to change the camera position for the map. */ class CameraDemoActivity : AppCompatActivity(), OnCameraMoveStartedListener, OnCameraMoveListener, OnCameraMoveCanceledListener, OnCameraIdleListener, OnMapReadyCallback { /** * The amount by which to scroll the camera. Note that this amount is in raw pixels, not dp * (density-independent pixels). */ private val SCROLL_BY_PX = 100 private val TAG = CameraDemoActivity::class.java.name private val sydneyLatLng = LatLng(-33.87365, 151.20689) private val bondiLocation: CameraPosition = CameraPosition.Builder() .target(LatLng(-33.891614, 151.276417)) .zoom(15.5f) .bearing(300f) .tilt(50f) .build() private val sydneyLocation: CameraPosition = CameraPosition.Builder(). target(LatLng(-33.87365, 151.20689)) .zoom(15.5f) .bearing(0f) .tilt(25f) .build() private lateinit var map: GoogleMap private lateinit var animateToggle: CompoundButton private lateinit var customDurationToggle: CompoundButton private lateinit var customDurationBar: SeekBar private var currPolylineOptions: PolylineOptions? = null private var isCanceled = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.camera_demo) animateToggle = findViewById(R.id.animate) customDurationToggle = findViewById(R.id.duration_toggle) customDurationBar = findViewById(R.id.duration_bar) updateEnabledState() val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } override fun onResume() { super.onResume() updateEnabledState() } override fun onMapReady(googleMap: GoogleMap?) { // return early if the map was not initialised properly map = googleMap ?: return with(googleMap) { setOnCameraIdleListener(this@CameraDemoActivity) setOnCameraMoveStartedListener(this@CameraDemoActivity) setOnCameraMoveListener(this@CameraDemoActivity) setOnCameraMoveCanceledListener(this@CameraDemoActivity) // We will provide our own zoom controls. uiSettings.isZoomControlsEnabled = false uiSettings.isMyLocationButtonEnabled = true // Show Sydney moveCamera(CameraUpdateFactory.newLatLngZoom(sydneyLatLng, 10f)) } } /** * When the map is not ready the CameraUpdateFactory cannot be used. This should be used to wrap * all entry points that call methods on the Google Maps API. * * @param stuffToDo the code to be executed if the map is initialised */ private fun checkReadyThen(stuffToDo: () -> Unit) { if (!::map.isInitialized) { Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show() } else { stuffToDo() } } /** * Called when the Go To Bondi button is clicked. */ @Suppress("UNUSED_PARAMETER") fun onGoToBondi(view: View) { checkReadyThen { changeCamera(CameraUpdateFactory.newCameraPosition(bondiLocation)) } } /** * Called when the Animate To Sydney button is clicked. */ @Suppress("UNUSED_PARAMETER") fun onGoToSydney(view: View) { checkReadyThen { changeCamera(CameraUpdateFactory.newCameraPosition(sydneyLocation), object : CancelableCallback { override fun onFinish() { Toast.makeText(baseContext, "Animation to Sydney complete", Toast.LENGTH_SHORT).show() } override fun onCancel() { Toast.makeText(baseContext, "Animation to Sydney canceled", Toast.LENGTH_SHORT).show() } }) } } /** * Called when the stop button is clicked. */ @Suppress("UNUSED_PARAMETER") fun onStopAnimation(view: View) = checkReadyThen { map.stopAnimation() } /** * Called when the zoom in button (the one with the +) is clicked. */ @Suppress("UNUSED_PARAMETER") fun onZoomIn(view: View) = checkReadyThen { changeCamera(CameraUpdateFactory.zoomIn()) } /** * Called when the zoom out button (the one with the -) is clicked. */ @Suppress("UNUSED_PARAMETER") fun onZoomOut(view: View) = checkReadyThen { changeCamera(CameraUpdateFactory.zoomOut()) } /** * Called when the tilt more button (the one with the /) is clicked. */ @Suppress("UNUSED_PARAMETER") fun onTiltMore(view: View) { checkReadyThen { val newTilt = Math.min(map.cameraPosition.tilt + 10, 90F) val cameraPosition = CameraPosition.Builder(map.cameraPosition).tilt(newTilt).build() changeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)) } } /** * Called when the tilt less button (the one with the \) is clicked. */ @Suppress("UNUSED_PARAMETER") fun onTiltLess(view: View) { checkReadyThen { val newTilt = Math.max(map.cameraPosition.tilt - 10, 0F) val cameraPosition = CameraPosition.Builder(map.cameraPosition).tilt(newTilt).build() changeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)) } } /** * Called when the left arrow button is clicked. This causes the camera to move to the left */ @Suppress("UNUSED_PARAMETER") fun onScrollLeft(view: View) { checkReadyThen { changeCamera(CameraUpdateFactory.scrollBy((-SCROLL_BY_PX).toFloat(),0f)) } } /** * Called when the right arrow button is clicked. This causes the camera to move to the right. */ @Suppress("UNUSED_PARAMETER") fun onScrollRight(view: View) { checkReadyThen { changeCamera(CameraUpdateFactory.scrollBy(SCROLL_BY_PX.toFloat(), 0f)) } } /** * Called when the up arrow button is clicked. The causes the camera to move up. */ @Suppress("UNUSED_PARAMETER") fun onScrollUp(view: View) { checkReadyThen { changeCamera(CameraUpdateFactory.scrollBy(0f, (-SCROLL_BY_PX).toFloat())) } } /** * Called when the down arrow button is clicked. This causes the camera to move down. */ @Suppress("UNUSED_PARAMETER") fun onScrollDown(view: View) { checkReadyThen { changeCamera(CameraUpdateFactory.scrollBy(0f, SCROLL_BY_PX.toFloat())) } } /** * Called when the animate button is toggled */ @Suppress("UNUSED_PARAMETER") fun onToggleAnimate(view: View) = updateEnabledState() /** * Called when the custom duration checkbox is toggled */ @Suppress("UNUSED_PARAMETER") fun onToggleCustomDuration(view: View) = updateEnabledState() /** * Update the enabled state of the custom duration controls. */ private fun updateEnabledState() { customDurationToggle.isEnabled = animateToggle.isChecked customDurationBar.isEnabled = animateToggle.isChecked && customDurationToggle.isChecked } /** * Change the camera position by moving or animating the camera depending on the state of the * animate toggle button. */ private fun changeCamera(update: CameraUpdate, callback: CancelableCallback? = null) { if (animateToggle.isChecked) { if (customDurationToggle.isChecked) { // The duration must be strictly positive so we make it at least 1. map.animateCamera(update, Math.max(customDurationBar.progress, 1), callback) } else { map.animateCamera(update, callback) } } else { map.moveCamera(update) } } override fun onCameraMoveStarted(reason: Int) { if (!isCanceled) map.clear() var reasonText = "UNKNOWN_REASON" currPolylineOptions = PolylineOptions().width(5f) when (reason) { OnCameraMoveStartedListener.REASON_GESTURE -> { currPolylineOptions?.color(Color.BLUE) reasonText = "GESTURE" } OnCameraMoveStartedListener.REASON_API_ANIMATION -> { currPolylineOptions?.color(Color.RED) reasonText = "API_ANIMATION" } OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION -> { currPolylineOptions?.color(Color.GREEN) reasonText = "DEVELOPER_ANIMATION" } } Log.d(TAG, "onCameraMoveStarted($reasonText)") addCameraTargetToPath() } /** * Ensures that currPolyLine options is not null before accessing it * * @param stuffToDo the code to be executed if currPolylineOptions is not null */ private fun checkPolylineThen(stuffToDo: () -> Unit) { if (currPolylineOptions != null) stuffToDo() } override fun onCameraMove() { Log.d(TAG, "onCameraMove") // When the camera is moving, add its target to the current path we'll draw on the map. checkPolylineThen { addCameraTargetToPath() } } override fun onCameraMoveCanceled() { // When the camera stops moving, add its target to the current path, and draw it on the map. checkPolylineThen { addCameraTargetToPath() map.addPolyline(currPolylineOptions) } isCanceled = true // Set to clear the map when dragging starts again. currPolylineOptions = null Log.d(TAG, "onCameraMoveCancelled") } override fun onCameraIdle() { checkPolylineThen { addCameraTargetToPath() map.addPolyline(currPolylineOptions) } currPolylineOptions = null isCanceled = false // Set to *not* clear the map when dragging starts again. Log.d(TAG, "onCameraIdle") } private fun addCameraTargetToPath() { currPolylineOptions?.add(map.cameraPosition.target) } }
Die folgenden Kamera-Listener sind verfügbar:
Der
onCameraMoveStarted()
-Callback vonOnCameraMoveStartedListener
wird aufgerufen, wenn sich die Kamera bewegt. Die Callback-Methode empfängt einreason
-Element für die Kamerabewegung. Das kann einen der folgenden Gründe haben:REASON_GESTURE
zeigt an, dass die Bewegung der Kamera eine Reaktion auf die Touch-Geste eines Nutzers auf der Karte war, z. B. Schwenken, Neigen, Zoomen (durch Auseinander- und Zusammenziehen der Finger) oder Drehen der Karte.REASON_API_ANIMATION
zeigt an, dass die API eine Kamerabewegung als Reaktion auf eine Nutzeraktion ausgeführt hat, die keine Touch-Geste war, z. B. Tippen auf die Schaltfläche zum Zoomen, Tippen auf die Schaltfläche „Mein Standort“ oder Klicken auf eine Markierung.REASON_DEVELOPER_ANIMATION
zeigt an, dass die Kamerabewegung durch deine App initiiert wurde.
Der
onCameraMove()
-Callback vonOnCameraMoveListener
wird mehrmals aufgerufen, wenn sich die Kamera bewegt oder der Nutzer mit dem Touchscreen interagiert. Die API ruft den Callback einmal pro Frame auf. Dieser Callback ist jedoch asynchron und daher nicht mit dem auf dem Bildschirm sichtbaren Inhalt synchron. Es kann auch sein, dass sich die Kameraposition zwischen zweionCameraMove()
-Callbacks nicht verändert.Der
OnCameraIdle()
-Callback vonOnCameraIdleListener
wird aufgerufen, wenn die Kamerabewegung stoppt und der Nutzer seine Interaktion mit der Karte beendet hat.Der
OnCameraMoveCanceled()
-Callback vonOnCameraMoveCanceledListener
wird aufgerufen, wenn die aktuelle Kamerabewegung unterbrochen wurde. Sofort nach demOnCameraMoveCanceled()
-Callback wird deronCameraMoveStarted()
-Callback mit dem neuenreason
-Element aufgerufen.Wenn deine App explizit
GoogleMap.stopAnimation()
aufruft, wird derOnCameraMoveCanceled()
-Callback aufgerufen, aber nicht deronCameraMoveStarted()
-Callback.
Um einen Listener auf der Karte festzulegen, rufst du die entsprechende Methode „set-listener“ auf.
Wenn du beispielsweise einen Callback von OnCameraMoveStartedListener
anforderst, muss GoogleMap.setOnCameraMoveStartedListener()
aufgerufen werden.
Aus CameraPosition
kannst du das Ziel der Kamera (Breiten-/Längengrad), Zoom, Ausrichtung und Neigung abrufen. Weitere Informationen zu diesen Eigenschaften findest du im Leitfaden zur Kameraposition.
Ereignisse bei Unternehmen und anderen POIs
Standardmäßig werden Points of Interest (POIs) zusammen mit den entsprechenden Symbolen auf der Basiskarte dargestellt. POIs sind beispielsweise Parks, Schulen, Dienstgebäude sowie Unternehmen wie Geschäfte, Restaurants oder Hotels.
Auf Klickereignisse auf einem POI kannst du reagieren. Weitere Informationen erhältst du in der Anleitung zu Unternehmen und anderen POIs.
Ereignisse auf Indoor-Karten
Du kannst Ereignisse verwenden, um die aktive Ebene einer Indoor-Karte zu ermitteln und anzupassen. Verwende die Schnittstelle OnIndoorStateChangeListener
, um einen Listener festzulegen, der aufgerufen wird, wenn entweder ein neues Gebäude fokussiert oder eine neue Etage in einem Gebäude aktiviert wird.
Durch Aufrufen von GoogleMap.getFocusedBuilding()
kannst du das Gebäude abrufen, das derzeit im Fokus ist.
Wenn du die Karte an einem bestimmten Breiten-/Längengrad zentrierst, erhältst du in der Regel das Gebäude an diesen Koordinaten. Das ist jedoch nicht immer der Fall.
Anschließend kannst du die derzeit aktive Ebene durch Aufrufen von IndoorBuilding.getActiveLevelIndex()
ermitteln.
Java
IndoorBuilding building = map.getFocusedBuilding(); if (building != null) { int activeLevelIndex = building.getActiveLevelIndex(); IndoorLevel activeLevel = building.getLevels().get(activeLevelIndex); }
Kotlin
map.focusedBuilding?.let { building: IndoorBuilding -> val activeLevelIndex = building.activeLevelIndex val activeLevel = building.levels[activeLevelIndex] }
Das ist hilfreich, wenn du benutzerdefiniertes Markup für die aktive Ebene verwenden möchtest, etwa Markierungen, Boden-Overlays, Kachel-Overlays, Polygone, Polylinien oder andere Formen.
Hinweis: Um zur Straßenebene zurückzukehren, rufe die Standardebene über IndoorBuilding.getDefaultLevelIndex()
ab und lege sie mithilfe von IndoorLevel.activate()
als aktive Ebene fest.
Ereignisse bei Markierungen und Infofenstern
Um Reaktionen auf Markierungsereignisse (einschließlich Klick- und Ziehereignissen für Markierungen) zu ermöglichen, lege die entsprechenden Listener für das Objekt GoogleMap
fest, zu dem die Markierung gehört. Weitere Informationen findest du im Leitfaden zu Markierungsereignissen.
Du kannst auch Ereignisse in Infofenstern erfassen.
Form- und Overlay-Ereignisse
Du kannst Klickereignisse auf Polylinien, Polygone, Kreise und Boden-Overlays erfassen und darauf reagieren.
Standortereignisse
Deine App kann auf die folgenden Ereignisse reagieren, die mit der Ebene „Mein Standort“ zusammenhängen:
- Wenn der Nutzer auf die Schaltfläche „Mein Standort“ klickt, erhält deine App einen
onMyLocationButtonClick()
-Callback vomGoogleMap.OnMyLocationButtonClickListener
. - Klickt der Nutzer auf den blauen Punkt „Mein Standort“, erhält deine App einen
onMyLocationClick()
-Callback vomGoogleMap.OnMyLocationClickListener
.
Weitere Informationen findest du im Leitfaden zur Ebene „Mein Standort“.