本例說明如何監聽及處理地圖上的一些事件。
詳情請參閱說明文件。
開始使用
請務必先設定開發環境,再試用程式碼範例。詳情請參閱「Maps SDK for Android 程式碼範例」一文。
查看程式碼
class EventsDemoActivity : AppCompatActivity(), OnMapClickListener,
OnMapLongClickListener, OnCameraIdleListener, OnMapReadyCallback {
private lateinit var tapTextView: TextView
private lateinit var cameraTextView: TextView
private lateinit var map: GoogleMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.events_demo)
tapTextView = findViewById(R.id.tap_text)
cameraTextView = findViewById(R.id.camera_text)
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
// return early if the map was not initialised properly
map = googleMap
map.setOnMapClickListener(this)
map.setOnMapLongClickListener(this)
map.setOnCameraIdleListener(this)
}
override fun onMapClick(point: LatLng) {
tapTextView.text = "tapped, point=$point"
}
override fun onMapLongClick(point: LatLng) {
tapTextView.text = "long pressed, point=$point"
}
override fun onCameraIdle() {
if (!::map.isInitialized) return
cameraTextView.text = map.cameraPosition.toString()
}
}
public class EventsDemoActivity extends AppCompatActivity
implements OnMapClickListener, OnMapLongClickListener, OnCameraIdleListener,
OnMapReadyCallback {
private TextView tapTextView;
private TextView cameraTextView;
private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events_demo);
tapTextView = findViewById(R.id.tap_text);
cameraTextView = findViewById(R.id.camera_text);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
this.map = map;
this.map.setOnMapClickListener(this);
this.map.setOnMapLongClickListener(this);
this.map.setOnCameraIdleListener(this);
}
@Override
public void onMapClick(LatLng point) {
tapTextView.setText("tapped, point=" + point);
}
@Override
public void onMapLongClick(LatLng point) {
tapTextView.setText("long pressed, point=" + point);
}
@Override
public void onCameraIdle() {
cameraTextView.setText(map.getCameraPosition().toString());
}
}
複製並執行範例
需要使用 Git 才能在本機執行這個範例。下列指令會複製範例應用程式存放區。
git clone git@github.com:googlemaps-samples/android-samples.git
將範例專案匯入 Android Studio:
- 在 Android Studio 中,選取「File」(檔案) >「New」(新增) >「Import Project」(匯入專案)。
前往您儲存存放區的位置,然後選取 Kotlin 或 Java 的專案目錄:
- Kotlin:
PATH-REPO/android-samples/ApiDemos/kotlin
- Java:
PATH-REPO/android-samples/ApiDemos/java
- Kotlin:
- 選取「開啟」。Android Studio 會使用 Gradle 建構工具來建立您的專案。
- 在專案的
local.properties
檔案所處目錄,建立空白的secrets.properties
檔案。詳情請參閱「將 API 金鑰加到專案」一文。 將下列字串加到
secrets.properties
,並將 YOUR_API_KEY 換成您 API 金鑰的值:MAPS_API_KEY=
YOUR_API_KEY - 執行應用程式。