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

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

Làm theo hướng dẫn để tạo một ứng dụng Android bằng SDK Bản đồ dành 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 phiên bản 2 của Google Maps cho Android trên 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. Sao chép hoặc tải kho lưu trữ Mẫu API phiên bản 2 của Google Maps cho Android nếu bạn không làm như vậy khi bắt đầu đọc hướng dẫn này.
  4. Nhập dự án hướng dẫn:

    • Trong Android Studio, chọn File > (Tệp >) Mới > Nhập dự án.
    • Chuyển đến vị trí bạn đã lưu Mẫu API Android phiên bản 2 của Google Maps sau khi tải xuống.
    • 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, rồi nhấp vào Open (Mở). Android Studio hiện đã có bản dựng 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 hướng dẫn này, bạn cần có một dự án trên Google Cloud có đầy đủ thông tin Đã bật API và khoá API được phép sử dụng SDK bản đồ dành cho Android. Để biết thêm thông tin, hãy xem:

Thêm khoá API vào ứng dụng của bạn

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

    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 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 hướng dẫn bật tuỳ chọn cho nhà phát triển trên thiết bị Android thiết bị và định cấu hình hệ thống của bạn để 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ị Android ảo (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 bao gồm các API của Google. Để biết thêm thông tin, hãy xem Thiết lập một 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ị khi được nhắc.

Android Studio gọi Gradle để tạo ứng dụng, sau đó chạy ứng dụng trên 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, tương tự như hình ảnh trên trang này.

Gỡ rối:

Tìm hiểu mã nguồn

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 MapWithMarker để giúp bạn hiểu cách tạo .

Kiểm tra tệp kê khai Android của bạn

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

  • Thêm một phần tử meta-data để nhúng phiên bản của Dịch vụ Google Play ứ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 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 phù hợp 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ợ Gradle cho Android sẽ cung cấp các khoá trong tệp local.properties của bạn dưới dạng bản dựng tệp kê khai biến.

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

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

      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 một 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 chuyển về khả năng tương thích 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 nội dung chế độ xem. Xử lý mảnh bản đồ bằng cách gọi FragmentManager.findFragmentById(). Sau đó 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 GoogleMap có sẵn đối tượng:

    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 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. Không cần thêm trình nghe lượt nhấp cho điểm đánh dấu nếu bạn muốn sử dụng chế độ 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.