Thêm bản đồ bằng điểm đánh dấu

Hướng dẫn này cho bạn biết cách thêm bản đồ của Google vào ứng dụng Android. Bản đồ bao gồm một điểm đánh dấu (còn gọi là ghim) để cho biết một vị trí cụ thể.

Làm theo hướng dẫn để tạo ứng dụng Android bằng cách sử dụng SDK Maps dành cho Android. Môi trường phát triển đề xuất là Android Studio.

Lấy mã

Nhân bản hoặc tải kho lưu trữ Mẫu Android API phiên bản 2 của Google Maps xuống từ GitHub.

Xem phiên bản Java của hoạt động:

    // 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.mapwithmarker;

import android.os.Bundle;
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;

/**
 * An activity that displays a Google map with a marker (pin) to indicate a particular location.
 */
public class MapsMarkerActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user receives a prompt to install
     * Play services inside the SupportMapFragment. The API invokes this method after the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(-33.852, 151.211);
        googleMap.addMarker(new MarkerOptions()
            .position(sydney)
            .title("Marker in Sydney"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

    

Xem phiên bản Kotlin của hoạt động:

    // 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.mapwithmarker

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

/**
 * An activity that displays a Google map with a marker (pin) to indicate a particular location.
 */
class MapsMarkerActivity : AppCompatActivity(), OnMapReadyCallback {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)

        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
      val sydney = LatLng(-33.852, 151.211)
      googleMap.addMarker(
        MarkerOptions()
          .position(sydney)
          .title("Marker in Sydney")
      )
      googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

    

Thiết lập dự án phát triển

Làm theo các bước sau để tạo dự án hướng dẫn trong Android Studio.

  1. Tảicài đặt Android Studio.
  2. Thêm gói Dịch vụ Google Play vào Android Studio.
  3. Nhân bản hoặc tải kho lưu trữ Mẫu dành cho Android API phiên bản 2 của Google Maps xuống nếu bạn không làm việc đó khi bắt đầu đọc hướng dẫn này.
  4. Nhập dự án hướng dẫn:

    • Trong Android Studio, hãy chọn File > New > Import Project (Tệp > Mới > Nhập dự án).
    • Sau khi tải kho lưu trữ Mẫu Android API phiên bản 2 của Google Maps, hãy chuyển đến vị trí bạn đã lưu kho lưu trữ Mẫu Android API phiên bản 2.
    • Tìm dự án MapWithMarker tại vị trí này:
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker (Java) hoặc
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker (Kotlin)
    • Chọn thư mục dự án, sau đó nhấp vào Open (Mở). Android Studio giờ đây sẽ tạo dự án của bạn bằng công cụ xây dựng Gradle.

Bật các API cần thiết và nhận khoá API

Để hoàn tất phần hướng dẫn này, bạn cần một dự án Google Cloud đã bật API cần thiết và có khoá API được phép sử dụng SDK Maps cho Android. Để biết thêm chi tiết, hãy xem:

Thêm khoá API vào ứng dụng

  1. Mở tệp local.properties của dự án.
  2. Thêm chuỗi sau đây rồi thay thế YOUR_API_KEY bằng giá trị của khoá API:

    MAPS_API_KEY=YOUR_API_KEY
    

    Khi bạn xây dựng ứng dụng, Trình bổ trợ Bí mật Gradle cho Android sẽ sao chép khoá API và cung cấp khoá đó dưới dạng biến bản dựng trong tệp kê khai Android, như giải thích bên dưới.

Tạo và chạy ứng dụng

Cách tạo và chạy ứng dụng:

  1. Kết nối thiết bị Android với máy tính. Làm theo instructions để bật tuỳ chọn cho nhà phát triển trên thiết bị Android và định cấu hình hệ thống để phát hiện thiết bị.

    Ngoài ra, bạn có thể sử dụng Trình quản lý thiết bị ảo Android (AVD) để định cấu hình một thiết bị ảo. Khi chọn một trình mô phỏng, hãy nhớ chọn một hình ảnh có chứa các API của Google. Để biết thêm thông tin chi tiết, hãy xem nội dung Thiết lập dự án Android Studio .

  2. Trong Android Studio, hãy nhấp vào tuỳ chọn trình đơn Run (Chạy) (hoặc biểu tượng nút phát). Chọn một thiết bị như được nhắc.

Android Studio sẽ gọi Gradle để tạo ứng dụng, sau đó chạy ứng dụng trên thiết bị hoặc trên trình mô phỏng. Bạn sẽ thấy một bản đồ có điểm đánh dấu trỏ tại Sydney trên bờ biển phía đông của Úc, tương tự như hình ảnh trên trang này.

Gỡ rối:

Tìm hiểu đoạn mã

Phần này của hướng dẫn giải thích các phần quan trọng nhất của ứng dụng MapWithMarker, để giúp bạn hiểu cách xây dựng một ứng dụng tương tự.

Kiểm tra tệp kê khai Android

Hãy lưu ý các phần tử sau trong tệp AndroidManifest.xml của ứng dụng:

  • Thêm phần tử meta-data để nhúng phiên bản Dịch vụ Google Play mà ứng dụng đã được biên dịch.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • Thêm phần tử meta-data chỉ định khoá API. Mẫu đi kèm với hướng dẫn này sẽ ánh xạ giá trị của khoá API với một biến bản dựng khớp với tên khoá mà bạn đã xác định trước đó là MAPS_API_KEY. Khi bạn tạo ứng dụng, Trình bổ trợ Bí mật cho Gradle dành cho Android sẽ cung cấp các khoá trong tệp local.properties của bạn dưới dạng biến bản dựng tệp kê khai.

    <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="${MAPS_API_KEY}" />
    

    Trong tệp build.gradle, dòng sau sẽ chuyển khoá API đến tệp kê khai Android của bạn.

      id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    

Dưới đây là ví dụ về một tệp kê khai đầy đủ:

<?xml version="1.0" encoding="utf-8"?>
<!--
 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.
-->

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!--
             The API key for Google Maps-based APIs.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="${MAPS_API_KEY}" />

        <activity
            android:name=".MapsMarkerActivity"
            android:label="@string/title_activity_maps"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Thêm bản đồ

Hiển thị bản đồ, sử dụng SDK Maps dành cho Android.

  1. Thêm phần tử <fragment> vào tệp bố cục của hoạt động, activity_maps.xml. Phần tử này xác định một SupportMapFragment để đóng vai trò là vùng chứa cho bản đồ và cung cấp quyền truy cập vào đối tượng GoogleMap. Hướng dẫn này sử dụng phiên bản thư viện hỗ trợ Android của mảnh bản đồ để đảm bảo khả năng tương thích ngược với các phiên bản trước đó của khung Android.

    <!--
     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.
    -->
    
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
    
    
  2. Trong phương thức onCreate() của hoạt động, hãy đặt tệp bố cục làm khung hiển thị nội dung. Tìm hiểu mảnh bản đồ bằng cách gọi FragmentManager.findFragmentById(). Sau đó, hãy sử dụng getMapAsync() để đăng ký lệnh gọi lại bản đồ:

    Java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    

    Kotlin

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps)
    
        // Get the SupportMapFragment and request notification when the map is ready to be used.
        val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
        mapFragment?.getMapAsync(this)
    }
    
  3. Triển khai giao diện OnMapReadyCallback và ghi đè phương thức onMapReady() để thiết lập bản đồ khi đối tượng GoogleMap có sẵn:

    Java

    public class MapsMarkerActivity extends AppCompatActivity
            implements OnMapReadyCallback {
    
        // ...
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            LatLng sydney = new LatLng(-33.852, 151.211);
            googleMap.addMarker(new MarkerOptions()
                .position(sydney)
                .title("Marker in Sydney"));
        }
    }
    

    Kotlin

    class MapsMarkerActivity : AppCompatActivity(), OnMapReadyCallback {
    
        // ...
    
        override fun onMapReady(googleMap: GoogleMap) {
          val sydney = LatLng(-33.852, 151.211)
          googleMap.addMarker(
            MarkerOptions()
              .position(sydney)
              .title("Marker in Sydney")
          )
        }
    }
    

Theo mặc định, SDK bản đồ dành cho Android sẽ hiển thị nội dung của cửa sổ thông tin khi người dùng nhấn vào một điểm đánh dấu. Bạn không cần thêm trình nghe lượt nhấp cho điểm đánh dấu nếu muốn sử dụng hành vi mặc định.

Các bước tiếp theo

Tìm hiểu thêm về đối tượng bản đồ và những việc bạn có thể làm với điểm đánh dấu.