İşaretçili Harita Ekleme

Bu eğiticide, Android uygulamanıza Google haritasını nasıl ekleyeceğiniz gösterilmektedir. Harita belirli bir konumu belirtmek için iğne olarak da adlandırılan bir işaretçi içerir.

Android için Haritalar SDK'sı. Önerilen geliştirme ortamı: Android Studio'ya gidin.

Kodu alın

Google Haritalar Android API v2 Samples deposunu klonlama veya indirme oluşturabilirsiniz.

Etkinliğin Java sürümünü görüntüleyin:

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

    

Etkinliğin Kotlin sürümünü görüntüleyin:

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

    

Geliştirme projenizi oluşturun

Android Studio'da eğitim projesini oluşturmak için aşağıdaki adımları uygulayın.

  1. Android Studio'yu indirin ve yükleyin.
  2. Android'e Google Play Hizmetleri paketini ekleyin Stüdyo'yu seçin.
  3. Google Haritalar Android API v2 Samples deposunu klonlama veya indirme bu işlemi yapmamış olmanız gerekir.
  4. Eğitim projesini içe aktarın:

    • Android Studio'da Dosya > Yeni > Projeyi İçe Aktarın.
    • Google Haritalar Android API v2 Sana Özel'i kaydettiğiniz konuma gidin depolanacağı tarihtir.
    • MapWithMarker projesini şu konumda bulun:
      PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker (Java) veya
      PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker (Kotlin)
    • Proje dizinini seçip 'ı tıklayın. Android Studio artık geliştirmenizi sağlar.

Gerekli API'leri etkinleştirin ve bir API anahtarı alın

Bu eğiticiyi tamamlamak için gerekli koşulları içeren bir Google Cloud projenize ihtiyacınız var: Etkinleştirilen API'ler ve Android için Haritalar SDK'sını kullanma yetkisi olan bir API anahtarı. Ayrıntılı bilgi için:

API anahtarını uygulamanıza ekleyin

  1. Projenizin local.properties dosyasını açın.
  2. Aşağıdaki dizeyi ekleyin ve YOUR_API_KEY değerini API anahtarınız:

    MAPS_API_KEY=YOUR_API_KEY
    

    Uygulamanızı oluştururken Android için Secrets Gradle Plugin API anahtarını kopyalar ve Android manifest'i aşağıda açıklandığı gibidir.

Uygulamanızı derleyip çalıştırma

Uygulamayı derlemek ve çalıştırmak için:

  1. Bilgisayarınıza bir Android cihaz bağlayın. Şunu izleyin: Android cihazınızda geliştirici seçeneklerini etkinleştirme talimatları açın ve sisteminizi cihazı algılayacak şekilde yapılandırın.

    Alternatif olarak Android Sanal Cihaz (AVD) Yöneticisi'ni de kullanabilirsiniz. sanal cihaz yapılandırması. Emülatör seçerken Google API'lerini içeren bir resim. Daha fazla bilgi için bkz. Android Studio Projesi Oluşturma .

  2. Android Studio'da Çalıştır menü seçeneğini (veya oynat düğmesi simgesini) tıklayın. İstendiği şekilde bir cihaz seçin.

Android Studio, uygulamayı derlemek için Gradle'ı çağırır ve ardından uygulamayı cihaz üzerinde veya emülatörde. Bir harita görüntülenir. Bu sayfadaki resme benzer şekilde, Avustralya'nın doğu kıyısında Sidney'de.

Sorun Giderme:

Kodu anlama

Eğiticinin bu bölümünde, çevrimiçi görüntülü reklam kampanyalarınızın MapWithMarker uygulaması, benzer bir uygulamasını indirin.

Android manifest dosyanızı kontrol edin

Uygulamanızın AndroidManifest.xml dosyasında aşağıdaki öğelere dikkat edin:

  • Google Play Hizmetleri'nin şu özelliklere sahip sürümünü yerleştirmek için bir meta-data öğesi ekleyin: uygulamanın derlenmesiyle ilgili daha fazla bilgi edinin.

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    
  • API anahtarınızı belirten bir meta-data öğesi ekleyin. Eşlik eden örnek bu eğitim, API anahtarının değerini bir derleme değişkeni ile eşler. daha önce tanımladığınız anahtarın adı, MAPS_API_KEY. Uygulamanızı oluştururken Android için Secrets Gradle Eklentisi local.properties dosyanızdaki anahtarları manifest derlemesi olarak kullanılabilir hale getirir değişkenlerine karşılık gelir.

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

    build.gradle dosyanızda aşağıdaki satır API anahtarınızı Android manifesti.

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

Aşağıda tam bir manifest örneği verilmiştir:

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

Harita ekleme

Android için Haritalar SDK'sını kullanarak bir harita görüntüleyin.

  1. Etkinliğinizin düzen dosyasına bir <fragment> öğesi ekleyin. activity_maps.xml. Bu öğe, bir Harita için kapsayıcı görevi görecek SupportMapFragment GoogleMap nesnesine erişim sağlamak için. Eğitim, Geriye doğru emin olmak için harita parçasının Android destek kitaplığı sürümü önceki Android çerçevesinin sürümleriyle uyumluluk.

    <!--
     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. Etkinliğinizin onCreate() yönteminde, düzen dosyasını içerik olarak ayarlayın görünüm. Çağrı yaparak harita parçasına herkese açık kullanıcı adı ekleyin FragmentManager.findFragmentById(). Daha sonra Harita geri çağırmasına kaydolmak için 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 arayüzünü uygulayın ve onMapReady() yöntemini geçersiz kıldığınızda, GoogleMap nesne kullanılabilir:

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

Android için Haritalar SDK'sı varsayılan olarak kullanıcı bir işaretçiye dokunduğunda bilgi penceresi Tıklama işleyici eklemeye gerek yoktur varsayılan davranışı kullanmaktan memnunsanız işaretçiye dokunun.

Sonraki adımlar

Harita nesnesi ve bu nesneyle yapabilecekleriniz hakkında daha fazla bilgi edinin işaretçiler.