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

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

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

Lấy mã

Sao chép hoặc tải kho lưu trữ Mẫu API Google Maps Android phiên bản 2 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

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

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

    • Trong Android Studio, hãy chọn File > Open (Tệp > Mở).
    • Chuyển đến vị trí bạn đã lưu kho lưu trữ Mẫu API Google Maps Android phiên bản 2 sau khi tải xuống, chọn thư mục gốc android-samples rồi nhấp vào Mở. Android Studio đồng bộ hoá dự án đa mô-đun bằng Gradle.
    • Trong trình đơn cấu hình chạy của Android Studio trên thanh công cụ, hãy chọn tutorials.java.MapWithMarker (nguồn trong tutorials/java/MapWithMarker) hoặc tutorials.kotlin.MapWithMarker (nguồn trong tutorials/kotlin/MapWithMarker).

Bật các API cần thiết và lấy khoá API

Để hoàn thành hướng dẫn này, bạn cần có một dự án trên đám mây của Google Cloud đã bật các API cần thiết và một khoá API được uỷ quyền sử dụng Maps SDK cho Android. Để biết thêm thông tin, hãy xem:

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

  1. Trong thư mục gốc android-samples (cùng thư mục với local.defaults.properties), hãy mở hoặc tạo tệp secrets.properties. Đừng kiểm tra tệp này trong phần quản lý phiên bản.
  2. Thêm chuỗi sau vào secrets.properties và thay thế YOUR_API_KEY bằng giá trị của khoá API:

    MAPS_API_KEY=YOUR_API_KEY
    

    Khi bạn tạo ứng dụng, Trình bổ trợ Secrets 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 trong phần Kiểm tra tệp kê khai Android.

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 hướng dẫn để bật Tùy 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ị trong Android Studio để định cấu hình thiết bị ảo. Khi chọn trình mô phỏng, hãy chọn một hồ sơ thiết bị có biểu tượng Google Play trong cột Play để hình ảnh hệ thống bao gồm các API của Google. Để biết thêm thông tin, hãy xem bài viết Thiết lập dự án Android Studio.

  2. Trong Android Studio, hãy xác minh rằng tutorials.java.MapWithMarker hoặc tutorials.kotlin.MapWithMarker được chọn trong trình đơn cấu hình chạy, sau đó nhấp vào Run (Chạy) và chọn một thiết bị theo lời nhắc.

    Bạn cũng có thể tạo hướng dẫn từ thư mục gốc android-samples trên dòng lệnh:

    ./gradlew :tutorials:java:MapWithMarker:assembleDebug
    ./gradlew :tutorials:kotlin:MapWithMarker:assembleDebug
    

Android Studio 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 chỉ vào Sydney trên bờ biển phía đông của Úc, tương tự như hình ảnh trên trang này.

Khắc phục sự cố:

Tìm hiểu mã

Phần này của hướng dẫn giải thích những 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

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 một phần tử meta-data chỉ định khoá API của bạn. Mẫu đi kèm với hướng dẫn này liên kết giá trị cho khoá API với một biến bản dựng khớp với tên của khoá mà bạn đã xác định trước đó, MAPS_API_KEY. Khi bạn tạo ứng dụng, Trình bổ trợ Secrets Gradle cho Android sẽ cung cấp các khoá trong tệp secrets.properties dưới dạng biến thể 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.kts ở cấp mô-đun, trình bổ trợ com.google.android.libraries.mapsplatform.secrets-gradle-plugin và khối secrets sau đây sẽ định cấu hình Trình bổ trợ Secrets cho Gradle để đọc khoá API của bạn từ secrets.properties (với local.defaults.properties làm phương án dự phòng) và truyền khoá đó đến tệp kê khai Android:

    secrets {
        // To add your Maps API key to this project:
        // 1. If the secrets.properties file does not exist, create it in the root directory (the same folder as the root local.properties file).
        // 2. Add this line, where YOUR_API_KEY is your API key:
        //        MAPS_API_KEY=YOUR_API_KEY
        propertiesFileName = "secrets.properties"
    
        // A properties file containing default secret values. This file can be
        // checked in version control.
        defaultPropertiesFileName = "local.defaults.properties"
    }

Ví dụ sau đây cho thấy một tệp kê khai hoàn chỉnh:

<?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 đồ bằng SDK Maps 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 AndroidX 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 chế độ xem nội dung. Xử lý 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 có đối tượng GoogleMap:

    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, Maps SDK 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 theo dõi 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.