помогите пожалуйста, как добавить в Яндекс MapKit сотни а то и больше меток с собственным изображением, пишу на Android Studio, Java. Несколько дней подряд в инете ищу, ответа так и не нашёл, а в документации по поводу MapKit'a толком ничего не понял. Если можно с конкретными примерами помогите плес:)
1 ответ
Я писал эту обертку для себя. В целом то что вас интересует это addMarker. Надо добавить 100 маркеров, просто вызовите его 100 раз.
class YandexMapView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
defStyleRes: Int = 0
) : FrameLayout(context, attrs, defStyle, defStyleRes) {
private val yandexMap: MapView
private var mapObjectCollection: MapObjectCollection
private var markerTapListener: MapObjectTapListener? = null
private val userLocation by lazy { getUserLocationLayer() }
init {
LayoutInflater.from(context).inflate(R.layout.map_view, this, true)
yandexMap = mapView
mapObjectCollection = yandexMap.map.mapObjects.addCollection()
}
fun onStart() {
yandexMap.onStart()
MapKitFactory.getInstance().onStart()
}
fun onStop() {
yandexMap.onStop()
MapKitFactory.getInstance().onStop()
}
fun release() {
mapObjectCollection.clear()
markerTapListener = null
}
fun setTapListener(listener: MapObjectTapListener) {
markerTapListener = listener
}
fun showUserLocation() {
userLocation.apply {
isVisible = true
isHeadingEnabled = false
setAnchor(
PointF((yandexMap.width * 0.5f), (yandexMap.height * 0.5f)),
PointF((yandexMap.width * 0.5f), (yandexMap.height * 0.83f))
)
resetAnchor()
}
}
fun moveAnimatedTo(
latitude: Double,
longitude: Double,
zoom: Float = DEFAULT_ZOOM,
azimuth: Float = 0F,
tilt: Float = 0F,
animation: Animation,
callback: Map.CameraCallback? = null
) {
yandexMap.map.move(
CameraPosition(Point(latitude, longitude), zoom, azimuth, tilt),
animation,
callback
)
}
fun addMarker(
latitude: Double,
longitude: Double,
@DrawableRes imageRes: Int,
userData: Any? = null
): PlacemarkMapObject {
val marker = mapObjectCollection.addPlacemark(
Point(latitude, longitude),
ImageProvider.fromResource(context, imageRes)
)
marker.userData = userData
markerTapListener?.let { marker.addTapListener(it) }
return marker
}
fun getZoom() = yandexMap.map.cameraPosition.zoom
private fun getUserLocationLayer() =
MapKitFactory.getInstance().createUserLocationLayer(yandexMap.mapWindow)
companion object {
const val DEFAULT_ZOOM = 10F
fun initialize(context: Context, apiKey: String) {
MapKitFactory.setApiKey(apiKey)
MapKitFactory.initialize(context)
}
}
}
В вашем Fragment/Activity это должно работать примерно так
//Маркеры в Yandex MapKit имеют WeakReference. И ссылки на них будут уничтожаться постоянно сборщиком мусора. Так что если вы хотите взаимодействовать с вашими маркерами, их надо хранить ручками. Например так
private val markerDataList = HashMap<Data, PlacemarkMapObject>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
YandexMapView.initialize(requireContext(), apiKey)
}
override fun onStart() {
super.onStart()
yandexMap.onStart()
}
override fun onStop() {
super.onStop()
yandexMap.onStop()
}
override fun onDestroy() {
super.onDestroy()
yandexMap?.release()
}
private fun addMarkers(dataList: List<Data>) {
for (data in dataList) {
val marker = yandexMap.addMarker(
latitude = data.latitude,
longitude = data.longitude,
imageRes = R.drawable.ic_marker,
userData = data.tag
)
//Вот здесь я как раз и сохраняю каждый маркер в свою мапу
markerDataList[data] = marker
}
}