Android용 Maps SDK를 사용하면 지도에서 이벤트를 수신할 수 있습니다.
코드 샘플
GitHub의 ApiDemos 저장소에는 이벤트와 리스너를 보여주는 샘플이 있습니다.
Kotlin
- EventsDemoActivity: 지도 클릭 및 카메라 변경 이벤트
- CameraDemoActivity: 카메라 변경 이벤트
- CircleDemoActivity: 마커 클릭 및 드래그 이벤트
- GroundOverlayDemoActivity: 지면 오버레이 클릭 이벤트
- IndoorDemoActivity: 실내 지도 이벤트
- MarkerDemoActivity: 마커 및 정보 창 이벤트
- PolygonDemoActivity: 다각형 이벤트
Java
- EventsDemoActivity: 지도 클릭 및 카메라 변경 이벤트
- CameraDemoActivity: 카메라 변경 이벤트
- CircleDemoActivity: 마커 클릭 및 드래그 이벤트
- GroundOverlayDemoActivity: 지면 오버레이 클릭 이벤트
- IndoorDemoActivity: 실내 지도 이벤트
- MarkerDemoActivity: 마커 및 정보 창 이벤트
- PolygonDemoActivity: 다각형 이벤트
지도 클릭/긴 클릭 이벤트
지도에서 GoogleMap.setOnMapClickListener(OnMapClickListener)
를 호출해서 설정하는
OnMapClickListener
를 사용하면 지도에서 특정 지점을 탭한 사용자에게 응답할 수 있습니다. 사용자가
지도의 한 지점을 클릭(탭)하면 지도에서 사용자가 클릭한
위치를 나타내는 onMapClick(LatLng)
이벤트가 수신됩니다. 화면에 이러한 위치(픽셀 단위)를 표시해야 하면 위도/경도 좌표와 화면 픽셀 좌표 간에 변환할 수 있도록 지원하는 Projection
을 지도에서 가져오세요.
지도에서 GoogleMap.setOnMapLongClickListener(OnMapLongClickListener)
를 호출하여 설정할 수 있는
OnMapLongClickListener
를 이용해 긴 클릭 이벤트를
수신할 수도 있습니다.
이 리스너는 클릭 리스너와 유사하게 작동하며
onMapLongClick(LatLng)
콜백과 함께 긴 클릭 이벤트가 발생할 경우 알림을 받게 됩니다.
라이트 모드에서 클릭 이벤트 사용 중지
라이트 모드에서 지도의 클릭 이벤트를 사용 중지하려면 MapView
또는 MapFragment
가 포함된 보기에서 setClickable()
을 호출하세요. 이 방법은 예를 들어 1개 이상의 지도를 목록 보기에 표시하고, 이 보기에서 클릭 이벤트 발생 시 지도와 관련이 없는 작업을 호출하려는 경우에 유용합니다.
클릭 이벤트를 사용 중지하는 옵션은 라이트 모드에서만 사용할 수 있습니다. 클릭 이벤트를 사용 중지하면 마커도 클릭할 수 없게 됩니다. 지도의 다른 컨트롤에는 영향을 미치지 않습니다.
MapView
의 경우:
val mapView = findViewById<MapView>(R.id.mapView)
mapView.isClickable = false
MapView mapView = findViewById(R.id.mapView);
mapView.setClickable(false);
MapFragment
의 경우:
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
val view = mapFragment.view
view?.isClickable = false
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
View view = mapFragment.getView();
view.setClickable(false);
카메라 변경 이벤트
지도뷰는 카메라가 평면을 내려다보는 것을 모델링하여 표시됩니다. 카메라의 속성을 변경하여 지도의 확대/축소 수준, 표시 영역, 시점을 바꿀 수 있습니다. 카메라 가이드를 참고하세요. 사용자는 동작을 통해 카메라에 영향을 미칠 수도 있습니다.
카메라 변경 리스너를 사용하면 카메라 움직임을 추적할 수 있습니다. 앱에서 카메라 움직임의 시작, 진행, 종료 이벤트에 대한 알림을 수신할 수 있습니다. 카메라가 움직이는 이유, 즉 카메라의 움직임이 사용자 동작에 의해 발생했는지, 기본 제공된 API 애니메이션이나 개발자가 조절하는 움직임에 의해 발생했는지 확인할 수도 있습니다.
다음 샘플에서는 사용 가능한 모든 카메라 이벤트 리스너를 보여줍니다.
/*
* 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)
}
}
// 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);
}
}
다음과 같은 카메라 리스너를 사용할 수 있습니다.
카메라가 움직이기 시작하면
OnCameraMoveStartedListener
의onCameraMoveStarted()
콜백이 호출됩니다. 콜백 메서드는 카메라 움직임에 대한reason
을 수신합니다. 다음 중 하나의 경우일 수 있습니다.REASON_GESTURE
: 지도 화면 이동, 기울이기, 손가락을 모으거나 벌려 확대/축소, 회전 등 지도에서 사용자의 동작에 따라 카메라가 움직였음을 나타냅니다.REASON_API_ANIMATION
: 확대/축소 버튼 탭, 내 위치 버튼 탭, 마커 클릭 등 사용자의 동작이 아닌 작업에 따라 API가 카메라를 움직였음을 나타냅니다.REASON_DEVELOPER_ANIMATION
: 앱에서 카메라를 움직이기 시작했음을 나타냅니다.
카메라가 움직이거나 사용자가 터치 스크린과 상호작용하는 동안
OnCameraMoveListener
의onCameraMove()
콜백이 여러 번 호출됩니다. API에서 프레임당 콜백을 한 번 호출한다는 점을 알면 콜백이 호출되는 빈도를 알 수 있습니다. 하지만 이 콜백은 비동기식으로 호출되므로 화면에 표시되는 내용과 일치하지 않습니다. 또한 하나의onCameraMove()
콜백과 그 다음 콜백 사이에 카메라 위치가 변경되지 않을 수 있습니다.카메라가 움직임을 중지하고 사용자가 지도와의 상호작용을 중지하면
OnCameraIdleListener
의OnCameraIdle()
콜백이 호출됩니다.현재 카메라 움직임이 중단된 경우
OnCameraMoveCanceledListener
의OnCameraMoveCanceled()
콜백이 호출됩니다.OnCameraMoveCanceled()
콜백 직후onCameraMoveStarted()
콜백이 새reason
과 함께 호출됩니다.앱에서
GoogleMap.stopAnimation()
을 명시적으로 호출하면OnCameraMoveCanceled()
콜백이 호출되지만onCameraMoveStarted()
콜백은 호출되지 않습니다.
지도에 리스너를 설정하려면 관련 set-listener 메서드를 호출하세요.
예를 들어 OnCameraMoveStartedListener
의 콜백을 요청하려면
GoogleMap.setOnCameraMoveStartedListener()
를 호출하세요.
CameraPosition
에서 카메라의 타겟(위도/경도), 확대/축소, 방위, 기울기를
가져올 수 있습니다. 이러한 속성에 대한
자세한 내용은 카메라 위치 가이드를 참고하세요.
비즈니스 및 기타 관심 장소의 이벤트
기본적으로 관심 장소(POI)는 해당 아이콘과 함께 기본 지도에 표시됩니다. 관심 장소에는 공원, 학교, 정부 건물 등은 물론 상점, 음식점, 호텔 등 비즈니스 관심 장소도 포함됩니다.
관심 장소의 클릭 이벤트에 응답할 수 있습니다. 비즈니스 및 기타 관심 장소 가이드를 참고하세요.
실내 지도 이벤트
이벤트를 사용하여 실내 지도의 활성 층을 찾아 맞춤설정할 수 있습니다. 새 건물에 포커스가 지정되거나 건물에서 새 층이 활성화될 때 호출되는 리스너를 설정하려면 OnIndoorStateChangeListener
인터페이스를 사용하세요.
GoogleMap.getFocusedBuilding()
을
호출하여 현재 포커스가 지정된 건물을 표시합니다.
특정 위도/경도에 지도의 중심을 맞추면
일반적으로 해당 위도/경도의 건물이 표시되지만 반드시 그런 것은 아닙니다.
그런 다음 IndoorBuilding.getActiveLevelIndex()
를
호출하여 현재 활성 층을 찾을 수 있습니다.
map.focusedBuilding?.let { building: IndoorBuilding ->
val activeLevelIndex = building.activeLevelIndex
val activeLevel = building.levels[activeLevelIndex]
}
IndoorBuilding building = map.getFocusedBuilding();
if (building != null) {
int activeLevelIndex = building.getActiveLevelIndex();
IndoorLevel activeLevel = building.getLevels().get(activeLevelIndex);
}
이 기능은 마커, 지면 오버레이, 타일 오버레이, 다각형, 다중선, 기타 도형 등 활성 층의 맞춤 마크업을 표시하려는 경우 유용합니다.
참고: 거리 수준으로 돌아가려면
IndoorBuilding.getDefaultLevelIndex()
를 통해 기본 층을 가져와
IndoorLevel.activate()
를 통해 활성 층으로 설정하세요.
마커 및 정보 창 이벤트
마커가 속한 GoogleMap
객체에 대응하는 리스너를 설정하여 마커 클릭 및 드래그 이벤트 등 마커 이벤트를 수신 대기하고 마커 이벤트에 응답할 수 있습니다. 마커 이벤트 가이드를 참고하세요.
정보 창에서 이벤트를 수신할 수도 있습니다.
도형 및 오버레이 이벤트
다중선, 다각형, 원, 지면 오버레이의 클릭 이벤트를 수신하고 클릭 이벤트에 응답할 수 있습니다.
위치 이벤트
앱에서 내 위치 레이어와 관련된 다음 이벤트에 응답할 수 있습니다.
- 사용자가 내 위치 버튼을 클릭하면 앱이
GoogleMap.OnMyLocationButtonClickListener
에서onMyLocationButtonClick()
콜백을 수신합니다. - 사용자가 내 위치를 나타내는 파란색 점을 클릭하면 앱이
GoogleMap.OnMyLocationClickListener
에서onMyLocationClick()
콜백을 수신합니다.
자세한 내용은 내 위치 레이어 가이드를 참고하세요.