Événements

Sélectionnez une plate-forme : Android iOS JavaScript

Le SDK Maps pour Android vous permet d'écouter des événements qui se produisent sur la carte.

Exemples de code

Le dépôt ApiDemos sur GitHub inclut des exemples qui montrent comment fonctionnent les événements et les écouteurs :

Java

Kotlin

Événements liés aux clics sur la carte et aux clics longs

Pour répondre à un utilisateur qui appuie sur un point de la carte, vous pouvez utiliser un OnMapClickListener (appelez GoogleMap.setOnMapClickListener(OnMapClickListener) pour le définir sur la carte). Lorsqu'un utilisateur clique (appuie) quelque part sur la carte, vous recevez un événement onMapClick(LatLng) qui indique l'emplacement en question. Notez que si vous avez besoin de la position correspondante sur l'écran (en pixels), vous pouvez obtenir une Projection de la carte qui vous permet de convertir les coordonnées de latitude/longitude en coordonnées en pixels à l'écran.

Vous pouvez également écouter les événements de clic long avec un OnMapLongClickListener (appelez GoogleMap.setOnMapLongClickListener(OnMapLongClickListener) pour le définir sur la carte). Cet écouteur se comporte de la même façon que l'écouteur de clic et sera averti des événements de clic long avec un rappel onMapLongClick(LatLng).

Désactiver les événements de clic en mode simplifié

Pour désactiver les événements de clic sur une carte en mode simplifié, appelez setClickable() sur la vue contenant la MapView ou le MapFragment. Cette démarche est utile, par exemple, pour afficher une ou plusieurs cartes sous forme de liste, où l'événement de clic doit appeler une action sans rapport avec la carte.

L'option permettant de désactiver les événements de clic est disponible en mode simplifié uniquement. Désactiver les événements de clic rend également les repères non cliquables et n'a aucun impact sur les autres commandes de la carte.

Pour une MapView :

Java


MapView mapView = findViewById(R.id.mapView);
mapView.setClickable(false);

      

Kotlin


val mapView = findViewById<MapView>(R.id.mapView)
mapView.isClickable = false

      

Pour un 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

      

Événements liés aux changements de caméra

La vue de la carte est modélisée comme une caméra orientée vers le bas sur une surface plane. Vous pouvez modifier les propriétés de la caméra pour agir sur le niveau de zoom, la fenêtre d'affichage et la perspective de la carte. Consultez le guide dédié à la caméra. Les utilisateurs peuvent également agir sur la caméra à l'aide de gestes.

Les écouteurs de changement de caméra vous permettent de suivre les mouvements de la caméra. Votre application peut recevoir des notifications qui lui signalent les événements de mouvement de la caméra (début, fin et mouvement en cours). Découvrez aussi pourquoi la caméra se déplace (gestes de l'utilisateur, animations intégrées à l'API ou mouvements contrôlés par les développeurs).

L'exemple de code suivant illustre tous les écouteurs d'événement de caméra disponibles :

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) {
        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)
    }
}

Les écouteurs de caméra suivants sont disponibles :

  • Le rappel onCameraMoveStarted() de OnCameraMoveStartedListener est invoqué lorsque la caméra commence à se déplacer. La méthode de rappel reçoit le motif (reason) du mouvement de la caméra. Voici les différents motifs possibles :

    • REASON_GESTURE indique que la caméra s'est déplacée en réponse à un geste de l'utilisateur sur la carte (panoramique, inclinaison, zoom par pincement ou rotation de la carte, par exemple).
    • REASON_API_ANIMATION indique que l'API a déplacé la caméra en réponse à une action non gestuelle de l'utilisateur (appui sur le bouton de zoom, sur le bouton "Ma position" ou sur un repère).
    • REASON_DEVELOPER_ANIMATION indique que votre application a initié le mouvement de la caméra.
  • Le rappel onCameraMove() de OnCameraMoveListener est invoqué plusieurs fois lorsque la caméra se déplace ou lorsque l'utilisateur interagit avec l'écran tactile. Pour vous faire une idée de la fréquence à laquelle les rappels sont invoqués, notez que l'API invoque le rappel une fois par image. Toutefois, ce rappel est invoqué de manière asynchrone. Il n'est donc pas synchronisé avec ce qui est visible à l'écran. En outre, il est possible que la caméra ne change pas de position entre un rappel onCameraMove() et le suivant.

  • Le rappel OnCameraIdle() de OnCameraIdleListener est invoqué lorsque la caméra cesse de se déplacer et que l'utilisateur n'interagit plus avec la carte.

  • Le rappel OnCameraMoveCanceled() de OnCameraMoveCanceledListener est invoqué en cas d'interruption du déplacement de la caméra. Immédiatement après le rappel OnCameraMoveCanceled(), le rappel onCameraMoveStarted() est invoqué avec la nouvelle reason.

    Si votre application appelle explicitement GoogleMap.stopAnimation(), le rappel OnCameraMoveCanceled() est invoqué, mais pas le rappel onCameraMoveStarted().

Pour définir un écouteur sur la carte, appelez la méthode de définition d'écouteur appropriée. Par exemple, pour demander un rappel à partir de OnCameraMoveStartedListener, appelez GoogleMap.setOnCameraMoveStartedListener().

Pour obtenir la cible de la caméra (latitude/longitude), le niveau de zoom, la direction et l'inclinaison, vous pouvez utiliser CameraPosition. Consultez le guide dédié à la position de la caméra pour en savoir plus sur ces propriétés.

Événements liés aux établissements et aux autres points d'intérêt

Par défaut, les points d'intérêt (POI) s'affichent sur la carte de base avec les icônes correspondantes. Les POI comprennent les parcs, les écoles, les bâtiments administratifs et d'autres lieux similaires, ainsi que des POI commerciaux (magasins, restaurants et hôtels, par exemple).

Vous pouvez répondre aux événements de clic sur un POI. Consultez le guide sur les établissements et autres points d'intérêt.

Événements liés aux plans d'intérieur

Vous pouvez utiliser des événements pour rechercher et personnaliser le niveau actif d'un plan d'intérieur. Utilisez l'interface OnIndoorStateChangeListener pour définir un écouteur à appeler lorsqu'un nouveau bâtiment entre dans le champ de vision ou lorsqu'un nouveau niveau est activé dans un bâtiment.

Obtenez le bâtiment qui se trouve actuellement dans le champ de vision en appelant GoogleMap.getFocusedBuilding(). Centrer la carte sur une latitude/longitude spécifique vous permet en général d'obtenir le bâtiment se trouvant à cette latitude/longitude, mais ce n'est pas garanti.

Vous pouvez alors trouver le niveau actuellement actif en appelant IndoorBuilding.getActiveLevelIndex().

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]
}

      

Cette approche permet d'afficher un balisage personnalisé pour le niveau actif, comme des repères, des superpositions au sol, des superpositions de tuiles, des polygones, des polylignes et d'autres formes.

Conseil : Pour revenir au niveau de la rue, obtenez le niveau par défaut via IndoorBuilding.getDefaultLevelIndex() et définissez-le comme niveau actif via IndoorLevel.activate().

Événements liés aux repères et aux fenêtres d'informations

Pour écouter les événements de repère et y répondre (y compris les événements de clic et de déplacement de repère), définissez l'écouteur correspondant sur l'objet GoogleMap auquel le repère appartient. Consultez le guide des événements de repère.

Vous pouvez également écouter les événements sur les fenêtres d'informations.

Événements liés aux formes et aux superpositions

Vous pouvez écouter les événements de clic sur les polylignes, les polygones, les cercles et les superpositions au sol, et y répondre.

Événements liés à la localisation

Votre application peut répondre aux événements suivants liés au calque "Ma position" :

Pour en savoir plus, consultez le guide dédié au calque "Ma position".