İşaretçili Harita Ekleme

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

Android için Haritalar SDK'sını kullanarak Android uygulaması oluşturmak için eğiticideki adımları uygulayın. Önerilen geliştirme ortamı Android Studio'dur.

Kodu alın

GitHub'dan Google Haritalar Android API v2 Örnekleri deposunu klonlayın veya indirin.

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 Studio'ya Google Play Hizmetleri paketini ekleyin.
  3. Bu eğiticiyi okumaya başladığınızda bunu yapmadıysanız Google Haritalar Android API v2 Örnek deposunu klonlayın veya indirin.
  4. Eğitim projesini içe aktarın:

    • Android Studio'da Dosya > Yeni > Projeyi İçe Aktar'ı seçin.
    • İndirdikten sonra Google Haritalar Android API v2 Örnekleri deposunu kaydettiğiniz konuma gidin.
    • 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çin ve ardından 'ı tıklayın. Android Studio artık Gradle oluşturma aracını kullanarak projenizi oluşturuyor.

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

Bu eğiticiyi tamamlamak için gerekli API'lerin etkinleştirildiği bir Google Cloud projesine ve Android için Haritalar SDK'sını kullanmak üzere yetkilendirilmiş bir API anahtarına ihtiyacınız vardır. Daha fazla bilgi için:

API anahtarını uygulamanıza ekleme

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

    MAPS_API_KEY=YOUR_API_KEY
    

    Uygulamanızı oluştururken Android için Secrets Gradle Eklentisi, API anahtarını kopyalar ve aşağıda açıklandığı gibi Android manifest dosyasında derleme değişkeni olarak kullanıma sunar.

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

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

  1. Bilgisayarınıza bir Android cihaz bağlayın. Android cihazınızda geliştirici seçeneklerini etkinleştirmek ve sisteminizi cihazı algılayacak şekilde yapılandırmak için instructions uygulayın.

    Alternatif olarak, sanal bir cihaz yapılandırmak için Android Virtual Device (AVD) Manager'ı kullanabilirsiniz. Bir emülatör seçerken Google API'lerini içeren bir görüntü seçtiğinizden emin olun. Daha fazla bilgi için Android Studio Projesi Oluşturma bölümüne bakın.

  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ı oluşturmak için Gradle'ı çağırır ve daha sonra, uygulamayı cihazda veya emülatörde çalıştırır. Bu sayfadaki görüntüye benzer şekilde, Avustralya'nın doğu yakasında Sidney'i işaret eden bir işaretçi görürsünüz.

Sorun giderme:

Kodu anlama

Eğiticinin bu bölümünde, benzer bir uygulamayı nasıl oluşturacağınızı anlamanıza yardımcı olmak için MapWithMarker uygulamasının en önemli kısımları açıklanmaktadır.

Android manifest'inizi kontrol edin

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

  • Uygulamanın derlendiği Google Play Hizmetleri sürümünü yerleştirmek için bir meta-data öğesi ekleyin.

    <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. Bu eğitimdeki örnek, API anahtarı değerini daha önce tanımladığınız MAPS_API_KEY ile eşleşen bir derleme değişkeniyle eşleştirir. Android için Secrets Gradle Plugin derlediğinizde local.properties dosyanızdaki anahtarları, manifest derleme değişkenleri olarak kullanılabilir hale getirir.

    <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 manifest'inize iletir.

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

Tam manifest örneği aşağıda 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 ekleyin

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, haritanın kapsayıcısı işlevi görmek ve GoogleMap nesnesine erişim sağlamak için bir SupportMapFragment tanımlar. Eğiticide, Android çerçevesinin önceki sürümleriyle geriye dönük uyumluluk sağlamak için harita parçasının Android destek kitaplığı sürümü kullanılmaktadır.

    <!--
     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 görünümü olarak ayarlayın. FragmentManager.findFragmentById() yöntemini çağırarak harita parçası için bir herkese açık kullanıcı adı alın. Ardından harita geri çağırmaya kaydolmak için getMapAsync() aracını kullanı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. GoogleMap nesnesi kullanılabilir olduğunda haritayı ayarlamak için OnMapReadyCallback arayüzünü uygulayın ve onMapReady() yöntemini geçersiz kılı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")
          )
        }
    }
    

Varsayılan olarak Android için Haritalar SDK'sı, kullanıcı bir işaretçiye dokunduğunda bilgi penceresinin içeriğini görüntüler. Varsayılan davranışı kullanmaktan memnunsanız işaretçi için tıklama işleyici eklemenize gerek yoktur.

Sonraki adımlar

Harita nesnesi ve işaretçilerle neler yapabileceğiniz hakkında daha fazla bilgi edinin.