5.30

所花时间(包括上课):1.5

打码量(行):230

博客量(篇):1

了解到知识点:学习地图点击事件

 

 package com.example.myapp;

 

import android.os.Bundle;

import android.widget.Toast;

 

import androidx.appcompat.app.AppCompatActivity;

 

import com.google.android.gms.maps.CameraUpdateFactory;

import com.google.android.gms.maps.GoogleMap;

import com.google.android.gms.maps.OnMapReadyCallback;

import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.LatLng;

import com.google.android.gms.maps.model.MarkerOptions;

 

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMapClickListener {

 

    private GoogleMap googleMap;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()

                .findFragmentById(R.id.mapFragment);

        if (mapFragment != null) {

            mapFragment.getMapAsync(this);

        }

    }

 

    @Override

    public void onMapReady(GoogleMap googleMap) {

        this.googleMap = googleMap;

 

        // 设置地图点击监听器

        googleMap.setOnMapClickListener(this);

    }

 

    @Override

    public void onMapClick(LatLng latLng) {

        // 处理地图点击事件

        Toast.makeText(this, "Clicked on Lat: " + latLng.latitude + ", Lng: " + latLng.longitude,

                Toast.LENGTH_SHORT).show();

 

        // 添加标记示例

        googleMap.addMarker(new MarkerOptions().position(latLng).title("Clicked Location"));

        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    }

}

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

 

    <fragment

        android:id="@+id/mapFragment"

        android:name="com.google.android.gms.maps.SupportMapFragment"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:layout_marginTop="?android:attr/actionBarSize"

        android:layout_alignParentTop="true"

        android:layout_alignParentStart="true" />

 

</RelativeLayout>

posted @ 2024-05-30 21:43  赵千万  阅读(2)  评论(0编辑  收藏  举报