如何使用Android地图API创建自定义形状的位图标记?


简介

如今,许多Android应用程序在其内部使用Google Maps来向用户显示地图。例如,我们使用许多食品配送应用程序,在这些应用程序中,我们可以看到我们的订单状态以及配送员在Google Maps上的位置。根据其用例,我们可以在每个应用程序上看到不同类型的标记。在本文中,我们将了解如何使用Android地图API创建自定义形状的位图标记?

实现

我们将创建一个简单的应用程序,在该应用程序中,我们将显示一个简单的Google地图,并在该地图上向德里位置添加一个自定义形状的标记。我们将遵循分步指南来构建此应用程序。现在让我们转向Android Studio来创建一个新项目。

步骤1:在Android Studio中创建一个新项目

导航到Android Studio,如下面的屏幕所示。在下面的屏幕中,点击“新建项目”以创建一个新的Android Studio项目。

点击“新建项目”后,您将看到下面的屏幕。

在此屏幕中,我们只需选择“Google Maps Activity”并点击“下一步”。点击“下一步”后,您将看到下面的屏幕。

在此屏幕中,我们只需指定项目名称。然后包名将自动生成。

注意:确保选择Java作为语言。

指定所有详细信息后,点击“完成”以创建一个新的Android Studio项目。

项目创建完成后,我们将看到两个打开的文件,即activity_maps.xml和MapsActivity.java文件。

步骤2:创建API密钥以显示Google Maps

访问下面的URL,其中您将找到有关如何创建Google Maps API密钥的详细文档,我们必须将其添加到我们的应用程序中以显示Google Maps。

步骤3:使用AndroidManifest.xml文件

现在,我们已经生成了Google Maps API密钥,我们必须在项目的AndroidManifest.xml文件中使用此密钥。导航到app>AndroidManifest.xml文件,并将以下代码添加到其中。代码中添加了注释以详细了解。

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.GoogleMapsProject" tools:targetApi="31"> <!-- TODO: Before you run your application, you need a Google Maps API key. To get one, follow the directions here: https://developers.google.com/maps/documentation/android-sdk/get-api-key Once you have your API key (it starts with "AIza"), define a new property in your project's local.properties file (e.g. MAPS_API_KEY=Aiza...), and replace the "YOUR_API_KEY" string in this file with "${MAPS_API_KEY}". --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="Enter your API key here" /> <activity android:name=".MapsActivity" android:exported="true" android:label="@string/title_activity_maps"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

注意 - 确保将您生成的API密钥添加到“输入您的API密钥”标签的位置。

步骤4:使用activity_main.xml

导航到activity_maps.xml。如果此文件不可见,要打开此文件,在左侧窗格中导航到app>res>layout>activity_maps.xml以打开此文件。打开此文件后,将以下代码添加到其中。代码中添加了注释以详细了解。

<?xml version="1.0" encoding="utf-8"?> <!-- on below line creating a fragment for displaying maps--> <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:map="http://schemas.android.com/apk/res-auto" 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=".MapsActivity" />

说明 - 在上面的代码中,我们正在创建一个片段,我们将在其中显示应用程序内的Google地图。我们为该片段指定了一个名称,即“支持地图片段”。

步骤4:使用MapsActivity.java文件

导航到MainActivity.java。如果此文件不可见,要打开此文件,在左侧窗格中导航到app>res>layout>MainActivity.java以打开此文件。打开此文件后,将以下代码添加到其中。代码中添加了注释以详细了解。

package com.example.googlemapsproject; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Bundle; 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.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.example.googlemapsproject.databinding.ActivityMapsBinding; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { // on below line creating a variable for google maps and binding. private GoogleMap mMap; private ActivityMapsBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMapsBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered 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 will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // on below line creating a lat lng for delhi location LatLng delhi = new LatLng(28.7041, 77.1025); // on below line adding marker. mMap.addMarker(new MarkerOptions() // on below line specifying the position where we have to add the marker. .position(delhi) // on below line specifying the title for our marker. .title("Marker in Delhi") // on below line specifying the icon for our marker. .icon(BitmapFromDrawable(this, R.drawable.ic_plane))); // on below line moving camera to our lat lng. mMap.moveCamera(CameraUpdateFactory.newLatLng(delhi)); } private BitmapDescriptor BitmapFromDrawable(Context context, int imageID) { // on below line we are creating a drawable from its id. Drawable imageDrawable = ContextCompat.getDrawable(context, imageID); // below line is use to set bounds to our vector drawable. imageDrawable.setBounds(0, 0, imageDrawable.getIntrinsicWidth(), imageDrawable.getIntrinsicHeight()); // on below line is use to create a bitmap for our drawable which we have added. Bitmap bitmap = Bitmap.createBitmap(imageDrawable.getIntrinsicWidth(), imageDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); // on below line is use to add bitmap in our canvas. Canvas canvas = new Canvas(bitmap); // below line is use to draw our // vector drawable in canvas. imageDrawable.draw(canvas); // after generating our bitmap we are returning our bitmap. return BitmapDescriptorFactory.fromBitmap(bitmap); } }

说明:在上面的代码中,首先我们为Google Maps和活动绑定创建变量。现在我们将看到onCreate方法。这是每个Android应用程序的默认方法。当创建应用程序视图时,将调用此方法。在此方法内部,我们设置内容视图,即名为activity_maps.xml的布局文件,以从该文件中设置UI。在onCreate方法内部,我们正在初始化绑定变量,然后我们为支持片段创建一个变量,并使用我们在activity_maps.xml文件中提供的片段ID初始化该变量。然后调用getMapSync以同步我们的地图。之后,我们覆盖onMapReady方法。在此方法中,我们为将要显示在德里位置的标记创建纬度和经度。然后,我们在我们的地图上添加一个自定义形状的标记。我们正在创建一个名为BitmapFromDrawable的新方法,该方法将从我们指定的drawable文件中为图标提供一个位图。然后,我们使用此位图描述符将其设置到我们的Google Maps上。最后,将我们的相机移动到我们显示标记的位置。

添加上述代码后,我们只需点击顶部的绿色图标即可在移动设备上运行应用程序。

注意:确保您已连接到您的真实设备或模拟器。

输出

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

结论

在本文中,我们了解了如何使用Android地图API创建自定义形状的位图标记。

更新于: 2023年5月8日

723次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告