Bằng cách sử dụng SDK Maps dành cho Android, bạn có thể theo dõi các sự kiện trên bản đồ.
Mã mẫu
Kho lưu trữ Apidemos trên GitHub bao gồm các mẫu minh hoạ các sự kiện và trình nghe:
Kotlin
- EventsDemoActivity: Các sự kiện thay đổi máy ảnh và sự kiện nhấp vào bản đồ
- CameraDemoActivity: Sự kiện thay đổi camera
- CircleDemoActivity: Sự kiện nhấp vào điểm đánh dấu và kéo
- GroundOverlayDemoActivity: Sự kiện nhấp vào lớp phủ mặt đất
- IndoorDemoActivity: Sự kiện trên bản đồ trong nhà
- MarkerDemoActivity: Điểm đánh dấu và các sự kiện trên cửa sổ thông tin
- PolygonDemoActivity: Sự kiện đa giác
Java
- EventsDemoActivity: Các sự kiện thay đổi máy ảnh và sự kiện nhấp vào bản đồ
- CameraDemoActivity: Sự kiện thay đổi camera
- CircleDemoActivity: Sự kiện nhấp vào điểm đánh dấu và kéo
- GroundOverlayDemoActivity: Sự kiện nhấp vào lớp phủ mặt đất
- IndoorDemoActivity: Sự kiện trên bản đồ trong nhà
- MarkerDemoActivity: Điểm đánh dấu và các sự kiện trên cửa sổ thông tin
- PolygonDemoActivity: Sự kiện đa giác
Sự kiện nhấp chuột vào bản đồ / nhấp chuột và giữ
Nếu muốn phản hồi người dùng nhấn vào một điểm trên bản đồ, bạn có thể sử dụng OnMapClickListener
mà bạn có thể đặt trên bản đồ bằng cách gọi GoogleMap.setOnMapClickListener(OnMapClickListener)
. Khi người dùng nhấp (nhấn) vào một nơi nào đó trên bản đồ, bạn sẽ nhận được một sự kiện onMapClick(LatLng)
cho biết vị trí trên bản đồ mà người dùng đã nhấp vào. Xin lưu ý rằng nếu cần vị trí tương ứng trên màn hình (tính bằng pixel), bạn có thể nhận Projection
từ bản đồ. Giá trị này cho phép bạn chuyển đổi giữa toạ độ vĩ độ/kinh độ và toạ độ pixel trên màn hình.
Bạn cũng có thể theo dõi các sự kiện nhấp chuột dài bằng OnMapLongClickListener
mà bạn có thể đặt trên bản đồ bằng cách gọi GoogleMap.setOnMapLongClickListener(OnMapLongClickListener)
.
Trình nghe này hoạt động tương tự như trình nghe lượt nhấp và sẽ được thông báo về các sự kiện nhấp dài bằng lệnh gọi lại onMapLongClick(LatLng)
.
Tắt sự kiện nhấp chuột ở chế độ thu gọn
Để tắt các sự kiện nhấp chuột trên bản đồ ở chế độ thu gọn, hãy gọi setClickable()
trên khung hiển thị chứa MapView
hoặc MapFragment
. Điều này rất hữu ích, chẳng hạn như khi hiển thị bản đồ hoặc các bản đồ ở chế độ xem danh sách, nơi bạn muốn sự kiện nhấp chuột gọi ra một hành động không liên quan đến bản đồ.
Lựa chọn tắt sự kiện nhấp chuột có chỉ trong chế độ thu gọn. Việc tắt sự kiện nhấp cũng sẽ khiến điểm đánh dấu không nhấp vào được. Chế độ này sẽ không ảnh hưởng đến các chế độ điều khiển khác trên bản đồ.
Đối với MapView
:
Kotlin
val mapView = findViewById<MapView>(R.id.mapView) mapView.isClickable = false
Java
MapView mapView = findViewById(R.id.mapView); mapView.setClickable(false);
Đối với 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);
Sự kiện thay đổi camera
Chế độ xem bản đồ được mô hình hoá như một máy ảnh nhìn xuống trên một mặt phẳng phẳng. Bạn có thể thay đổi các thuộc tính của máy ảnh để tác động đến mức thu phóng, cổng chế độ xem và góc nhìn của bản đồ. Xem hướng dẫn về máy ảnh. Người dùng cũng có thể tác động đến máy ảnh bằng cách thực hiện các cử chỉ.
Khi sử dụng trình nghe thay đổi camera, bạn có thể theo dõi chuyển động của camera. Ứng dụng của bạn có thể nhận thông báo cho các sự kiện bắt đầu, đang diễn ra và kết thúc liên quan đến chuyển động của máy ảnh. Bạn cũng có thể xem lý do máy ảnh di chuyển, cho dù đó là do cử chỉ của người dùng, ảnh động API tích hợp hay chuyển động do nhà phát triển kiểm soát.
Mẫu sau đây minh hoạ tất cả trình nghe sự kiện camera hiện có:
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) } }
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); } }
Bạn có thể sử dụng các trình nghe camera sau:
Lệnh gọi lại
onCameraMoveStarted()
củaOnCameraMoveStartedListener
được gọi khi máy ảnh bắt đầu di chuyển. Phương thức gọi lại nhận được mộtreason
cho chuyển động của camera. Lý do có thể là một trong những lý do sau:REASON_GESTURE
cho biết rằng máy ảnh đã di chuyển theo cử chỉ của người dùng trên bản đồ, chẳng hạn như kéo (hình ảnh), nghiêng, chụm để thu phóng hoặc xoay bản đồ.REASON_API_ANIMATION
cho biết rằng API đã di chuyển máy ảnh để phản hồi một hành động không cần dùng cử chỉ của người dùng, chẳng hạn như nhấn vào nút thu phóng, nhấn vào nút Vị trí của tôi hoặc nhấp vào một điểm đánh dấu.REASON_DEVELOPER_ANIMATION
cho biết rằng ứng dụng của bạn đã bắt đầu chuyển động cho camera.
Lệnh gọi lại
onCameraMove()
củaOnCameraMoveListener
được gọi nhiều lần trong khi camera đang di chuyển hoặc người dùng đang tương tác với màn hình cảm ứng. Như một hướng dẫn về tần suất lệnh gọi lại được gọi, bạn nên biết rằng API sẽ gọi lệnh gọi lại một lần cho mỗi khung hình. Tuy nhiên, xin lưu ý rằng lệnh gọi lại này được gọi không đồng bộ nên không đồng bộ với nội dung hiển thị trên màn hình. Ngoài ra, xin lưu ý rằng vị trí máy ảnh có thể không thay đổi trong một lần gọi lạionCameraMove()
cho đến lần gọi lại tiếp theo.Lệnh gọi lại
OnCameraIdle()
củaOnCameraIdleListener
được gọi khi máy ảnh ngừng di chuyển và người dùng ngừng tương tác với bản đồ.Lệnh gọi lại
OnCameraMoveCanceled()
củaOnCameraMoveCanceledListener
được gọi khi chuyển động hiện tại của camera bị gián đoạn. Ngay sau khi gọi lạiOnCameraMoveCanceled()
, lệnh gọi lạionCameraMoveStarted()
sẽ được gọi bằngreason
mới.Nếu ứng dụng của bạn gọi
GoogleMap.stopAnimation()
một cách rõ ràng, thì lệnh gọi lạiOnCameraMoveCanceled()
sẽ được gọi, nhưng lệnh gọi lạionCameraMoveStarted()
không được gọi.
Để thiết lập một trình nghe trên bản đồ, hãy gọi phương thức trình nghe tập hợp có liên quan.
Ví dụ: để yêu cầu gọi lại từ OnCameraMoveStartedListener
, hãy gọi GoogleMap.setOnCameraMoveStartedListener()
.
Bạn có thể xem mục tiêu của máy ảnh (vĩ độ/kinh độ), thu phóng, góc phương tiện và độ nghiêng từ CameraPosition
. Xem hướng dẫn về vị trí camera để biết thông tin chi tiết về các thuộc tính này.
Sự kiện về doanh nghiệp và các địa điểm yêu thích khác
Theo mặc định, các địa điểm yêu thích (POI) sẽ xuất hiện trên bản đồ cơ sở cùng với các biểu tượng tương ứng. POI bao gồm công viên, trường học, toà nhà chính phủ và các địa điểm khác, cũng như địa điểm yêu thích dành cho doanh nghiệp như cửa hàng, nhà hàng và khách sạn.
Bạn có thể phản hồi các sự kiện nhấp chuột vào POI. Xem hướng dẫn về doanh nghiệp và các địa điểm yêu thích khác.
Sự kiện trên bản đồ trong nhà
Bạn có thể sử dụng sự kiện để tìm và tuỳ chỉnh cấp độ hoạt động của bản đồ trong nhà. Sử dụng giao diện OnIndoorStateChangeListener
để thiết lập trình nghe được gọi khi một toà nhà mới được lấy làm tâm điểm hoặc một cấp mới được kích hoạt trong một toà nhà.
Xem toà nhà mà bạn đang xem bằng cách gọi GoogleMap.getFocusedBuilding()
.
Việc căn giữa bản đồ theo một vĩ độ/kinh độ cụ thể sẽ thường cung cấp cho bạn toà nhà tại vĩ độ/kinh độ đó, nhưng điều này không được đảm bảo.
Sau đó, bạn có thể tìm thấy cấp độ đang hoạt động bằng cách gọi 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); }
Thao tác này rất hữu ích nếu bạn muốn hiển thị mã đánh dấu tuỳ chỉnh cho cấp đang hoạt động, chẳng hạn như điểm đánh dấu, lớp phủ mặt đất, lớp phủ xếp kề, đa giác, hình nhiều đường và các hình dạng khác.
Gợi ý: Để quay lại cấp đường phố, hãy lấy cấp mặc định thông qua IndoorBuilding.getDefaultLevelIndex()
và đặt cấp đó thành cấp đang hoạt động thông qua IndoorLevel.activate()
.
Sự kiện điểm đánh dấu và cửa sổ thông tin
Bạn có thể theo dõi và phản hồi các sự kiện đánh dấu, bao gồm cả các sự kiện nhấp vào điểm đánh dấu và kéo, bằng cách thiết lập trình nghe tương ứng trên đối tượng GoogleMap
chứa điểm đánh dấu. Xem hướng dẫn về sự kiện điểm đánh dấu.
Bạn cũng có thể theo dõi các sự kiện trên cửa sổ thông tin.
Sự kiện về hình dạng và lớp phủ
Bạn có thể theo dõi và phản hồi các sự kiện nhấp chuột trên hình nhiều đường, đa giác, hình tròn và lớp phủ mặt đất.
Sự kiện theo địa điểm
Ứng dụng của bạn có thể phản hồi các sự kiện sau đây liên quan đến lớp Vị trí của tôi:
- Nếu người dùng nhấp vào nút Vị trí của tôi, thì ứng dụng sẽ nhận được lệnh gọi lại
onMyLocationButtonClick()
từGoogleMap.OnMyLocationButtonClickListener
. - Nếu người dùng nhấp vào chấm màu xanh dương Vị trí của tôi, ứng dụng sẽ nhận được lệnh gọi lại
onMyLocationClick()
từGoogleMap.OnMyLocationClickListener
.
Để biết thông tin chi tiết, hãy xem hướng dẫn tới lớp Vị trí của tôi.