במדריך הזה מוסבר איך להוסיף את מפת Google לאפליקציה ל-Android. המפה כוללת סמן (שנקרא גם סיכה) כדי לציין מיקום ספציפי.
פעלו לפי ההוראות במדריך לבניית אפליקציה ל-Android באמצעות ה-SDK של מפות Google ל-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, צריך לפעול לפי השלבים הבאים.
- מורידים ומתקינים את Android Studio.
- מוסיפים את החבילה של Google Play Services ל-Android Studio.
- אם לא עשיתם זאת כשהתחלתם לקרוא את המדריך, תוכלו לשכפל או להוריד את מאגר הדוגמאות לגרסה 2 של Android API של מפות Google.
ייבוא הפרויקט של המדריך:
- ב-Android Studio, בוחרים באפשרות קובץ > חדש > ייבוא פרויקט.
- אחרי שמורידים את מאגר הדוגמאות לגרסה 2 של ממשק ה-API של מפות Google ל-Android, עוברים למיקום שבו שמרתם אותו.
- מאתרים את הפרויקט MapWithMarker במיקום הזה:
PATH-TO-SAVED-REPO/android-samples/tutorials/java/MapWithMarker
(Java) או
PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/MapWithMarker
(Kotlin) - בוחרים את ספריית הפרויקט ולוחצים על Open (פתיחה). עכשיו אפשר לפתח את הפרויקט ב-Android Studio באמצעות הכלי Gradle build.
מפעילים את ממשקי ה-API הנחוצים ומקבלים מפתח API
כדי להשלים את המדריך, אתם צריכים פרויקט ב-Google Cloud שבו ממשקי ה-API הנדרשים מופעלים ומפתח API שמורשה להשתמש ב-SDK של מפות Google ל-Android. פרטים נוספים זמינים במאמרים הבאים:
הוספה של מפתח ה-API לאפליקציה
- פותחים את קובץ
local.properties
של הפרויקט. מוסיפים את המחרוזת הבאה ולאחר מכן מחליפים את
YOUR_API_KEY
בערך של מפתח ה-API:MAPS_API_KEY=YOUR_API_KEY
כשמפתחים את האפליקציה, הפלאגין Secrets Gradle ל-Android יעתיק את מפתח ה-API ויהפוך אותו לזמין כמשתנה build במניפסט של Android, כפי שמוסבר בהמשך.
פיתוח והרצה של אפליקציה
כדי ליצור ולהפעיל את האפליקציה:
מחברים מכשיר Android למחשב. פועלים לפי instructions כדי להפעיל אפשרויות למפתחים במכשיר Android ולהגדיר את המערכת לזיהוי המכשיר.
לחלופין, אתם יכולים להשתמש במנהל המכשירים הווירטואליים של Android (AVD) כדי להגדיר מכשיר וירטואלי. כשבוחרים אמולטור, חשוב לבחור תמונה שכוללת את Google APIs. לפרטים נוספים קראו את המאמר הגדרת פרויקט Android Studio .
ב-Android Studio, לוחצים על האפשרות בתפריט הפעלה (או על סמל לחצן ההפעלה). בוחרים מכשיר בהתאם להנחיות.
מערכת Android Studio מפעילה את Gradle כדי ליצור את האפליקציה, ולאחר מכן היא מריצה את האפליקציה במכשיר או באמולטור. אתם אמורים לראות מפה עם סמן המצביע על סידני בחוף המזרחי של אוסטרליה, בדומה לתמונה בדף הזה.
פתרון בעיות:
- אם המפה לא מופיעה, ודאו שקיבלתם מפתח API ושהוספתם אותו לאפליקציה, כפי שמתואר למעלה. חפשו הודעות שגיאה לגבי מפתח ה-API ב-Android Monitor ב-Android Studio.
- להשתמש בכלים לניפוי באגים ב-Android Studio כדי להציג יומנים ולנפות באגים באפליקציה.
הסבר על הקוד
בחלק הזה של המדריך מוסברים החלקים המשמעותיים ביותר של אפליקציית MapWithMarker, כדי לעזור לכם להבין איך ליצור אפליקציה דומה.
בדיקת המניפסט של 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 ממפה את הערך של מפתח ה-API למשתנה build שתואם לשם של המפתח שהגדרתם קודם,MAPS_API_KEY
. כשמפתחים את האפליקציה, הפלאגין Secrets Gradle ל-Android הופך את המפתחות בקובץlocal.properties
לזמינים כמשתני build של מניפסט.<meta-data android:name="com.google.android.geo.API_KEY" android:value="${MAPS_API_KEY}" />
בקובץ
build.gradle
, השורה הבאה מעבירה את מפתח ה-API אל מניפסט Android שלכם.id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
לפניכם דוגמה למניפסט מלא:
<?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>
הוספת מפה
הצג מפה באמצעות ה-SDK של מפות Google ל-Android.
הוספת רכיב
<fragment>
לקובץ הפריסה של הפעילות,activity_maps.xml
. הרכיב הזה מגדיר אתSupportMapFragment
שישמש כמאגר של המפה ויספק גישה לאובייקטGoogleMap
. במדריך נעשה שימוש בגרסה של קטע המפה בספריית התמיכה של 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" />
ב-method
onCreate()
של הפעילות, צריך להגדיר את קובץ הפריסה בתור תצוגת התוכן. קריאה ל-FragmentManager.findFragmentById()
מאפשרת לטפל בקטע שבמפה. לאחר מכן משתמשים ב-getMapAsync()
כדי להירשם לקריאה החוזרת (callback):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) }
כדי להגדיר את המפה כשהאובייקט
GoogleMap
זמין, צריך להטמיע את הממשקOnMapReadyCallback
ולבטל את השיטהonMapReady()
: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") ) } }
כברירת מחדל, ה-SDK של מפות Google ל-Android מציג את התוכן של חלון המידע כשהמשתמש מקיש על סמן. אין צורך להוסיף רכיב האזנה לקליקים עבור הסמן אם אתם שמחים להשתמש בהתנהגות ברירת המחדל.
השלבים הבאים
כאן תוכלו לקרוא מידע נוסף על אובייקט המפה ועל הפעולות שאפשר לבצע באמצעות סמנים.