การเพิ่มแผนที่ด้วยเครื่องหมาย

จัดทุกอย่างให้เป็นระเบียบอยู่เสมอด้วยคอลเล็กชัน บันทึกและจัดหมวดหมู่เนื้อหาตามค่ากำหนดของคุณ

บทแนะนํานี้จะแสดงวิธีเพิ่ม Google Maps ลงในแอป Android โดยแผนที่จะมีเครื่องหมายหรือเรียกอีกอย่างว่าหมุดเพื่อแสดงตําแหน่งที่เฉพาะเจาะจง

ทําตามบทแนะนําเพื่อสร้างแอป Android โดยใช้ Maps SDK สําหรับ Android สภาพแวดล้อมในการพัฒนาซอฟต์แวร์ที่แนะนําคือ Android Studio

รับโค้ด

โคลนหรือดาวน์โหลดที่เก็บ Google Maps Android API v2 ตัวอย่างจาก GitHub

ดูกิจกรรมในเวอร์ชัน Java:

    // 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));
    }
}

    

ดูกิจกรรมเวอร์ชัน Kotlin

    // 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))
    }
}

    

ตั้งค่าโปรเจ็กต์การพัฒนา

ทําตามขั้นตอนเหล่านี้เพื่อสร้างโปรเจ็กต์บทแนะนําใน Android Studio

  1. ดาวน์โหลดและติดตั้ง Android Studio
  2. เพิ่มแพ็กเกจบริการ Google Play ลงใน Android Studio
  3. โคลนหรือดาวน์โหลดที่เก็บ Google Maps Android API v2 หากคุณไม่ได้ทําตอนเริ่มอ่านบทแนะนํานี้
  4. นําเข้าโปรเจ็กต์บทแนะนํา:

    • ใน Android Studio ให้เลือกไฟล์ > ใหม่ > นําเข้าโปรเจ็กต์
    • ไปยังตําแหน่งที่คุณบันทึกที่เก็บ Google Maps Android API v2 Sample หลังจากดาวน์โหลด
    • ค้นหาโปรเจ็กต์ MapWithMarker ในตําแหน่งนี้
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker (Java) หรือ
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker (Kotlin)
    • เลือกไดเรกทอรีโปรเจ็กต์ แล้วคลิกเปิด ตอนนี้ Android Studio สร้างโปรเจ็กต์ของคุณโดยใช้เครื่องมือสร้าง Gradle แล้ว

เปิดใช้ API ที่จําเป็นและรับคีย์ API

หากต้องการสร้างบทแนะนํานี้ให้เสร็จสมบูรณ์ คุณต้องมีโปรเจ็กต์ Google Cloud ที่เปิดใช้ API ที่จําเป็นและคีย์ API ที่ได้รับอนุญาตให้ใช้ Maps SDK สําหรับ Android โปรดดูรายละเอียดเพิ่มเติมได้จากหัวข้อต่อไปนี้

เพิ่มคีย์ API ลงในแอป

  1. เปิดไฟล์ local.properties ของโปรเจ็กต์
  2. เพิ่มสตริงต่อไปนี้และแทนที่ YOUR_API_KEY ด้วยค่าของคีย์ API

    MAPS_API_KEY=YOUR_API_KEY
    

    เมื่อคุณสร้างแอป ปลั๊กอิน Gradle สําหรับ Android จะคัดลอกคีย์ API และทําให้เป็นตัวแปรบิวด์ในไฟล์ Manifest ของ Android ตามที่อธิบายไว้ด้านล่าง

สร้างและเรียกใช้แอป

วิธีสร้างและเรียกใช้แอป

  1. เชื่อมต่ออุปกรณ์ Android กับคอมพิวเตอร์ ทําตามวิธีการเพื่อเปิดใช้ตัวเลือกสําหรับนักพัฒนาแอปในอุปกรณ์ Android และกําหนดค่าระบบให้ตรวจจับอุปกรณ์ได้

    หรือจะใช้โปรแกรมจัดการอุปกรณ์เสมือน Android (AVD) เพื่อกําหนดค่าอุปกรณ์เสมือนจริงก็ได้ เมื่อเลือกโปรแกรมจําลอง โปรดเลือกรูปภาพที่มี Google API โปรดดูรายละเอียดเพิ่มเติมที่หัวข้อตั้งค่าโปรเจ็กต์ Android Studio

  2. ใน Android Studio ให้คลิกตัวเลือกเมนูเรียกใช้ (หรือไอคอนปุ่มเล่น) เลือกอุปกรณ์เมื่อได้รับข้อความแจ้ง

Android Studio จะเรียกใช้ Gradle เพื่อสร้างแอป จากนั้นเรียกใช้แอปในอุปกรณ์หรือในโปรแกรมจําลอง คุณควรเห็นแผนที่ที่มีเครื่องหมายระบุตําแหน่งอยู่ที่ซิดนีย์บนชายฝั่งตะวันออกของออสเตรเลีย ซึ่งคล้ายกับรูปภาพในหน้านี้

การแก้ปัญหา:

ทําความเข้าใจโค้ด

ส่วนบทแนะนํานี้ในบทแนะนําจะอธิบายส่วนที่สําคัญที่สุดของแอป MapWithMarker เพื่อช่วยให้คุณเข้าใจวิธีสร้างแอปที่คล้ายกัน

ตรวจสอบไฟล์ Manifest ของ Android

โปรดทราบองค์ประกอบต่อไปนี้ในไฟล์ AndroidManifest.xml ของแอป

  • เพิ่มเอลิเมนต์ meta-data เพื่อฝังเวอร์ชันของบริการ Google Play ที่ใช้คอมไพล์แอป

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • เพิ่มเอลิเมนต์ meta-data ที่ระบุคีย์ API ตัวอย่างประกอบกับบทแนะนํานี้จะแมปค่าของคีย์ API กับตัวแปรบิลด์ที่ตรงกับชื่อของคีย์ที่กําหนดไว้ก่อนหน้านี้ซึ่งก็คือ MAPS_API_KEY เมื่อคุณสร้างแอป ปลั๊กอิน Gradle สําหรับ Android จะทําให้คีย์ในไฟล์ local.properties พร้อมใช้งานเป็นตัวแปรบิลด์ของไฟล์ Manifest

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

    ในไฟล์ build.gradle บรรทัดต่อไปนี้จะส่งคีย์ API ของคุณไปยังไฟล์ Manifest ของ Android

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

ด้านล่างเป็นตัวอย่างของไฟล์ Manifest แบบเต็ม

<?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"
    package="com.example.mapwithmarker">

    <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>

เพิ่มแผนที่

แสดงแผนที่โดยใช้ Maps SDK สําหรับ Android

  1. เพิ่มเอลิเมนต์ <fragment> ลงในไฟล์เลย์เอาต์ของกิจกรรม activity_maps.xml องค์ประกอบนี้กําหนด SupportMapFragment เพื่อทําหน้าที่เป็นคอนเทนเนอร์สําหรับแผนที่ และให้สิทธิ์เข้าถึงออบเจ็กต์ GoogleMap บทแนะนําใช้ Fragment ในแผนที่เวอร์ชันสนับสนุนของ Android เพื่อให้แน่ใจว่าจะเข้ากันได้กับแผนเฟรมเวิร์ก 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. ในเมธอด onCreate() ของกิจกรรม ให้ตั้งค่าไฟล์เลย์เอาต์เป็นมุมมองเนื้อหา เรียกใช้ส่วนย่อยของส่วนย่อยในแผนที่ด้วยการเรียก FragmentManager.findFragmentById() จากนั้นใช้ getMapAsync() เพื่อลงทะเบียนสําหรับการเรียกกลับในแผนที่:

    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. ใช้อินเทอร์เฟซ OnMapReadyCallback และลบล้างเมธอด onMapReady() เพื่อตั้งค่าแผนที่เมื่อออบเจ็กต์ 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")
          )
        }
    }
    

โดยค่าเริ่มต้น Maps SDK สําหรับ Android จะแสดงเนื้อหาของหน้าต่างข้อมูลเมื่อผู้ใช้แตะที่เครื่องหมาย และไม่จําเป็นต้องเพิ่ม Listener การคลิก สําหรับเครื่องหมายหากคุณยินดีใช้พฤติกรรมเริ่มต้น

ขั้นตอนถัดไป

ดูข้อมูลเพิ่มเติมเกี่ยวกับออบเจ็กต์แผนที่ และสิ่งที่คุณทําได้ด้วยเครื่องหมาย