Ví dụ này tạo một bản đồ bằng cách sử dụng SupportMapFragment
từ SDK Bản đồ dành cho Android.
Để biết thêm thông tin, hãy xem tài liệu.
Bắt đầu
Trước khi có thể thử mã mẫu, bạn phải định cấu hình môi trường phát triển. Để biết thêm thông tin, hãy xem Mã mẫu SDK Bản đồ dành cho Android.
Xem mã
class BasicMapDemoActivity : AppCompatActivity(), OnMapReadyCallback { val SYDNEY = LatLng(-33.862, 151.21) val ZOOM_LEVEL = 13f override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_basic_map_demo) val mapFragment : SupportMapFragment? = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment mapFragment?.getMapAsync(this) } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just move the camera to Sydney and add a marker in Sydney. */ override fun onMapReady(googleMap: GoogleMap) { with(googleMap) { moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, ZOOM_LEVEL)) addMarker(MarkerOptions().position(SYDNEY)) } } }
public class BasicMapDemoActivity extends SamplesBaseActivity implements OnMapReadyCallback { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.basic_demo); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); applyInsets(findViewById(R.id.map_container)); } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, * we * just add a marker near Africa. */ @Override public void onMapReady(GoogleMap map) { map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker")); } }
Sao chép và chạy các mẫu
Bạn cần có Git để chạy mẫu này trên máy. Lệnh sau đây sẽ sao chép kho lưu trữ ứng dụng mẫu.
git clone git@github.com:googlemaps-samples/android-samples.git
Nhập dự án mẫu vào Android Studio:
- Trong Android Studio, hãy chọn File > New > Import Project (Tệp > Mới > Nhập dự án).
Chuyển đến vị trí bạn đã lưu kho lưu trữ và chọn thư mục dự án cho Kotlin hoặc Java:
- Kotlin:
PATH-REPO/android-samples/ApiDemos/kotlin
- Java:
PATH-REPO/android-samples/ApiDemos/java
- Kotlin:
- Chọn Mở. Android Studio sẽ tạo dự án của bạn bằng công cụ bản dựng Gradle.
- Tạo một tệp
secrets.properties
trống trong cùng thư mục với tệplocal.properties
của dự án. Để biết thêm thông tin về tệp này, hãy xem phần Thêm khoá API vào dự án. - Lấy khoá API từ dự án của bạn bằng cách bật SDK Bản đồ dành cho Android.
Thêm chuỗi sau vào
secrets.properties
, thay thế YOUR_API_KEY bằng giá trị của khoá API:MAPS_API_KEY=
YOUR_API_KEY - Chạy ứng dụng.