MapmyIndia Android SDK — добавление пользовательского маркера
Многие приложения для Android используют карты в своем приложении. Мы увидим, что они отображают пользовательские значки маркеров на своих картах. В этой статье мы рассмотрим, как добавить пользовательский маркер на карту моих карт Индии в нашем приложении для Android. Пример видео приведен ниже, чтобы получить представление о том, что мы собираемся делать в этой статье.
Note: This Android article covered in both Java and Kotlin languages.
Пошаговая реализация
Шаг 1. Создайте новый проект в Android Studio.
Чтобы создать новый проект в Android Studio, обратитесь к разделу «Как создать/запустить новый проект в Android Studio ».
Шаг 2. Загрузка SDK для Map My India
Перейдите по ссылке и загрузите jar-файл для Map My India SDK. После загрузки скопируйте файл, чтобы добавить его в наш проект. Перейдите в раздел «Проект» в своем проекте Android Studio. Затем перейдите в «Имя проекта»> «Приложение»> «Библиотеки». Щелкните его правой кнопкой мыши и просто вставьте загруженный файл jar в эту папку.
Шаг 3: Добавление зависимости в файл build.gradle
Перейдите к файлу app> build.gradle и добавьте к нему приведенную ниже зависимость в разделе зависимостей.
implementation "com.google.code.gson:gson:2.3"
implementation files("libs/map_sdk_2.1.jar")После добавления зависимости просто синхронизируйте свой проект.
Шаг 4: Работа с файлом activity_main.xml
Перейдите к app > res > layout > activity_main.xml и добавьте в него приведенный ниже код. В код добавлены комментарии для более подробного ознакомления.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--on below line we are creating a map view--> <com.mmi.MapmyIndiaMapView android:id="@+id/idMapView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> |
Шаг 5. Добавление разрешений в файл AndroidManifest.xml
Перейдите к файлу app>AndroidManifest.xml и добавьте к нему указанные ниже разрешения.
XML
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> |
Теперь добавьте приведенный ниже код в тег приложения в файле AndroidManifest.xml, чтобы использовать устаревшую библиотеку в нашем приложении.
XML
<uses-library android:name="org.apache.http.legacy" android:required="false" /> |
Шаг 6. Создание ключа API для использования Map My India SDK.
Перейдите по ссылке. Зарегистрируйтесь, указав свой адрес электронной почты и пароль, и вы увидите экран ниже. Внутри этого перейдите на вкладку учетных данных, чтобы увидеть свой ключ API. Скопируйте этот ключ API, который мы должны использовать в нашем проекте.
Шаг 7: Создайте файл макета для отображения всплывающей подсказки на маркере
Перейдите к приложению> res> layout> щелкните его правой кнопкой мыши> New> Layout Resource file и назовите его как всплывающую подсказку и добавьте к нему приведенный ниже код. Комментарии добавлены в код, чтобы узнать его в деталях.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" android:orientation="vertical" android:padding="5dp"> <!-- displaying title on below line--> <TextView android:id="@+id/tooltip_title" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_gravity="left" android:layout_weight="1" android:gravity="center" android:maxEms="17" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="18sp" android:textStyle="bold" /> <!--displaying description on below line--> <TextView android:id="@+id/tooltip_description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:maxEms="17" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="12sp" android:visibility="gone" /> <!--displaying sub description on below line--> <TextView android:id="@+id/tooltip_sub_description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:maxEms="17" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="10sp" /> </LinearLayout> <!--displaying tip view on below line--> <com.mmi.view.TipView android:id="@+id/tip_view" android:layout_width="fill_parent" android:layout_height="10dp" /> </LinearLayout> |
Шаг 8: Работа с файлом MainActivity
Перейдите к приложению > java > имени пакета вашего приложения > файлу MainActivity и добавьте в него приведенный ниже код. В код добавлены комментарии для более подробного ознакомления.
Kotlin
package com.gtappdevelopers.mapmyindiakotlin import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport com.mmi.LicenceManagerimport com.mmi.MapmyIndiaMapViewimport com.mmi.layers.BasicInfoWindowimport com.mmi.layers.Markerimport com.mmi.util.GeoPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // on below line we are setting rest api key and map sdk key. LicenceManager.getInstance().restAPIKey = "Enter your API key" LicenceManager.getInstance().mapSDKKey = "Enter your API key" // on below line we are creating variables for map view and initializing it. val mapmyIndiaMapView = findViewById<MapmyIndiaMapView>(R.id.idMapView) // on below line we are getting our map view. val mapView = mapmyIndiaMapView.mapView // on below line we are adding latitude and longitude val geoPoint = GeoPoint(28.7041, 77.1025) // on below line we are creating an info window for our tool tip. val infoWindow = BasicInfoWindow(R.layout.tooltip, mapView) // on below line setting tooltip color. infoWindow.setTipColor(resources.getColor(R.color.white)) // on below line we are creating our marker. val marker = Marker(mapView) // on below line setting title,description // and custom icon for marker. marker.title = "New Delhi" marker.description = "Capital of India" marker.icon = resources.getDrawable(R.drawable.delhi) // on below line we are setting marker position. marker.position = geoPoint // on below line we are adding anchor for our marker. marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER) // on below line we are adding our marker to map view. mapView.overlays.add(marker) // on below line we are setting map // view center position to marker. mapView.invalidate() mapView.setCenter(geoPoint) }} |
Java
package com.gtappdevelopers.mapmyindia; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.mmi.LicenceManager;import com.mmi.MapView;import com.mmi.MapmyIndiaMapView;import com.mmi.layers.BasicInfoWindow;import com.mmi.layers.Marker;import com.mmi.util.GeoPoint; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are setting rest api key and map sdk key. LicenceManager.getInstance().setRestAPIKey("Enter your API key"); LicenceManager.getInstance().setMapSDKKey("Enter your API key"); // on below line we are creating variables for map view and initializing it. MapmyIndiaMapView mapmyIndiaMapView = findViewById(R.id.idMapView); // on below line we are getting our map view. MapView mapView = mapmyIndiaMapView.getMapView(); // on below line we are adding latitude and longitude GeoPoint geoPoint = new GeoPoint(28.7041, 77.1025); // on below line we are creating an info window for our tool tip. BasicInfoWindow infoWindow = new BasicInfoWindow(R.layout.tooltip, mapView); // on below line setting tooltip color. infoWindow.setTipColor(getResources().getColor(R.color.white)); // on below line we are creating our marker. Marker marker = new Marker(mapView); // on below line setting title,description // and custom icon for marker. marker.setTitle("New Delhi"); marker.setDescription("Capital of India"); marker.setIcon(getResources().getDrawable(R.drawable.delhi)); // on below line we are setting marker position. marker.setPosition(geoPoint); // on below line we are adding anchor for our marker. marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER); // on below line we are adding our marker to map view. mapView.getOverlays().add(marker); // on below line we are setting map view // center position to marker. mapView.invalidate(); mapView.setCenter(geoPoint); }} |
Note: Make sure to add the image which you want to display in the drawable folder.
Теперь запустите ваше приложение, чтобы увидеть результат.
Выход: