Utilizzando Maps SDK for Android, puoi ascoltare gli eventi sulla mappa.
Esempi di codice
Il repository ApiDemos su GitHub include esempi che mostrano eventi e listener:
Kotlin
- EventsDemoActivity: eventi di clic sulla mappa e di modifica della videocamera
- CameraDemoActivity: eventi di modifica della videocamera
- CircleDemoActivity: eventi di clic e trascinamento degli indicatori
- GroundOverlayDemoActivity: eventi di clic sugli overlay del suolo
- IndoorDemoActivity: eventi della mappa di interni
- MarkerDemoActivity: eventi degli indicatori e delle finestre informative
- PolygonDemoActivity: eventi dei poligoni
Java
- EventsDemoActivity: eventi di clic sulla mappa e di modifica della videocamera
- CameraDemoActivity: eventi di modifica della videocamera
- CircleDemoActivity: eventi di clic e trascinamento degli indicatori
- GroundOverlayDemoActivity: eventi di clic sugli overlay del suolo
- IndoorDemoActivity: eventi della mappa di interni
- MarkerDemoActivity: eventi degli indicatori e delle finestre informative
- PolygonDemoActivity: eventi dei poligoni
Eventi di clic / clic prolungato sulla mappa
Se vuoi rispondere a un utente che tocca un punto sulla mappa, puoi utilizzare un
OnMapClickListener che puoi impostare sulla mappa
chiamando GoogleMap.setOnMapClickListener(OnMapClickListener). Quando un utente fa clic (tocca) da qualche parte sulla mappa, riceverai un evento onMapClick(LatLng) che indica la posizione sulla mappa su cui l'utente ha fatto clic. Tieni presente che
se hai bisogno della posizione corrispondente sullo schermo (in pixel), puoi
ottenere un Projection dalla mappa che ti consente di convertire
tra coordinate di latitudine/longitudine e coordinate di pixel dello schermo.
Puoi anche ascoltare gli eventi di clic prolungato con un
OnMapLongClickListener che puoi impostare sulla
mappa chiamando GoogleMap.setOnMapLongClickListener(OnMapLongClickListener).
Questo listener si comporta in modo simile al click listener e riceverà una notifica sugli eventi di clic prolungato con un callback onMapLongClick(LatLng).
Disattivare gli eventi di clic in modalità Lite
Per disattivare gli eventi di clic su una mappa in modalità Lite, chiama setClickable()
sulla visualizzazione che contiene MapView o MapFragment. Questa opzione è utile, ad esempio, quando visualizzi una o più mappe in una visualizzazione elenco, in cui vuoi che l'evento di clic richiami un'azione non correlata alla mappa.
L'opzione per disattivare gli eventi di clic è disponibile solo in modalità Lite. La disattivazione degli eventi di clic renderà anche gli indicatori non selezionabili. Non influirà sugli altri controlli della mappa.
Per un MapView:
Kotlin
val mapView = findViewById<MapView>(R.id.mapView) mapView.isClickable = false
Java
MapView mapView = findViewById(R.id.mapView); mapView.setClickable(false);
Per un MapFragment:
Kotlin
val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment val view = mapFragment.view view?.isClickable = false
Java
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); View view = mapFragment.getView(); view.setClickable(false);
Eventi di modifica della videocamera
La visualizzazione mappa è modellata come una videocamera che guarda verso il basso su un piano piatto. Puoi modificare le proprietà della videocamera per influire sul livello di zoom, sull'area visibile e sulla prospettiva della mappa. Consulta la guida alla videocamera. Gli utenti possono anche influire sulla videocamera eseguendo gesti.
Utilizzando i listener di modifica della videocamera, puoi tenere traccia dei movimenti della videocamera. La tua app può ricevere notifiche per gli eventi di inizio, in corso e fine del movimento della videocamera. Puoi anche vedere perché la videocamera si sta muovendo, se è causata da gesti dell'utente, animazioni API integrate o movimenti controllati dallo sviluppatore.
Il seguente esempio illustra tutti i listener di eventi della videocamera disponibili:
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 com.example.common_ui.R 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.example.common_ui.databinding.CameraDemoBinding import com.google.android.gms.maps.model.PolylineOptions /** * This shows how to change the camera position for the map. */ class CameraDemoActivity : SamplesBaseActivity(), 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 private lateinit var binding: CameraDemoBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = CameraDemoBinding.inflate(layoutInflater) setContentView(binding.root) animateToggle = binding.animate customDurationToggle = binding.durationToggle customDurationBar = binding.durationBar updateEnabledState() val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) applyInsets(binding.mapContainer) binding.bondi.setOnClickListener(this::onGoToBondi) binding.sydney.setOnClickListener(this::onGoToSydney) binding.stopAnimation.setOnClickListener(this::onStopAnimation) binding.animate.setOnClickListener(this::onToggleAnimate) binding.scrollLeft.setOnClickListener(this::onScrollLeft) binding.scrollUp.setOnClickListener(this::onScrollUp) binding.scrollDown.setOnClickListener(this::onScrollDown) binding.scrollRight.setOnClickListener(this::onScrollRight) binding.zoomIn.setOnClickListener(this::onZoomIn) binding.zoomOut.setOnClickListener(this::onZoomOut) binding.tiltMore.setOnClickListener(this::onTiltMore) binding.tiltLess.setOnClickListener(this::onTiltLess) binding.durationToggle.setOnClickListener(this::onToggleCustomDuration) } override fun onResume() { super.onResume() updateEnabledState() } override fun onMapReady(googleMap: GoogleMap) { map = googleMap // return early if the map was not initialised properly 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) } }
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.example.common_ui.databinding.CameraDemoBinding; import com.google.android.gms.maps.model.PolylineOptions; /** * This shows how to change the camera position for the map. */ public class CameraDemoActivity extends SamplesBaseActivity 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; private CameraDemoBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = CameraDemoBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); animateToggle = binding.animate; customDurationToggle = binding.durationToggle; customDurationBar = binding.durationBar; updateEnabledState(); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(com.example.common_ui.R.id.map); mapFragment.getMapAsync(this); applyInsets(binding.mapContainer); binding.bondi.setOnClickListener(this::onGoToBondi); binding.sydney.setOnClickListener(this::onGoToSydney); binding.stopAnimation.setOnClickListener(this::onStopAnimation); binding.animate.setOnClickListener(this::onToggleAnimate); binding.scrollLeft.setOnClickListener(this::onScrollLeft); binding.scrollUp.setOnClickListener(this::onScrollUp); binding.scrollDown.setOnClickListener(this::onScrollDown); binding.scrollRight.setOnClickListener(this::onScrollRight); binding.zoomIn.setOnClickListener(this::onZoomIn); binding.zoomOut.setOnClickListener(this::onZoomOut); binding.tiltMore.setOnClickListener(this::onTiltMore); binding.tiltLess.setOnClickListener(this::onTiltLess); binding.durationToggle.setOnClickListener(this::onToggleCustomDuration); } @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)); } public GoogleMap getMap() { return map; } /** * 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, com.example.common_ui.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); } }
Sono disponibili i seguenti listener della videocamera:
Il callback
onCameraMoveStarted()diOnCameraMoveStartedListenerviene richiamato quando la videocamera inizia a muoversi. Il metodo di callback riceve unreasonper il movimento della videocamera. Il motivo può essere uno dei seguenti:REASON_GESTUREindica che la videocamera si è spostata in risposta a un gesto dell'utente sulla mappa, ad esempio panoramica, inclinazione, pizzicamento per lo zoom o rotazione della mappa.REASON_API_ANIMATIONindica che l'API ha spostato la videocamera in risposta a un'azione dell'utente non basata su gesti, ad esempio toccando il pulsante zoom, toccando il pulsante Posizione o facendo clic su un indicatore.REASON_DEVELOPER_ANIMATIONindica che la tua app ha avviato il movimento della videocamera.
Il callback
onCameraMove()diOnCameraMoveListenerviene richiamato più volte mentre la videocamera è in movimento o l'utente interagisce con il touch screen. Come guida alla frequenza con cui viene richiamato il callback, è utile sapere che l'API richiama il callback una volta per frame. Tieni presente, tuttavia, che questo callback viene richiamato in modo asincrono e quindi non è sincronizzato con ciò che è visibile sullo schermo. Tieni presente, inoltre, che è possibile che la posizione della videocamera rimanga invariata tra un callbackonCameraMove()e l'altro.Il callback
OnCameraIdle()diOnCameraIdleListenerviene richiamato quando la videocamera smette di muoversi e l'utente ha smesso di interagire con la mappa.Il callback
OnCameraMoveCanceled()diOnCameraMoveCanceledListenerviene richiamato quando il movimento corrente della videocamera è stato interrotto. Subito dopo il callbackOnCameraMoveCanceled(), viene richiamato il callbackonCameraMoveStarted()con il nuovoreason.Se la tua app chiama esplicitamente
GoogleMap.stopAnimation(), viene richiamato ilOnCameraMoveCanceled()callback, ma ilonCameraMoveStarted()callback non viene richiamato.
Per impostare un listener sulla mappa, chiama il metodo set-listener pertinente.
Ad esempio, per richiedere un callback da OnCameraMoveStartedListener, chiama
GoogleMap.setOnCameraMoveStartedListener().
Puoi ottenere la destinazione (latitudine/longitudine), lo zoom, la direzione e l'inclinazione della videocamera
da CameraPosition. Per informazioni dettagliate su queste proprietà, consulta la guida alla
posizione della videocamera.
Eventi su attività e altri punti di interesse
Per impostazione predefinita, i punti di interesse (PDI) vengono visualizzati sulla mappa base insieme alle icone corrispondenti. I PDI includono parchi, scuole, edifici governativi e altro ancora, nonché PDI aziendali come negozi, ristoranti e hotel.
Puoi rispondere agli eventi di clic su un PDI. Consulta la guida alle attività e ad altri punti di interesse.
Eventi della mappa di interni
Puoi utilizzare gli eventi per trovare e personalizzare il livello attivo di una mappa di interni. Utilizza
l'interfaccia OnIndoorStateChangeListener
per impostare un listener da chiamare quando
viene messo a fuoco un nuovo edificio o viene attivato un nuovo livello in un edificio.
Ottieni l'edificio attualmente messo a fuoco chiamando
GoogleMap.getFocusedBuilding().
Centrare la mappa su una latitudine/longitudine specifica in genere ti darà l'edificio a quella latitudine/longitudine, ma non è garantito.
Puoi quindi trovare il livello attualmente attivo chiamando
IndoorBuilding.getActiveLevelIndex().
Kotlin
map.focusedBuilding?.let { building: IndoorBuilding -> val activeLevelIndex = building.activeLevelIndex val activeLevel = building.levels[activeLevelIndex] }
Java
IndoorBuilding building = map.getFocusedBuilding(); if (building != null) { int activeLevelIndex = building.getActiveLevelIndex(); IndoorLevel activeLevel = building.getLevels().get(activeLevelIndex); }
Questa opzione è utile se vuoi mostrare markup personalizzati per il livello attivo, come indicatori, overlay del suolo, overlay di riquadri, poligoni, polilinee e altre forme.
Suggerimento: per tornare al livello della strada, ottieni il livello predefinito tramite IndoorBuilding.getDefaultLevelIndex() e impostalo come livello attivo tramite IndoorLevel.activate().
Eventi degli indicatori e delle finestre informative
Puoi ascoltare e rispondere agli eventi degli indicatori, inclusi gli eventi di clic e trascinamento degli indicatori, impostando il listener corrispondente sull'oggetto GoogleMap a cui appartiene l'indicatore. Consulta la guida agli eventi degli indicatori.
Puoi anche ascoltare gli eventi nelle finestre informative.
Eventi di forme e overlay
Puoi ascoltare e rispondere agli eventi di clic su polilinee, poligoni, cerchi, e overlay del suolo.
Eventi di posizione
La tua app può rispondere ai seguenti eventi relativi al livello La mia posizione:
- Se l'utente fa clic sul pulsante La mia posizione, la tua app riceve un
onMyLocationButtonClick()callback daGoogleMap.OnMyLocationButtonClickListener. - Se l'utente fa clic sul punto blu La mia posizione, la tua app riceve un
onMyLocationClick()callback daGoogleMap.OnMyLocationClickListener.
Per maggiori dettagli, consulta la guida al livello La mia posizione.