Rename Gradle targets Android (#2226)

This commit is contained in:
Bart Louwers
2024-04-02 23:15:50 +02:00
committed by GitHub
parent 37170ed61c
commit 9f8ae7a98b
1081 changed files with 132 additions and 370 deletions

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 308 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 831 B

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 729 B

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,115 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.5580596923828,
37.78563944612241
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.58346557617185,
37.743571187449064
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.51068115234375,
37.72347854862523
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.51583099365234,
37.77125750792944
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.5913619995117,
37.795406713958236
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.56080627441403,
37.69441603823106
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.62981414794922,
37.722392304715825
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.52235412597656,
37.807071480609274
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.53608703613278,
37.75334401310656
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
237.57591247558594,
37.77071473849609
]
}
}
]
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,766 @@
{
"id": "hybrid",
"name": "Satellite Hybrid",
"zoom": 1,
"pitch": 0,
"center": [
0,
0
],
"glyphs": "https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key=uwvyvzaF2P7UWbyOEvjU",
"layers": [
{
"id": "satellite",
"type": "raster",
"paint": {
"raster-opacity": 1
},
"filter": [
"all"
],
"layout": {
"visibility": "visible"
},
"source": "satellite",
"minzoom": 0
},
{
"id": "tunnel",
"type": "line",
"paint": {
"line-color": "rgba(255, 255, 255, 0.2)",
"line-width": [
"interpolate",
[
"exponential",
1.5
],
[
"zoom"
],
6,
0.5,
20,
30
],
"line-dasharray": [
0.28,
0.14
]
},
"filter": [
"all",
[
"==",
"$type",
"LineString"
],
[
"==",
"brunnel",
"tunnel"
],
[
"in",
"class",
"motorway",
"primary",
"secondary",
"tertiary",
"trunk"
]
],
"layout": {
"line-cap": "butt",
"line-join": "miter"
},
"source": "openmaptiles",
"source-layer": "transportation"
},
{
"id": "path",
"type": "line",
"paint": {
"line-color": "rgba(247, 247, 247, 0.33)",
"line-width": [
"interpolate",
[
"exponential",
1.5
],
[
"zoom"
],
14,
0.5,
20,
4
],
"line-dasharray": [
1,
1
]
},
"filter": [
"all",
[
"==",
"$type",
"LineString"
],
[
"in",
"class",
"path",
"track"
]
],
"layout": {
"line-cap": "square",
"line-join": "bevel"
},
"source": "openmaptiles",
"source-layer": "transportation"
},
{
"id": "road",
"type": "line",
"paint": {
"line-color": [
"interpolate",
[
"linear"
],
[
"zoom"
],
8,
"rgba(255, 255, 255, 0.2)",
14,
"rgba(255, 255, 255, 0.3)"
],
"line-width": [
"interpolate",
[
"linear"
],
[
"zoom"
],
5,
[
"match",
[
"get",
"class"
],
[
"motorway",
"motorway_link"
],
1,
0
],
7,
[
"match",
[
"get",
"class"
],
[
"motorway",
"motorway_link"
],
1.4,
0
],
8,
[
"match",
[
"get",
"class"
],
[
"motorway",
"motorway_link",
"primary",
"trunk"
],
0.75,
0
],
9,
[
"match",
[
"get",
"class"
],
[
"secondary",
"tertiary"
],
0.7,
1
],
10,
[
"match",
[
"get",
"class"
],
[
"motorway",
"motorway_link"
],
1.3,
1.3
],
14,
[
"match",
[
"get",
"class"
],
[
"minor",
"service"
],
0.5,
2.4
]
]
},
"filter": [
"all",
[
"==",
"$type",
"LineString"
],
[
"!in",
"class",
"rail",
"ferry",
"path",
"track"
],
[
"!=",
"brunnel",
"tunnel"
]
],
"layout": {
"line-cap": "butt",
"line-join": "round"
},
"source": "openmaptiles",
"minzoom": 6,
"source-layer": "transportation"
},
{
"id": "railway",
"type": "line",
"paint": {
"line-color": "rgba(179, 170, 158, 0.2)",
"line-opacity": [
"interpolate",
[
"linear"
],
[
"zoom"
],
11,
0.5,
16,
1.3
]
},
"filter": [
"==",
"class",
"rail"
],
"layout": {
"visibility": "visible"
},
"source": "openmaptiles",
"minzoom": 11,
"source-layer": "transportation"
},
{
"id": "admin_sub",
"type": "line",
"paint": {
"line-color": "rgba(194, 194, 194, 0.5)",
"line-dasharray": [
2,
1
]
},
"filter": [
"in",
"admin_level",
4,
6,
8
],
"layout": {
"visibility": "visible"
},
"source": "openmaptiles",
"minzoom": 3,
"source-layer": "boundary"
},
{
"id": "admin_country-dark",
"type": "line",
"paint": {
"line-color": "rgba(0, 0, 0, 0.51)",
"line-width": [
"interpolate",
[
"exponential",
1.5
],
[
"zoom"
],
3,
0.5,
21,
32
],
"line-offset": 1
},
"filter": [
"all",
[
"<=",
"admin_level",
2
],
[
"==",
"$type",
"LineString"
]
],
"layout": {
"line-cap": "butt",
"line-join": "round",
"visibility": "visible"
},
"source": "openmaptiles",
"source-layer": "boundary"
},
{
"id": "admin_country",
"type": "line",
"paint": {
"line-color": "rgba(226, 226, 226, 1)",
"line-width": [
"interpolate",
[
"exponential",
1.5
],
[
"zoom"
],
3,
0.5,
21,
32
]
},
"filter": [
"all",
[
"<=",
"admin_level",
2
],
[
"==",
"$type",
"LineString"
]
],
"layout": {
"line-cap": "round",
"line-join": "round",
"visibility": "visible"
},
"source": "openmaptiles",
"source-layer": "boundary"
},
{
"id": "road_label",
"type": "symbol",
"paint": {
"text-color": "rgba(255, 255, 255, 1)",
"text-halo-color": "rgba(43, 43, 43, 1)",
"text-halo-width": 1
},
"filter": [
"==",
"$type",
"LineString"
],
"layout": {
"text-font": [
"Noto Sans Regular"
],
"text-size": [
"interpolate",
[
"cubic-bezier",
0.75,
1,
0.75,
1
],
[
"zoom"
],
10,
8,
15,
9
],
"text-field": "{name:latin} {name:nonlatin}",
"text-transform": "none",
"symbol-placement": "line",
"text-letter-spacing": 0.1,
"text-rotation-alignment": "map"
},
"source": "openmaptiles",
"source-layer": "transportation_name"
},
{
"id": "place_label",
"type": "symbol",
"paint": {
"text-color": "rgba(255, 255, 255, 1)",
"text-halo-blur": 0.5,
"text-halo-color": [
"match",
[
"get",
"class"
],
[
"city"
],
"rgba(0, 0, 0, 0.75)",
"rgba(43, 43, 43, 1)"
],
"text-halo-width": 1
},
"filter": [
"all",
[
"==",
"$type",
"Point"
],
[
"!in",
"class",
"country",
"state"
]
],
"layout": {
"text-font": [
"Noto Sans Regular"
],
"text-size": [
"interpolate",
[
"cubic-bezier",
0.5,
1,
0.5,
1
],
[
"zoom"
],
3,
[
"match",
[
"get",
"class"
],
"city",
11,
10
],
6,
[
"match",
[
"get",
"class"
],
"city",
14.5,
11
],
8,
[
"match",
[
"get",
"class"
],
"city",
16,
12
],
10,
[
"match",
[
"get",
"class"
],
"city",
20,
13
]
],
"text-field": "{name:latin}\n{name:nonlatin}",
"text-max-width": 10
},
"source": "openmaptiles",
"maxzoom": 16,
"minzoom": 3,
"source-layer": "place"
},
{
"id": "state_label",
"type": "symbol",
"paint": {
"text-color": "rgba(255, 255, 255, 1)",
"text-halo-blur": 1,
"text-halo-color": "rgba(0, 0, 0, 1)",
"text-halo-width": 1
},
"filter": [
"all",
[
"==",
"$type",
"Point"
],
[
"in",
"class",
"state"
]
],
"layout": {
"text-font": [
"Noto Sans Italic"
],
"text-size": [
"interpolate",
[
"cubic-bezier",
0.75,
1,
0.75,
1
],
[
"zoom"
],
1,
[
"step",
[
"get",
"rank"
],
13,
1,
12,
2,
12
],
4,
[
"step",
[
"get",
"rank"
],
15,
1,
14,
2,
14
],
6,
[
"step",
[
"get",
"rank"
],
23,
1,
18,
2,
18
],
9,
[
"step",
[
"get",
"rank"
],
27,
1,
22,
2,
22
]
],
"text-field": "{name:latin}",
"text-max-width": 10
},
"source": "openmaptiles",
"maxzoom": 12,
"minzoom": 3,
"source-layer": "place"
},
{
"id": "country_label",
"type": "symbol",
"paint": {
"text-color": "rgba(255, 255, 255, 1)",
"text-halo-blur": 1,
"text-halo-color": "rgba(0, 0, 0, 1)",
"text-halo-width": 1
},
"filter": [
"all",
[
"==",
"$type",
"Point"
],
[
"in",
"class",
"country"
]
],
"layout": {
"text-font": [
"Noto Sans Bold"
],
"text-size": [
"interpolate",
[
"cubic-bezier",
0.75,
1,
0.75,
1
],
[
"zoom"
],
1,
[
"step",
[
"get",
"rank"
],
13,
1,
12,
2,
12
],
4,
[
"step",
[
"get",
"rank"
],
15,
1,
14,
2,
14
],
6,
[
"step",
[
"get",
"rank"
],
23,
1,
18,
2,
18
],
9,
[
"step",
[
"get",
"rank"
],
27,
1,
22,
2,
22
]
],
"text-field": "{name:latin}",
"text-max-width": 10
},
"source": "openmaptiles",
"maxzoom": 12,
"source-layer": "place"
}
],
"bearing": 0,
"sources": {
"satellite": {
"url": "https://api.maptiler.com/tiles/satellite/tiles.json?key=uwvyvzaF2P7UWbyOEvjU",
"type": "raster",
"tileSize": 256
},
"openmaptiles": {
"url": "https://api.maptiler.com/tiles/v3/tiles.json?key=uwvyvzaF2P7UWbyOEvjU",
"type": "vector"
}
},
"version": 8,
"metadata": {
"maputnik:renderer": "mbgljs",
"openmaptiles:version": "3.x"
}
}

View File

@@ -0,0 +1 @@
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"LineString","coordinates":[[-121.3714599609375,38.64583568648869],[-121.48681640624999,38.64047263931154],[-121.53076171875,38.61579745317875],[-121.56509399414061,38.57823196583313],[-121.75186157226561,38.533127435052776],[-121.97021484374999,38.35350340353833],[-122.08007812499999,38.24680876017446],[-122.16796875,38.19718009396176],[-122.23800659179686,38.09457899232253],[-122.27371215820312,38.01455819225337],[-122.33551025390625,37.94094845586459],[-122.27371215820312,37.81846319511331],[-122.4151611328125,37.7652868250379]]}}]}

View File

@@ -0,0 +1 @@
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[-122.28813171386719,38.617406963286136],[-122.26959228515624,38.6833657775237],[-122.18238830566406,38.55568323796419],[-122.10617065429688,38.51378825951165],[-122.11509704589845,38.50465406475561],[-122.18307495117188,38.542795073979015],[-122.19955444335938,38.496593518947556],[-122.28813171386719,38.617406963286136]]]}}]}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [40, -30]
},
"properties": {
"image-name": "popup-debug",
"name": "Line 1\nLine 2\nLine 3"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [40, 30]
},
"properties": {
"image-name": "popup",
"name": "Line 1\nLine 2\nLine 3"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-40, -30]
},
"properties": {
"image-name": "popup-debug",
"name": "One longer line"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-40, 30]
},
"properties": {
"image-name": "popup",
"name": "One longer line"
}
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 552 B

View File

@@ -0,0 +1,85 @@
package org.maplibre.android.testapp
import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy
import android.os.StrictMode.VmPolicy
import android.text.TextUtils
import androidx.multidex.MultiDexApplication
import org.maplibre.android.MapStrictMode
import org.maplibre.android.MapLibre
import org.maplibre.android.WellKnownTileServer
import org.maplibre.android.log.Logger
import org.maplibre.android.testapp.utils.ApiKeyUtils
import org.maplibre.android.testapp.utils.TileLoadingMeasurementUtils
import org.maplibre.android.testapp.utils.TimberLogger
import timber.log.Timber
import timber.log.Timber.DebugTree
/**
* Application class of the test application.
*
*
* Initialises components as LeakCanary, Strictmode, Timber and MapLibre
*
*/
open class MapLibreApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
initializeLogger()
initializeStrictMode()
initializeMapbox()
}
private fun initializeLogger() {
Logger.setLoggerDefinition(TimberLogger())
if (BuildConfig.DEBUG) {
Timber.plant(DebugTree())
}
}
private fun initializeStrictMode() {
StrictMode.setThreadPolicy(
ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build()
)
StrictMode.setVmPolicy(
VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build()
)
}
private fun initializeMapbox() {
val apiKey = ApiKeyUtils.getApiKey(applicationContext)
if (apiKey != null) {
validateApiKey(apiKey)
}
MapLibre.getInstance(applicationContext, apiKey, TILE_SERVER)
TileLoadingMeasurementUtils.setUpTileLoadingMeasurement()
MapStrictMode.setStrictModeEnabled(true)
}
companion object {
val TILE_SERVER = WellKnownTileServer.MapTiler
private const val DEFAULT_API_KEY = "YOUR_API_KEY_GOES_HERE"
private const val API_KEY_NOT_SET_MESSAGE =
(
"In order to run the Test App you need to set a valid " +
"API key. During development, you can set the MLN_API_KEY environment variable for the SDK to " +
"automatically include it in the Test App. Otherwise, you can manually include it in the " +
"res/values/developer-config.xml file in the MapLibreAndroidTestApp folder."
)
private fun validateApiKey(apiKey: String) {
if (TextUtils.isEmpty(apiKey) || apiKey == DEFAULT_API_KEY) {
Timber.e(API_KEY_NOT_SET_MESSAGE)
}
}
}
}

View File

@@ -0,0 +1,173 @@
package org.maplibre.android.testapp.activity
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.Resources.NotFoundException
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.SimpleOnItemTouchListener
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.adapter.FeatureAdapter
import org.maplibre.android.testapp.adapter.FeatureSectionAdapter
import org.maplibre.android.testapp.model.activity.Feature
import org.maplibre.android.testapp.utils.ItemClickSupport
import timber.log.Timber
import java.util.*
/**
* Activity shown when application is started
*
*
* This activity will generate data for RecyclerView based on the AndroidManifest entries.
* It uses tags as category and description to order the different entries.
*
*/
class FeatureOverviewActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private var sectionAdapter: FeatureSectionAdapter? = null
private var features: List<Feature>? = null
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feature_overview)
recyclerView = findViewById<View>(R.id.recyclerView) as RecyclerView
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.addOnItemTouchListener(SimpleOnItemTouchListener())
recyclerView.setHasFixedSize(true)
ItemClickSupport.addTo(recyclerView)
.setOnItemClickListener(object : ItemClickSupport.OnItemClickListener {
override fun onItemClicked(recyclerView: RecyclerView?, position: Int, view: View?) {
if (sectionAdapter!!.isSectionHeaderPosition(position).not()) {
val itemPosition = sectionAdapter!!.getConvertedPosition(position)
val feature = features!![itemPosition]
startFeature(feature)
}
}
})
if (savedInstanceState == null) {
loadFeatures()
} else {
features = savedInstanceState.getParcelableArrayList(KEY_STATE_FEATURES)
onFeaturesLoaded(features)
}
}
private fun loadFeatures() {
try {
LoadFeatureTask().execute(
packageManager.getPackageInfo(
packageName,
PackageManager.GET_ACTIVITIES or PackageManager.GET_META_DATA
)
)
} catch (exception: PackageManager.NameNotFoundException) {
Timber.e(exception, "Could not resolve package info")
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun onFeaturesLoaded(featuresList: List<Feature>?) {
features = featuresList
if (featuresList == null || featuresList.isEmpty()) {
return
}
val sections: MutableList<FeatureSectionAdapter.Section> = ArrayList()
var currentCat = ""
for (i in features!!.indices) {
val category = features!![i].category
if (currentCat != category) {
sections.add(FeatureSectionAdapter.Section(i, category))
currentCat = category
}
}
sectionAdapter = FeatureSectionAdapter(
this,
R.layout.section_main_layout,
R.id.section_text,
FeatureAdapter(features!!)
)
sectionAdapter!!.setSections(sections.toTypedArray())
recyclerView!!.adapter = sectionAdapter
}
private fun startFeature(feature: Feature) {
val intent = Intent()
intent.component = ComponentName(packageName, feature.name)
startActivity(intent)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelableArrayList(KEY_STATE_FEATURES, features as ArrayList<Feature>?)
}
private inner class LoadFeatureTask : AsyncTask<PackageInfo?, Void?, List<Feature>>() {
protected override fun doInBackground(vararg p0: PackageInfo?): List<Feature>? {
val features: MutableList<Feature> = ArrayList()
val app = p0[0]
val packageName = FeatureOverviewActivity.javaClass.`package`.name
val metaDataKey = getString(R.string.category)
if (app != null) {
for (info in app.activities) {
if (info.labelRes != 0 && info.name.startsWith(packageName) &&
info.name != FeatureOverviewActivity::class.java.name
) {
val label = getString(info.labelRes)
val description = resolveString(info.descriptionRes)
val category = resolveMetaData(info.metaData, metaDataKey)
features.add(Feature(info.name, label, description, category!!))
}
}
}
if (!features.isEmpty()) {
val comparator = Comparator { lhs: Feature, rhs: Feature ->
var result = lhs.category.compareTo(rhs.category, ignoreCase = true)
if (result == 0) {
result = lhs.getLabel().compareTo(rhs.getLabel(), ignoreCase = true)
}
result
}
Collections.sort(features, comparator)
}
return features
}
private fun resolveMetaData(bundle: Bundle?, key: String): String? {
var category: String? = null
if (bundle != null) {
category = bundle.getString(key)
}
return category
}
private fun resolveString(@StringRes stringRes: Int): String {
return try {
getString(stringRes)
} catch (exception: NotFoundException) {
"-"
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onPostExecute(features: List<Feature>) {
super.onPostExecute(features)
onFeaturesLoaded(features)
}
}
companion object {
private const val KEY_STATE_FEATURES = "featureList"
}
}

View File

@@ -0,0 +1,186 @@
package org.maplibre.android.testapp.activity.annotation
import android.app.ProgressDialog
import android.os.AsyncTask
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.MenuItemCompat
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.GeoParseUtil
import timber.log.Timber
import java.io.IOException
import java.lang.ref.WeakReference
import java.text.DecimalFormat
import java.util.*
/**
* Test activity showcasing adding a large amount of Markers.
*/
class BulkMarkerActivity : AppCompatActivity(), OnItemSelectedListener {
private lateinit var maplibreMap: MapLibreMap
private lateinit var mapView: MapView
private var locations: List<LatLng>? = null
private var progressDialog: ProgressDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_marker_bulk)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(OnMapReadyCallback { maplibreMap: MapLibreMap -> initMap(maplibreMap) })
}
private fun initMap(maplibreMap: MapLibreMap) {
this.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val spinnerAdapter = ArrayAdapter.createFromResource(
this,
R.array.bulk_marker_list,
android.R.layout.simple_spinner_item
)
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
menuInflater.inflate(R.menu.menu_bulk_marker, menu)
val item = menu.findItem(R.id.spinner)
val spinner = MenuItemCompat.getActionView(item) as Spinner
spinner.adapter = spinnerAdapter
spinner.onItemSelectedListener = this@BulkMarkerActivity
return true
}
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
val amount = Integer.valueOf(resources.getStringArray(R.array.bulk_marker_list)[position])
if (locations == null) {
progressDialog = ProgressDialog.show(this, "Loading", "Fetching markers", false)
LoadLocationTask(this, amount).execute()
} else {
showMarkers(amount)
}
}
private fun onLatLngListLoaded(latLngs: List<LatLng>?, amount: Int) {
progressDialog!!.hide()
locations = latLngs
showMarkers(amount)
}
private fun showMarkers(amount: Int) {
var amount = amount
if (maplibreMap == null || locations == null || mapView.isDestroyed) {
return
}
maplibreMap.clear()
if (locations!!.size < amount) {
amount = locations!!.size
}
showGlMarkers(amount)
}
private fun showGlMarkers(amount: Int) {
val markerOptionsList: MutableList<MarkerOptions> = ArrayList()
val formatter = DecimalFormat("#.#####")
val random = Random()
var randomIndex: Int
for (i in 0 until amount) {
randomIndex = random.nextInt(locations!!.size)
val latLng = locations!![randomIndex]
markerOptionsList.add(
MarkerOptions()
.position(latLng)
.title(i.toString())
.snippet(formatter.format(latLng.latitude) + "`, " + formatter.format(latLng.longitude))
)
}
maplibreMap.addMarkers(markerOptionsList)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// nothing selected, nothing to do!
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
if (progressDialog != null) {
progressDialog!!.dismiss()
}
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
private class LoadLocationTask constructor(
activity: BulkMarkerActivity,
private val amount: Int
) : AsyncTask<Void?, Int?, List<LatLng>?>() {
private val activity: WeakReference<BulkMarkerActivity>
override fun doInBackground(vararg p0: Void?): List<LatLng>? {
val activity = activity.get()
if (activity != null) {
var json: String? = null
try {
json = GeoParseUtil.loadStringFromAssets(
activity.applicationContext,
"points.geojson"
)
} catch (exception: IOException) {
Timber.e(exception, "Could not add markers")
}
if (json != null) {
return GeoParseUtil.parseGeoJsonCoordinates(json)
}
}
return null
}
override fun onPostExecute(locations: List<LatLng>?) {
super.onPostExecute(locations)
val activity = activity.get()
activity?.onLatLngListLoaded(locations, amount)
}
init {
this.activity = WeakReference(activity)
}
}
}

View File

@@ -0,0 +1,128 @@
package org.maplibre.android.testapp.activity.annotation
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.maplibre.android.annotations.Marker
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.IconUtils
/**
* Test activity showcasing updating a Marker position, title, icon and snippet.
*/
class DynamicMarkerChangeActivity : AppCompatActivity() {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private var marker: Marker? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dynamic_marker)
mapView = findViewById(R.id.mapView)
mapView.setTag(false)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { maplibreMap: MapLibreMap ->
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
this@DynamicMarkerChangeActivity.maplibreMap = maplibreMap
// Create marker
val markerOptions = MarkerOptions()
.position(LAT_LNG_CHELSEA)
.icon(
IconUtils.drawableToIcon(
this@DynamicMarkerChangeActivity,
R.drawable.ic_stars,
ResourcesCompat.getColor(resources, R.color.blueAccent, theme)
)
)
.title(getString(R.string.dynamic_marker_chelsea_title))
.snippet(getString(R.string.dynamic_marker_chelsea_snippet))
marker = maplibreMap.addMarker(markerOptions)
}
)
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setColorFilter(ContextCompat.getColor(this, R.color.primary))
fab.setOnClickListener { view: View? ->
updateMarker()
}
}
private fun updateMarker() {
// update model
val first = mapView.tag as Boolean
mapView.tag = !first
// update marker
marker!!.position =
if (first) LAT_LNG_CHELSEA else LAT_LNG_ARSENAL
marker!!.icon = IconUtils.drawableToIcon(
this,
R.drawable.ic_stars,
if (first) {
ResourcesCompat.getColor(
resources,
R.color.blueAccent,
theme
)
} else {
ResourcesCompat.getColor(
resources,
R.color.redAccent,
theme
)
}
)
marker!!.title =
if (first) getString(R.string.dynamic_marker_chelsea_title) else getString(R.string.dynamic_marker_arsenal_title)
marker!!.snippet =
if (first) getString(R.string.dynamic_marker_chelsea_snippet) else getString(R.string.dynamic_marker_arsenal_snippet)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
companion object {
private val LAT_LNG_CHELSEA = LatLng(51.481670, -0.190849)
private val LAT_LNG_ARSENAL = LatLng(51.555062, -0.108417)
}
}

View File

@@ -0,0 +1,185 @@
package org.maplibre.android.testapp.activity.annotation
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.drawable.toBitmap
import com.mapbox.geojson.FeatureCollection
import com.mapbox.geojson.Point
import okhttp3.Call
import okhttp3.Callback
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.maplibre.android.MapLibre
import org.maplibre.android.annotations.IconFactory
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.geometry.LatLngBounds
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapView
import org.maplibre.android.testapp.R
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Locale
/* ANCHOR: top */
class JsonApiActivity : AppCompatActivity() {
// Declare a variable for MapView
private lateinit var mapView: MapView
// Declare a variable for MapboxMap
private lateinit var maplibreMap: MapLibreMap
/* ANCHOR_END: top */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Init MapLibre
MapLibre.getInstance(this)
// Init layout view
setContentView(R.layout.activity_json_api)
// Init the MapView
mapView = findViewById(R.id.mapView)
/* ANCHOR: mapAsync */
mapView.getMapAsync { map ->
maplibreMap = map
maplibreMap.setStyle("https://demotiles.maplibre.org/style.json")
// Fetch data from USGS
getEarthQuakeDataFromUSGS()
}
/* ANCHOR_END: mapAsync */
}
/* ANCHOR: getEarthquakes */
// Get Earthquake data from usgs.gov, read API doc at:
// https://earthquake.usgs.gov/fdsnws/event/1/
private fun getEarthQuakeDataFromUSGS() {
val url = "https://earthquake.usgs.gov/fdsnws/event/1/query".toHttpUrl().newBuilder()
.addQueryParameter("format", "geojson")
.addQueryParameter("starttime", "2022-01-01")
.addQueryParameter("endtime", "2022-12-31")
.addQueryParameter("minmagnitude", "5.8")
.addQueryParameter("latitude", "24")
.addQueryParameter("longitude", "121")
.addQueryParameter("maxradius", "1.5")
.build()
val request: Request = Request.Builder().url(url).build()
OkHttpClient().newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Toast.makeText(this@JsonApiActivity, "Fail to fetch data", Toast.LENGTH_SHORT)
.show()
}
override fun onResponse(call: Call, response: Response) {
val featureCollection = response.body?.string()
?.let(FeatureCollection::fromJson)
?: return
// If FeatureCollection in response is not null
// Then add markers to map
runOnUiThread { addMarkersToMap(featureCollection) }
}
})
}
/* ANCHOR_END: getEarthquakes */
/* ANCHOR: addMarkers */
private fun addMarkersToMap(data: FeatureCollection) {
val bounds = mutableListOf<LatLng>()
// Get bitmaps for marker icon
val infoIconDrawable = ResourcesCompat.getDrawable(
this.resources,
// Intentionally specify package name
// This makes copy from another project easier
org.maplibre.android.R.drawable.maplibre_info_icon_default,
null
)!!
val bitmapBlue = infoIconDrawable.toBitmap()
val bitmapRed = infoIconDrawable
.mutate()
.apply { setTint(Color.RED) }
.toBitmap()
// Add symbol for each point feature
data.features()?.forEach { feature ->
val geometry = feature.geometry()?.toJson() ?: return@forEach
val point = Point.fromJson(geometry) ?: return@forEach
val latLng = LatLng(point.latitude(), point.longitude())
bounds.add(latLng)
// Contents in InfoWindow of each marker
val title = feature.getStringProperty("title")
val epochTime = feature.getNumberProperty("time")
val dateString = SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.TAIWAN).format(epochTime)
// If magnitude > 6.0, show marker with red icon. If not, show blue icon instead
val mag = feature.getNumberProperty("mag")
val icon = IconFactory.getInstance(this)
.fromBitmap(if (mag.toFloat() > 6.0) bitmapRed else bitmapBlue)
// Use MarkerOptions and addMarker() to add a new marker in map
val markerOptions = MarkerOptions()
.position(latLng)
.title(dateString)
.snippet(title)
.icon(icon)
maplibreMap.addMarker(markerOptions)
}
// Move camera to newly added annotations
maplibreMap.getCameraForLatLngBounds(LatLngBounds.fromLatLngs(bounds))?.let {
val newCameraPosition = CameraPosition.Builder()
.target(it.target)
.zoom(it.zoom - 0.5)
.build()
maplibreMap.cameraPosition = newCameraPosition
}
}
/* ANCHOR_END: addMarkers */
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
}

View File

@@ -0,0 +1,199 @@
package org.maplibre.android.testapp.activity.annotation
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.annotations.Polygon
import org.maplibre.android.annotations.PolygonOptions
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.* // ktlint-disable no-wildcard-imports
import org.maplibre.android.testapp.R
import java.util.ArrayList
/**
* Test activity to showcase the Polygon annotation API & programmatically creating a MapView.
*
*
* Shows how to change Polygon features as visibility, alpha, color and points.
*
*/
class PolygonActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private var polygon: Polygon? = null
private var fullAlpha = true
private var polygonIsVisible = true
private var color = true
private var allPoints = true
private var holes = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// configure inital map state
val options = MapLibreMapOptions.createFromAttributes(this, null)
.attributionTintColor(Config.RED_COLOR)
.compassFadesWhenFacingNorth(false)
.camera(
CameraPosition.Builder()
.target(LatLng(45.520486, -122.673541))
.zoom(12.0)
.tilt(40.0)
.build()
)
// create map
mapView = MapView(this, options)
mapView.id = R.id.mapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
setContentView(mapView)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
map.setStyle(Style.getPredefinedStyle("Streets"))
map.setOnPolygonClickListener { polygon: Polygon ->
Toast.makeText(
this@PolygonActivity,
"You clicked on polygon with id = " + polygon.id,
Toast.LENGTH_SHORT
).show()
}
polygon = maplibreMap.addPolygon(
PolygonOptions()
.addAll(Config.STAR_SHAPE_POINTS)
.fillColor(Config.BLUE_COLOR)
)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_id_alpha -> {
fullAlpha = !fullAlpha
polygon!!.alpha =
if (fullAlpha) Config.FULL_ALPHA else Config.PARTIAL_ALPHA
true
}
R.id.action_id_visible -> {
polygonIsVisible = !polygonIsVisible
polygon!!.alpha =
if (polygonIsVisible) if (fullAlpha) Config.FULL_ALPHA else Config.PARTIAL_ALPHA else Config.NO_ALPHA
true
}
R.id.action_id_points -> {
allPoints = !allPoints
polygon!!.points =
if (allPoints) Config.STAR_SHAPE_POINTS else Config.BROKEN_SHAPE_POINTS
true
}
R.id.action_id_color -> {
color = !color
polygon!!.fillColor =
if (color) Config.BLUE_COLOR else Config.RED_COLOR
true
}
R.id.action_id_holes -> {
holes = !holes
polygon!!.holes =
if (holes) Config.STAR_SHAPE_HOLES else emptyList()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_polygon, menu)
return true
}
internal object Config {
val BLUE_COLOR = Color.parseColor("#3bb2d0")
val RED_COLOR = Color.parseColor("#AF0000")
const val FULL_ALPHA = 1.0f
const val PARTIAL_ALPHA = 0.5f
const val NO_ALPHA = 0.0f
val STAR_SHAPE_POINTS: ArrayList<LatLng?> = object : ArrayList<LatLng?>() {
init {
add(LatLng(45.522585, -122.685699))
add(LatLng(45.534611, -122.708873))
add(LatLng(45.530883, -122.678833))
add(LatLng(45.547115, -122.667503))
add(LatLng(45.530643, -122.660121))
add(LatLng(45.533529, -122.636260))
add(LatLng(45.521743, -122.659091))
add(LatLng(45.510677, -122.648792))
add(LatLng(45.515008, -122.664070))
add(LatLng(45.502496, -122.669048))
add(LatLng(45.515369, -122.678489))
add(LatLng(45.506346, -122.702007))
add(LatLng(45.522585, -122.685699))
}
}
val BROKEN_SHAPE_POINTS = STAR_SHAPE_POINTS.subList(0, STAR_SHAPE_POINTS.size - 3)
val STAR_SHAPE_HOLES: ArrayList<List<LatLng?>?> = object : ArrayList<List<LatLng?>?>() {
init {
add(
ArrayList<LatLng>(object : ArrayList<LatLng?>() {
init {
add(LatLng(45.521743, -122.669091))
add(LatLng(45.530483, -122.676833))
add(LatLng(45.520483, -122.676833))
add(LatLng(45.521743, -122.669091))
}
})
)
add(
ArrayList<LatLng>(object : ArrayList<LatLng?>() {
init {
add(LatLng(45.529743, -122.662791))
add(LatLng(45.525543, -122.662791))
add(LatLng(45.525543, -122.660))
add(LatLng(45.527743, -122.660))
add(LatLng(45.529743, -122.662791))
}
})
)
}
}
}
}

View File

@@ -0,0 +1,209 @@
package org.maplibre.android.testapp.activity.annotation
import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.annotations.Polyline
import org.maplibre.android.annotations.PolylineOptions
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import java.util.*
/**
* Test activity showcasing the Polyline annotations API.
*
*
* Shows how to add and remove polylines.
*
*/
class PolylineActivity : AppCompatActivity() {
private var polylines: MutableList<Polyline>? = null
private var polylineOptions: ArrayList<PolylineOptions?>? = ArrayList()
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private var fullAlpha = true
private var showPolylines = true
private var width = true
private var color = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_polyline)
if (savedInstanceState != null) {
polylineOptions = savedInstanceState.getParcelableArrayList(STATE_POLYLINE_OPTIONS)
} else {
polylineOptions!!.addAll(allPolylines)
}
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { maplibreMap: MapLibreMap ->
this@PolylineActivity.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Satellite Hybrid"))
maplibreMap.setOnPolylineClickListener { polyline: Polyline ->
Toast.makeText(
this@PolylineActivity,
"You clicked on polyline with id = " + polyline.id,
Toast.LENGTH_SHORT
).show()
}
polylines = maplibreMap.addPolylines(polylineOptions!!)
}
)
val fab = findViewById<View>(R.id.fab)
fab?.setOnClickListener { view: View? ->
if (maplibreMap != null) {
if (polylines != null && polylines!!.size > 0) {
if (polylines!!.size == 1) {
// test for removing annotation
maplibreMap.removeAnnotation(polylines!![0])
} else {
// test for removing annotations
maplibreMap.removeAnnotations(polylines!!)
}
}
polylineOptions!!.clear()
polylineOptions!!.addAll(randomLine)
polylines = maplibreMap.addPolylines(polylineOptions!!)
}
}
}
private val allPolylines: List<PolylineOptions?>
private get() {
val options: MutableList<PolylineOptions?> = ArrayList()
options.add(generatePolyline(ANDORRA, LUXEMBOURG, "#F44336"))
options.add(generatePolyline(ANDORRA, MONACO, "#FF5722"))
options.add(generatePolyline(MONACO, VATICAN_CITY, "#673AB7"))
options.add(generatePolyline(VATICAN_CITY, SAN_MARINO, "#009688"))
options.add(generatePolyline(SAN_MARINO, LIECHTENSTEIN, "#795548"))
options.add(generatePolyline(LIECHTENSTEIN, LUXEMBOURG, "#3F51B5"))
return options
}
private fun generatePolyline(start: LatLng, end: LatLng, color: String): PolylineOptions {
val line = PolylineOptions()
line.add(start)
line.add(end)
line.color(Color.parseColor(color))
return line
}
val randomLine: List<PolylineOptions?>
get() {
val randomLines = allPolylines
Collections.shuffle(randomLines)
return object : ArrayList<PolylineOptions?>() {
init {
add(randomLines[0])
}
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
outState.putParcelableArrayList(STATE_POLYLINE_OPTIONS, polylineOptions)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_polyline, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (polylines!!.size <= 0) {
Toast.makeText(this@PolylineActivity, "No polylines on map", Toast.LENGTH_LONG).show()
return super.onOptionsItemSelected(item)
}
return when (item.itemId) {
R.id.action_id_remove -> {
// test to remove all annotations
polylineOptions!!.clear()
maplibreMap.clear()
polylines!!.clear()
true
}
R.id.action_id_alpha -> {
fullAlpha = !fullAlpha
for (p in polylines!!) {
p.alpha = if (fullAlpha) FULL_ALPHA else PARTIAL_ALPHA
}
true
}
R.id.action_id_color -> {
color = !color
for (p in polylines!!) {
p.color = if (color) Color.RED else Color.BLUE
}
true
}
R.id.action_id_width -> {
width = !width
for (p in polylines!!) {
p.width = if (width) 3.0f else 5.0f
}
true
}
R.id.action_id_visible -> {
showPolylines = !showPolylines
for (p in polylines!!) {
p.alpha =
if (showPolylines) (if (fullAlpha) FULL_ALPHA else PARTIAL_ALPHA) else NO_ALPHA
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
companion object {
private const val STATE_POLYLINE_OPTIONS = "polylineOptions"
private val ANDORRA = LatLng(42.505777, 1.52529)
private val LUXEMBOURG = LatLng(49.815273, 6.129583)
private val MONACO = LatLng(43.738418, 7.424616)
private val VATICAN_CITY = LatLng(41.902916, 12.453389)
private val SAN_MARINO = LatLng(43.942360, 12.457777)
private val LIECHTENSTEIN = LatLng(47.166000, 9.555373)
private const val FULL_ALPHA = 1.0f
private const val PARTIAL_ALPHA = 0.5f
private const val NO_ALPHA = 0.0f
}
}

View File

@@ -0,0 +1,134 @@
package org.maplibre.android.testapp.activity.annotation
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import java.text.DecimalFormat
import java.util.ArrayList
/**
* Test activity showcasing to add a Marker on click.
*
*
* Shows how to use a OnMapClickListener and a OnMapLongClickListener
*
*/
class PressForMarkerActivity : AppCompatActivity() {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private var markerList: ArrayList<MarkerOptions>? = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_press_for_marker)
mapView = findViewById<View>(R.id.mapView) as MapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { map: MapLibreMap? ->
if (map != null) {
maplibreMap = map
}
resetMap()
maplibreMap.addOnMapLongClickListener { point: LatLng ->
addMarker(point)
false
}
maplibreMap.addOnMapClickListener { point: LatLng ->
addMarker(point)
false
}
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
if (savedInstanceState != null) {
markerList = savedInstanceState.getParcelableArrayList(STATE_MARKER_LIST)
if (markerList != null) {
maplibreMap.addMarkers(markerList!!)
}
}
}
}
private fun addMarker(point: LatLng) {
val pixel = maplibreMap.projection.toScreenLocation(point)
val title = (
LAT_LON_FORMATTER.format(point.latitude) + ", " +
LAT_LON_FORMATTER.format(point.longitude)
)
val snippet = "X = " + pixel.x.toInt() + ", Y = " + pixel.y.toInt()
val marker = MarkerOptions()
.position(point)
.title(title)
.snippet(snippet)
markerList!!.add(marker)
maplibreMap.addMarker(marker)
}
private fun resetMap() {
if (maplibreMap == null) {
return
}
markerList!!.clear()
maplibreMap.removeAnnotations()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_press_for_marker, menu)
return true
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
outState.putParcelableArrayList(STATE_MARKER_LIST, markerList)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menuItemReset -> {
resetMap()
true
}
else -> super.onOptionsItemSelected(item)
}
}
companion object {
private val LAT_LON_FORMATTER = DecimalFormat("#.#####")
private const val STATE_MARKER_LIST = "markerList"
}
}

View File

@@ -0,0 +1,365 @@
package org.maplibre.android.testapp.activity.benchmark
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.putJsonObject
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.maplibre.android.BuildConfig.GIT_REVISION
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.log.Logger
import org.maplibre.android.log.Logger.INFO
import org.maplibre.android.maps.*
import org.maplibre.android.maps.MapLibreMap.CancelableCallback
import org.maplibre.android.testapp.BuildConfig
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.FpsStore
import org.maplibre.android.testapp.utils.BenchmarkResults
import org.maplibre.android.testapp.utils.FrameTimeStore
import java.io.File
import java.util.*
data class BenchmarkInputData(
val styleNames: List<String>,
val styleURLs: List<String>,
val resultsAPI: String = ""
) {
init {
if (styleNames.size != styleURLs.size)
throw Error("Different size: styleNames=$styleNames, styleURLs=$styleURLs")
}
}
/**
* Prepares JSON payload that is sent to the API that collects benchmark results.
* See https://github.com/maplibre/ci-runners
*/
@SuppressLint("NewApi")
fun jsonPayload(styleNames: List<String>, fpsResults: BenchmarkResults, encodingTimeResults: BenchmarkResults, renderingTimeResults: BenchmarkResults): JsonObject {
return buildJsonObject {
putJsonObject("resultsPerStyle") {
for (style in styleNames) {
putJsonObject(style) {
fpsResults.resultsPerStyle[style].let { results ->
if (results !== null) {
put("avgFps", JsonPrimitive(results.map { it.average }.average()))
put("low1pFps", JsonPrimitive(results.map { it.low1p }.average()))
}
}
encodingTimeResults.resultsPerStyle[style].let { results ->
if (results !== null) {
put("avgEncodingTime", JsonPrimitive(results.map { it.average }.average()))
put("low1pEncodingTime", JsonPrimitive(results.map { it.low1p }.average()))
}
}
renderingTimeResults.resultsPerStyle[style].let { results ->
if (results !== null) {
put("avgRenderingTime", JsonPrimitive(results.map { it.average }.average()))
put("low1pRenderingTime", JsonPrimitive(results.map { it.low1p }.average()))
}
}
}
}
}
put("deviceManufacturer", JsonPrimitive(Build.MANUFACTURER))
put("model", JsonPrimitive(Build.MODEL))
put("renderer", JsonPrimitive(BuildConfig.FLAVOR))
put("debugBuild", JsonPrimitive(BuildConfig.DEBUG))
put("gitRevision", JsonPrimitive(GIT_REVISION))
}
}
/**
* Benchmark using a [android.view.TextureView]
*/
class BenchmarkActivity : AppCompatActivity() {
private val TAG = "BenchmarkActivity"
private lateinit var mapView: MapView
private var handler: Handler? = null
private var delayed: Runnable? = null
private var fpsStore = FpsStore()
private var encodingTimeStore = FrameTimeStore()
private var renderingTimeStore = FrameTimeStore()
private var fpsResults = BenchmarkResults()
private var encodingTimeResults = BenchmarkResults()
private var renderingTimeResults = BenchmarkResults()
private var runsLeft = 5
private var measureFrameTime = true
// the styles used for the benchmark
// can be overridden adding with developer-config.xml
// ```xml
// <array name="benchmark_style_names">
// <item>Americana</item>
// </array>
// <array name="benchmark_style_urls">
// <item>https://zelonewolf.github.io/openstreetmap-americana/style.json</item>
// </array>
// ```
private lateinit var inputData: BenchmarkInputData
@SuppressLint("DiscouragedApi")
private fun getStringFromResources(name: String): String {
return try {
resources.getString(applicationContext.resources.getIdentifier(
name,
"string",
applicationContext.packageName))
} catch (e: Throwable) {
""
}
}
@SuppressLint("DiscouragedApi")
private fun getArrayFromResources(name: String): Array<String> {
return try {
resources.getStringArray(applicationContext.resources.getIdentifier(
name,
"array",
applicationContext.packageName))
} catch (e: Throwable) {
emptyArray()
}
}
private fun getBenchmarkInputData(): BenchmarkInputData {
// read input for benchmark from JSON file (on CI)
val jsonFile = File("${Environment.getExternalStorageDirectory()}/benchmark-input.json")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager() && jsonFile.isFile) {
val jsonFileContents = jsonFile.readText()
val jsonElement = Json.parseToJsonElement(jsonFileContents)
val styleNames = jsonElement.jsonObject["styleNames"]?.jsonArray?.map { it.jsonPrimitive.content }
val styleURLs = jsonElement.jsonObject["styleURLs"]?.jsonArray?.map { it.jsonPrimitive.content }
val resultsAPI = jsonElement.jsonObject["resultsAPI"]?.jsonPrimitive?.content
if (styleNames == null || styleURLs == null || resultsAPI == null) {
throw Error("${jsonFile.name} is missing elements")
}
return BenchmarkInputData(
styleNames = styleNames.toList(),
styleURLs = styleURLs.toList(),
resultsAPI = resultsAPI
)
} else {
Logger.i(TAG, "${jsonFile.name} not found, reading from developer-config.xml")
}
// try to read from developer-config.xml instead (for development)
val styleNames = getArrayFromResources("benchmark_style_names")
val styleURLs = getArrayFromResources("benchmark_style_urls")
if (styleNames.isNotEmpty() && styleURLs.isNotEmpty()) {
return BenchmarkInputData(
styleNames = styleNames.toList(),
styleURLs = styleURLs.toList()
)
}
// return default
return BenchmarkInputData(
styleNames = listOf("MapLibre Demotiles"),
styleURLs = listOf("https://demotiles.maplibre.org/style.json")
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Logger.setVerbosity(INFO)
setContentView(R.layout.activity_benchmark)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
handler = Handler(mainLooper)
setupToolbar()
inputData = getBenchmarkInputData()
setupMapView(savedInstanceState)
}
private fun setupToolbar() {
val actionBar = supportActionBar
if (actionBar != null) {
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setHomeButtonEnabled(true)
}
}
private fun setupMapView(savedInstanceState: Bundle?) {
mapView = findViewById<View>(R.id.mapView) as MapView
if (measureFrameTime) {
mapView.addOnDidFinishRenderingFrameListener { fully: Boolean, frameEncodingTime: Double, frameRenderingTime: Double ->
encodingTimeStore.add(frameEncodingTime * 1e3)
renderingTimeStore.add(frameRenderingTime * 1e3)
}
}
mapView.getMapAsync { maplibreMap: MapLibreMap ->
maplibreMap.setStyle(inputData.styleURLs[0])
maplibreMap.setSwapBehaviorFlush(measureFrameTime)
if (!measureFrameTime) {
maplibreMap.setOnFpsChangedListener { fps: Double ->
fpsStore.add(fps)
}
}
// Start an animation on the map as well
flyTo(maplibreMap, 0, 0,14.0)
}
}
private fun flyTo(maplibreMap: MapLibreMap, place: Int, style: Int, zoom: Double) {
maplibreMap.animateCamera(
CameraUpdateFactory.newLatLngZoom(PLACES[place], zoom),
10000,
object : CancelableCallback {
override fun onCancel() {
delayed = Runnable {
delayed = null
flyTo(maplibreMap, place, style, zoom)
}
delayed?.let {
handler!!.postDelayed(it, 2000)
}
}
override fun onFinish() {
if (place == PLACES.size - 1) { // done with tour
if (measureFrameTime) {
encodingTimeResults.addResult(
inputData.styleNames[style],
encodingTimeStore
)
encodingTimeStore.reset()
println("Encoding time results $encodingTimeResults")
renderingTimeResults.addResult(
inputData.styleNames[style],
renderingTimeStore
)
renderingTimeStore.reset()
println("Rendering time results $renderingTimeResults")
} else {
fpsResults.addResult(inputData.styleNames[style], fpsStore)
fpsStore.reset()
println("FPS results $fpsResults")
}
println("Benchmark ${jsonPayload(inputData.styleNames, fpsResults, encodingTimeResults, renderingTimeResults)}")
if (style < inputData.styleURLs.size - 1) { // continue with next style
maplibreMap.setStyle(inputData.styleURLs[style + 1])
flyTo(maplibreMap, 0, style + 1, zoom)
} else if (runsLeft > 0) { // start over
--runsLeft
maplibreMap.setStyle(inputData.styleURLs[0])
flyTo(maplibreMap, 0, 0, zoom)
} else {
benchmarkDone()
}
return
}
// continue with next place
flyTo(maplibreMap, place + 1, style, zoom)
}
}
)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
if (handler != null && delayed != null) {
handler!!.removeCallbacks(delayed!!)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
private fun sendResults() {
val api = inputData.resultsAPI
if (api.isEmpty()) {
Logger.i(TAG, "Not sending results to API")
return
}
val client = OkHttpClient()
val payload = jsonPayload(inputData.styleNames, fpsResults, encodingTimeResults, renderingTimeResults)
Logger.i(TAG, "Sending JSON payload to API: $payload")
val request = Request.Builder()
.url(api)
.post(
Json.encodeToString(payload).toRequestBody("application/json".toMediaType()))
.build()
client.newCall(request).execute()
}
private fun benchmarkDone() {
sendResults()
setResult(Activity.RESULT_OK)
finish()
}
companion object {
private val PLACES = arrayOf(
LatLng(37.7749, -122.4194), // SF
LatLng(38.9072, -77.0369), // DC
LatLng(52.3702, 4.8952), // AMS
LatLng(60.1699, 24.9384), // HEL
LatLng(-13.1639, -74.2236), // AYA
LatLng(52.5200, 13.4050), // BER
LatLng(12.9716, 77.5946), // BAN
LatLng(31.2304, 121.4737) // SHA
)
}
}

View File

@@ -0,0 +1,163 @@
package org.maplibre.android.testapp.activity.camera
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapLibreMap.CancelableCallback
import org.maplibre.android.maps.MapLibreMap.OnCameraIdleListener
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import timber.log.Timber
/**
* Test activity showcasing the Camera API and listen to camera updates by animating the camera
* above London.
*
* Shows how to use animate, ease and move camera update factory methods.
*/
class CameraAnimationTypeActivity : AppCompatActivity(), OnMapReadyCallback {
private val callback: CancelableCallback =
object : CancelableCallback {
override fun onCancel() {
Timber.i("Duration onCancel Callback called.")
Toast.makeText(
this@CameraAnimationTypeActivity.applicationContext,
"Ease onCancel Callback called.",
Toast.LENGTH_LONG
)
.show()
}
override fun onFinish() {
Timber.i("Duration onFinish Callback called.")
Toast.makeText(
this@CameraAnimationTypeActivity.applicationContext,
"Ease onFinish Callback called.",
Toast.LENGTH_LONG
)
.show()
}
}
private lateinit var maplibreMap: MapLibreMap
private lateinit var mapView: MapView
private var cameraState = false
private val cameraIdleListener = OnCameraIdleListener {
if (maplibreMap != null) {
Timber.w(maplibreMap.cameraPosition.toString())
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera_animation_types)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
maplibreMap.setStyle(Style.Builder().fromUri(Style.getPredefinedStyle("Streets")))
maplibreMap.uiSettings.isAttributionEnabled = false
maplibreMap.uiSettings.isLogoEnabled = false
maplibreMap.addOnCameraIdleListener(cameraIdleListener)
// handle move button clicks
val moveButton = findViewById<View>(R.id.cameraMoveButton)
moveButton?.setOnClickListener { view: View? ->
val cameraPosition =
CameraPosition.Builder()
.target(nextLatLng)
.zoom(14.0)
.tilt(30.0)
.tilt(0.0)
.build()
maplibreMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
// handle ease button clicks
val easeButton = findViewById<View>(R.id.cameraEaseButton)
easeButton?.setOnClickListener { view: View? ->
val cameraPosition =
CameraPosition.Builder()
.target(nextLatLng)
.zoom(15.0)
.bearing(180.0)
.tilt(30.0)
.build()
maplibreMap.easeCamera(
CameraUpdateFactory.newCameraPosition(cameraPosition),
7500,
callback
)
}
// handle animate button clicks
val animateButton = findViewById<View>(R.id.cameraAnimateButton)
animateButton?.setOnClickListener { view: View? ->
val cameraPosition =
CameraPosition.Builder().target(nextLatLng).bearing(270.0).tilt(20.0).build()
maplibreMap.animateCamera(
CameraUpdateFactory.newCameraPosition(cameraPosition),
7500,
callback
)
}
}
private val nextLatLng: LatLng
private get() {
cameraState = !cameraState
return if (cameraState) LAT_LNG_TOWER_BRIDGE else LAT_LNG_LONDON_EYE
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
if (maplibreMap != null) {
maplibreMap.removeOnCameraIdleListener(cameraIdleListener)
}
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
companion object {
private val LAT_LNG_LONDON_EYE = LatLng(51.50325, -0.11968)
private val LAT_LNG_TOWER_BRIDGE = LatLng(51.50550, -0.07520)
}
}

View File

@@ -0,0 +1,277 @@
package org.maplibre.android.testapp.activity.camera
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.TypeEvaluator
import android.animation.ValueAnimator
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.animation.AnticipateOvershootInterpolator
import android.view.animation.BounceInterpolator
import android.view.animation.Interpolator
import androidx.appcompat.app.AppCompatActivity
import androidx.collection.LongSparseArray
import androidx.core.view.animation.PathInterpolatorCompat
import androidx.interpolator.view.animation.FastOutLinearInInterpolator
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.*
import org.maplibre.android.testapp.R
/** Test activity showcasing using Android SDK animators to animate camera position changes. */
class CameraAnimatorActivity : AppCompatActivity(), OnMapReadyCallback {
private val animators = LongSparseArray<Animator>()
private lateinit var set: Animator
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera_animator)
mapView = findViewById<View>(R.id.mapView) as MapView
if (::mapView.isInitialized) {
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
}
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
map.setStyle(Style.getPredefinedStyle("Streets"))
initFab()
}
private fun initFab() {
findViewById<View>(R.id.fab).setOnClickListener { view: View ->
view.visibility = View.GONE
val animatedPosition =
CameraPosition.Builder()
.target(LatLng(37.789992, -122.402214))
.tilt(60.0)
.zoom(14.5)
.bearing(135.0)
.build()
set = createExampleAnimator(maplibreMap.cameraPosition, animatedPosition)
set.start()
}
}
//
// Animator API used for the animation on the FAB
//
private fun createExampleAnimator(
currentPosition: CameraPosition,
targetPosition: CameraPosition
): Animator {
val animatorSet = AnimatorSet()
animatorSet.play(createLatLngAnimator(currentPosition.target!!, targetPosition.target!!))
animatorSet.play(createZoomAnimator(currentPosition.zoom, targetPosition.zoom))
animatorSet.play(createBearingAnimator(currentPosition.bearing, targetPosition.bearing))
animatorSet.play(createTiltAnimator(currentPosition.tilt, targetPosition.tilt))
return animatorSet
}
private fun createLatLngAnimator(currentPosition: LatLng, targetPosition: LatLng): Animator {
val latLngAnimator =
ValueAnimator.ofObject(LatLngEvaluator(), currentPosition, targetPosition)
latLngAnimator.duration = (1000 * ANIMATION_DELAY_FACTOR).toLong()
latLngAnimator.interpolator = FastOutSlowInInterpolator()
latLngAnimator.addUpdateListener { animation: ValueAnimator ->
maplibreMap.moveCamera(
CameraUpdateFactory.newLatLng((animation.animatedValue as LatLng))
)
}
return latLngAnimator
}
private fun createZoomAnimator(currentZoom: Double, targetZoom: Double): Animator {
val zoomAnimator = ValueAnimator.ofFloat(currentZoom.toFloat(), targetZoom.toFloat())
zoomAnimator.duration = (2200 * ANIMATION_DELAY_FACTOR).toLong()
zoomAnimator.startDelay = (600 * ANIMATION_DELAY_FACTOR).toLong()
zoomAnimator.interpolator = AnticipateOvershootInterpolator()
zoomAnimator.addUpdateListener { animation: ValueAnimator ->
maplibreMap.moveCamera(
CameraUpdateFactory.zoomTo((animation.animatedValue as Float).toDouble())
)
}
return zoomAnimator
}
private fun createBearingAnimator(currentBearing: Double, targetBearing: Double): Animator {
val bearingAnimator =
ValueAnimator.ofFloat(currentBearing.toFloat(), targetBearing.toFloat())
bearingAnimator.duration = (1000 * ANIMATION_DELAY_FACTOR).toLong()
bearingAnimator.startDelay = (1000 * ANIMATION_DELAY_FACTOR).toLong()
bearingAnimator.interpolator = FastOutLinearInInterpolator()
bearingAnimator.addUpdateListener { animation: ValueAnimator ->
maplibreMap.moveCamera(
CameraUpdateFactory.bearingTo((animation.animatedValue as Float).toDouble())
)
}
return bearingAnimator
}
private fun createTiltAnimator(currentTilt: Double, targetTilt: Double): Animator {
val tiltAnimator = ValueAnimator.ofFloat(currentTilt.toFloat(), targetTilt.toFloat())
tiltAnimator.duration = (1000 * ANIMATION_DELAY_FACTOR).toLong()
tiltAnimator.startDelay = (1500 * ANIMATION_DELAY_FACTOR).toLong()
tiltAnimator.addUpdateListener { animation: ValueAnimator ->
maplibreMap.moveCamera(
CameraUpdateFactory.tiltTo((animation.animatedValue as Float).toDouble())
)
}
return tiltAnimator
}
//
// Interpolator examples
//
private fun obtainExampleInterpolator(menuItemId: Int): Animator? {
return animators[menuItemId.toLong()]
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_animator, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (!::maplibreMap.isInitialized) {
return false
}
if (item.itemId != android.R.id.home) {
findViewById<View>(R.id.fab).visibility = View.GONE
resetCameraPosition()
playAnimation(item.itemId)
}
return super.onOptionsItemSelected(item)
}
private fun resetCameraPosition() {
maplibreMap.moveCamera(
CameraUpdateFactory.newCameraPosition(
CameraPosition.Builder()
.target(START_LAT_LNG)
.zoom(11.0)
.bearing(0.0)
.tilt(0.0)
.build()
)
)
}
private fun playAnimation(itemId: Int) {
val animator = obtainExampleInterpolator(itemId)
if (animator != null) {
animator.cancel()
animator.start()
}
}
private fun obtainExampleInterpolator(interpolator: Interpolator, duration: Long): Animator {
val zoomAnimator = ValueAnimator.ofFloat(11.0f, 16.0f)
zoomAnimator.duration = (duration * ANIMATION_DELAY_FACTOR).toLong()
zoomAnimator.interpolator = interpolator
zoomAnimator.addUpdateListener { animation: ValueAnimator ->
maplibreMap.moveCamera(
CameraUpdateFactory.zoomTo((animation.animatedValue as Float).toDouble())
)
}
return zoomAnimator
}
//
// MapView lifecycle
//
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
for (i in 0 until animators.size()) {
animators[animators.keyAt(i)]!!.cancel()
}
if (set != null) {
set.cancel()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
if (::mapView.isInitialized) {
mapView.onDestroy()
}
}
override fun onLowMemory() {
super.onLowMemory()
if (::mapView.isInitialized) {
mapView.onLowMemory()
}
}
/** Helper class to evaluate LatLng objects with a ValueAnimator */
private class LatLngEvaluator : TypeEvaluator<LatLng> {
private val latLng = LatLng()
override fun evaluate(fraction: Float, startValue: LatLng, endValue: LatLng): LatLng {
latLng.latitude = startValue.latitude + (endValue.latitude - startValue.latitude) * fraction
latLng.longitude = startValue.longitude + (endValue.longitude - startValue.longitude) * fraction
return latLng
}
}
companion object {
private const val ANIMATION_DELAY_FACTOR = 1.5
private val START_LAT_LNG = LatLng(37.787947, -122.407432)
}
init {
val accelerateDecelerateAnimatorSet = AnimatorSet()
accelerateDecelerateAnimatorSet.playTogether(
createLatLngAnimator(START_LAT_LNG, LatLng(37.826715, -122.422795)),
obtainExampleInterpolator(FastOutSlowInInterpolator(), 2500)
)
animators.put(
R.id.menu_action_accelerate_decelerate_interpolator.toLong(),
accelerateDecelerateAnimatorSet
)
val bounceAnimatorSet = AnimatorSet()
bounceAnimatorSet.playTogether(
createLatLngAnimator(START_LAT_LNG, LatLng(37.787947, -122.407432)),
obtainExampleInterpolator(BounceInterpolator(), 3750)
)
animators.put(R.id.menu_action_bounce_interpolator.toLong(), bounceAnimatorSet)
animators.put(
R.id.menu_action_anticipate_overshoot_interpolator.toLong(),
obtainExampleInterpolator(AnticipateOvershootInterpolator(), 2500)
)
animators.put(
R.id.menu_action_path_interpolator.toLong(),
obtainExampleInterpolator(
PathInterpolatorCompat.create(.22f, .68f, 0f, 1.71f),
2500
)
)
}
}

View File

@@ -0,0 +1,223 @@
package org.maplibre.android.testapp.activity.camera
import android.annotation.SuppressLint
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.constants.GeometryConstants
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapLibreMap.*
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import timber.log.Timber
/** Test activity showcasing how to listen to camera change events. */
class CameraPositionActivity : FragmentActivity(), OnMapReadyCallback, View.OnClickListener, OnMapLongClickListener {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private lateinit var fab: FloatingActionButton
private var logCameraChanges = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera_position)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
toolbar.setTitle(R.string.activity_camera_position)
toolbar.setNavigationIcon(R.drawable.ic_ab_back)
toolbar.setNavigationOnClickListener { v: View? -> finish() }
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
map.setStyle(Style.getPredefinedStyle("Satellite Hybrid")) { style: Style? ->
// add a listener to FAB
fab = findViewById(R.id.fab)
fab.setColorFilter(ContextCompat.getColor(this@CameraPositionActivity, R.color.primary))
fab.setOnClickListener(this)
toggleLogCameraChanges()
// listen to long click events to toggle logging camera changes
maplibreMap.addOnMapLongClickListener(this)
}
}
override fun onMapLongClick(point: LatLng): Boolean {
toggleLogCameraChanges()
return false
}
@SuppressLint("InflateParams")
override fun onClick(view: View) {
val context = view.context
val dialogContent = LayoutInflater.from(context).inflate(R.layout.dialog_camera_position, null)
val builder = AlertDialog.Builder(context)
builder.setTitle(R.string.dialog_camera_position)
builder.setView(onInflateDialogContent(dialogContent))
builder.setPositiveButton("Animate", DialogClickListener(maplibreMap, dialogContent))
builder.setNegativeButton("Cancel", null)
builder.setCancelable(false)
builder.show()
}
private fun toggleLogCameraChanges() {
logCameraChanges = !logCameraChanges
if (logCameraChanges) {
maplibreMap.addOnCameraIdleListener(idleListener)
maplibreMap.addOnCameraMoveCancelListener(moveCanceledListener)
maplibreMap.addOnCameraMoveListener(moveListener)
maplibreMap.addOnCameraMoveStartedListener(moveStartedListener)
} else {
maplibreMap.removeOnCameraIdleListener(idleListener)
maplibreMap.removeOnCameraMoveCancelListener(moveCanceledListener)
maplibreMap.removeOnCameraMoveListener(moveListener)
maplibreMap.removeOnCameraMoveStartedListener(moveStartedListener)
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onDestroy() {
super.onDestroy()
if (::maplibreMap.isInitialized) {
maplibreMap.removeOnMapLongClickListener(this)
}
if (::mapView.isInitialized) {
mapView.onDestroy()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
private fun onInflateDialogContent(view: View): View {
linkTextView(view, R.id.value_lat, R.id.seekbar_lat, LatLngChangeListener(), 180 + 38)
linkTextView(view, R.id.value_lon, R.id.seekbar_lon, LatLngChangeListener(), 180 - 77)
linkTextView(view, R.id.value_zoom, R.id.seekbar_zoom, ValueChangeListener(), 6)
linkTextView(view, R.id.value_bearing, R.id.seekbar_bearing, ValueChangeListener(), 90)
linkTextView(view, R.id.value_tilt, R.id.seekbar_tilt, ValueChangeListener(), 40)
return view
}
private fun linkTextView(view: View, @IdRes textViewRes: Int, @IdRes seekBarRes: Int, listener: ValueChangeListener, defaultValue: Int) {
val value = view.findViewById<View>(textViewRes) as TextView
val seekBar = view.findViewById<View>(seekBarRes) as SeekBar
listener.setLinkedValueView(value)
seekBar.setOnSeekBarChangeListener(listener)
seekBar.progress = defaultValue
}
private val idleListener = OnCameraIdleListener {
Timber.e("OnCameraIdle")
fab.setColorFilter(
ContextCompat.getColor(this@CameraPositionActivity, android.R.color.holo_green_dark)
)
}
private val moveListener = OnCameraMoveListener {
Timber.e("OnCameraMove")
fab.setColorFilter(
ContextCompat.getColor(this@CameraPositionActivity, android.R.color.holo_orange_dark)
)
}
private val moveCanceledListener = OnCameraMoveCanceledListener {
Timber.e("OnCameraMoveCanceled")
}
private val moveStartedListener: OnCameraMoveStartedListener = object : OnCameraMoveStartedListener {
private val REASONS = arrayOf("REASON_API_GESTURE", "REASON_DEVELOPER_ANIMATION", "REASON_API_ANIMATION")
override fun onCameraMoveStarted(reason: Int) {
// reason ranges from 1 <-> 3
fab.setColorFilter(
ContextCompat.getColor(this@CameraPositionActivity, android.R.color.holo_red_dark)
)
Timber.e("OnCameraMoveStarted: %s", REASONS[reason - 1])
}
}
private open inner class ValueChangeListener : OnSeekBarChangeListener {
protected var textView: TextView? = null
fun setLinkedValueView(textView: TextView?) {
this.textView = textView
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
textView!!.text = progress.toString()
}
}
private inner class LatLngChangeListener : ValueChangeListener() {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
super.onProgressChanged(seekBar, progress - 180, fromUser)
}
}
private class DialogClickListener(private val maplibreMap: MapLibreMap?, private val dialogContent: View) : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
val latitude = (dialogContent.findViewById<View>(R.id.value_lat) as TextView).text.toString().toDouble()
val longitude = (dialogContent.findViewById<View>(R.id.value_lon) as TextView).text.toString().toDouble()
val zoom = (dialogContent.findViewById<View>(R.id.value_zoom) as TextView).text.toString().toDouble()
val bearing = (dialogContent.findViewById<View>(R.id.value_bearing) as TextView).text.toString().toDouble()
val tilt = (dialogContent.findViewById<View>(R.id.value_tilt) as TextView).text.toString().toDouble()
if (latitude < GeometryConstants.MIN_LATITUDE || latitude > GeometryConstants.MAX_LATITUDE) {
Toast.makeText(dialogContent.context, "latitude value must be set between " + GeometryConstants.MIN_LATITUDE + " and " + GeometryConstants.MAX_LATITUDE, Toast.LENGTH_SHORT).show()
return
}
val cameraPosition = CameraPosition.Builder().target(LatLng(latitude, longitude)).zoom(zoom).bearing(bearing).tilt(tilt).build()
maplibreMap?.animateCamera(
CameraUpdateFactory.newCameraPosition(cameraPosition),
5000,
object : CancelableCallback {
override fun onCancel() {
Timber.v("OnCancel called")
}
override fun onFinish() {
Timber.v("OnFinish called")
}
}
)
Timber.v(cameraPosition.toString())
}
}
}

View File

@@ -0,0 +1,426 @@
package org.maplibre.android.testapp.activity.camera
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.view.*
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.IntDef
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.mapbox.android.gestures.*
import org.maplibre.android.annotations.Marker
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapLibreMap.*
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.FontCache
import org.maplibre.android.testapp.utils.ResourceUtils
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
/** Test activity showcasing APIs around gestures implementation. */
class GestureDetectorActivity : AppCompatActivity() {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private lateinit var recyclerView: RecyclerView
private var gestureAlertsAdapter: GestureAlertsAdapter? = null
private var gesturesManager: AndroidGesturesManager? = null
private var marker: Marker? = null
private var focalPointLatLng: LatLng? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_gesture_detector)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { maplibreMap: MapLibreMap ->
this@GestureDetectorActivity.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
initializeMap()
}
)
recyclerView = findViewById(R.id.alerts_recycler)
recyclerView.setLayoutManager(LinearLayoutManager(this))
gestureAlertsAdapter = GestureAlertsAdapter()
recyclerView.setAdapter(gestureAlertsAdapter)
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
gestureAlertsAdapter!!.cancelUpdates()
mapView.onPause()
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
private fun initializeMap() {
gesturesManager = maplibreMap.gesturesManager
val layoutParams = recyclerView!!.layoutParams as RelativeLayout.LayoutParams
layoutParams.height = (mapView.height / 1.75).toInt()
layoutParams.width = mapView.width / 3
recyclerView!!.layoutParams = layoutParams
attachListeners()
fixedFocalPointEnabled(maplibreMap.uiSettings.focalPoint != null)
}
fun attachListeners() {
maplibreMap.addOnMoveListener(
object : OnMoveListener {
override fun onMoveBegin(detector: MoveGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_START, "MOVE START")
)
}
override fun onMove(detector: MoveGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_PROGRESS, "MOVE PROGRESS")
)
}
override fun onMoveEnd(detector: MoveGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_END, "MOVE END")
)
recalculateFocalPoint()
}
}
)
maplibreMap.addOnRotateListener(
object : OnRotateListener {
override fun onRotateBegin(detector: RotateGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_START, "ROTATE START")
)
}
override fun onRotate(detector: RotateGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_PROGRESS, "ROTATE PROGRESS")
)
recalculateFocalPoint()
}
override fun onRotateEnd(detector: RotateGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_END, "ROTATE END")
)
}
}
)
maplibreMap.addOnScaleListener(
object : OnScaleListener {
override fun onScaleBegin(detector: StandardScaleGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_START, "SCALE START")
)
if (focalPointLatLng != null) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(
GestureAlert.TYPE_OTHER,
"INCREASING MOVE THRESHOLD"
)
)
gesturesManager!!.moveGestureDetector.moveThreshold =
ResourceUtils.convertDpToPx(this@GestureDetectorActivity, 175f)
gestureAlertsAdapter!!.addAlert(
GestureAlert(
GestureAlert.TYPE_OTHER,
"MANUALLY INTERRUPTING MOVE"
)
)
gesturesManager!!.moveGestureDetector.interrupt()
}
recalculateFocalPoint()
}
override fun onScale(detector: StandardScaleGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_PROGRESS, "SCALE PROGRESS")
)
}
override fun onScaleEnd(detector: StandardScaleGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_END, "SCALE END")
)
if (focalPointLatLng != null) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(
GestureAlert.TYPE_OTHER,
"REVERTING MOVE THRESHOLD"
)
)
gesturesManager!!.moveGestureDetector.moveThreshold = 0f
}
}
}
)
maplibreMap.addOnShoveListener(
object : OnShoveListener {
override fun onShoveBegin(detector: ShoveGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_START, "SHOVE START")
)
}
override fun onShove(detector: ShoveGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_PROGRESS, "SHOVE PROGRESS")
)
}
override fun onShoveEnd(detector: ShoveGestureDetector) {
gestureAlertsAdapter!!.addAlert(
GestureAlert(GestureAlert.TYPE_END, "SHOVE END")
)
}
}
)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_gestures, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val uiSettings = maplibreMap.uiSettings
when (item.itemId) {
R.id.menu_gesture_focus_point -> {
fixedFocalPointEnabled(focalPointLatLng == null)
return true
}
R.id.menu_gesture_animation -> {
uiSettings.isScaleVelocityAnimationEnabled =
!uiSettings.isScaleVelocityAnimationEnabled
uiSettings.isRotateVelocityAnimationEnabled =
!uiSettings.isRotateVelocityAnimationEnabled
uiSettings.isFlingVelocityAnimationEnabled =
!uiSettings.isFlingVelocityAnimationEnabled
return true
}
R.id.menu_gesture_rotate -> {
uiSettings.isRotateGesturesEnabled = !uiSettings.isRotateGesturesEnabled
return true
}
R.id.menu_gesture_tilt -> {
uiSettings.isTiltGesturesEnabled = !uiSettings.isTiltGesturesEnabled
return true
}
R.id.menu_gesture_zoom -> {
uiSettings.isZoomGesturesEnabled = !uiSettings.isZoomGesturesEnabled
return true
}
R.id.menu_gesture_scroll -> {
uiSettings.isScrollGesturesEnabled = !uiSettings.isScrollGesturesEnabled
return true
}
R.id.menu_gesture_double_tap -> {
uiSettings.isDoubleTapGesturesEnabled = !uiSettings.isDoubleTapGesturesEnabled
return true
}
R.id.menu_gesture_quick_zoom -> {
uiSettings.isQuickZoomGesturesEnabled = !uiSettings.isQuickZoomGesturesEnabled
return true
}
R.id.menu_gesture_scroll_horizontal -> {
uiSettings.isHorizontalScrollGesturesEnabled =
!uiSettings.isHorizontalScrollGesturesEnabled
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun fixedFocalPointEnabled(enabled: Boolean) {
if (enabled) {
focalPointLatLng = LatLng(51.50325, -0.12968)
marker = maplibreMap.addMarker(MarkerOptions().position(focalPointLatLng))
maplibreMap.easeCamera(
CameraUpdateFactory.newLatLngZoom(focalPointLatLng!!, 16.0),
object : CancelableCallback {
override fun onCancel() {
recalculateFocalPoint()
}
override fun onFinish() {
recalculateFocalPoint()
}
}
)
} else {
if (marker != null) {
maplibreMap.removeMarker(marker!!)
marker = null
}
focalPointLatLng = null
maplibreMap.uiSettings.focalPoint = null
}
}
private fun recalculateFocalPoint() {
if (focalPointLatLng != null) {
maplibreMap.uiSettings.focalPoint =
maplibreMap.projection.toScreenLocation(focalPointLatLng!!)
}
}
private class GestureAlertsAdapter : RecyclerView.Adapter<GestureAlertsAdapter.ViewHolder>() {
private var isUpdating = false
private val updateHandler = Handler()
private val alerts: MutableList<GestureAlert> = ArrayList()
class ViewHolder internal constructor(view: View) : RecyclerView.ViewHolder(view) {
var alertMessageTv: TextView
@ColorInt var textColor = 0
init {
val typeface = FontCache.get("Roboto-Regular.ttf", view.context)
alertMessageTv = view.findViewById(R.id.alert_message)
alertMessageTv.typeface = typeface
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =
LayoutInflater.from(parent.context)
.inflate(R.layout.item_gesture_alert, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val alert = alerts[position]
holder.alertMessageTv.text = alert.message
holder.alertMessageTv.setTextColor(
ContextCompat.getColor(holder.alertMessageTv.context, alert.color)
)
}
override fun getItemCount(): Int {
return alerts.size
}
fun addAlert(alert: GestureAlert) {
for (gestureAlert in alerts) {
if (gestureAlert.alertType != GestureAlert.TYPE_PROGRESS) {
break
}
if (alert.alertType == GestureAlert.TYPE_PROGRESS && gestureAlert == alert) {
return
}
}
if (itemCount >= MAX_NUMBER_OF_ALERTS) {
alerts.removeAt(itemCount - 1)
}
alerts.add(0, alert)
if (!isUpdating) {
isUpdating = true
updateHandler.postDelayed(updateRunnable, 250)
}
}
@SuppressLint("NotifyDataSetChanged")
private val updateRunnable = Runnable {
notifyDataSetChanged()
isUpdating = false
}
fun cancelUpdates() {
updateHandler.removeCallbacksAndMessages(null)
}
}
private class GestureAlert
internal constructor(
@field:Type @param:Type
val alertType: Int,
val message: String?
) {
@Retention(RetentionPolicy.SOURCE)
@IntDef(TYPE_NONE, TYPE_START, TYPE_PROGRESS, TYPE_END, TYPE_OTHER)
internal annotation class Type
@ColorInt var color = 0
override fun equals(o: Any?): Boolean {
if (this === o) {
return true
}
if (o == null || javaClass != o.javaClass) {
return false
}
val that = o as GestureAlert
if (alertType != that.alertType) {
return false
}
return if (message != null) message == that.message else that.message == null
}
override fun hashCode(): Int {
var result = alertType
result = 31 * result + (message?.hashCode() ?: 0)
return result
}
companion object {
const val TYPE_NONE = 0
const val TYPE_START = 1
const val TYPE_END = 2
const val TYPE_PROGRESS = 3
const val TYPE_OTHER = 4
}
init {
when (alertType) {
TYPE_NONE -> color = android.R.color.black
TYPE_END -> color = android.R.color.holo_red_dark
TYPE_OTHER -> color = android.R.color.holo_purple
TYPE_PROGRESS -> color = android.R.color.holo_orange_dark
TYPE_START -> color = android.R.color.holo_green_dark
}
}
}
companion object {
private const val MAX_NUMBER_OF_ALERTS = 30
}
}

View File

@@ -0,0 +1,178 @@
package org.maplibre.android.testapp.activity.camera
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.mapbox.geojson.FeatureCollection
import com.mapbox.geojson.FeatureCollection.fromJson
import com.mapbox.geojson.Point
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.geometry.LatLngBounds
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.style.layers.Property.ICON_ANCHOR_CENTER
import org.maplibre.android.style.layers.PropertyFactory.*
import org.maplibre.android.style.layers.SymbolLayer
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.databinding.ActivityLatlngboundsBinding
import org.maplibre.android.testapp.utils.GeoParseUtil
import org.maplibre.android.utils.BitmapUtils
import java.net.URISyntaxException
/** Test activity showcasing using the LatLngBounds camera API. */
class LatLngBoundsActivity : AppCompatActivity() {
private lateinit var maplibreMap: MapLibreMap
private lateinit var bottomSheetBehavior: BottomSheetBehavior<*>
private lateinit var bounds: LatLngBounds
private lateinit var binding: ActivityLatlngboundsBinding
private val peekHeight by lazy {
375.toPx(this) // 375dp
}
private val additionalPadding by lazy {
32.toPx(this) // 32dp
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLatlngboundsBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
initMapView(savedInstanceState)
}
private fun initMapView(savedInstanceState: Bundle?) {
binding.mapView.onCreate(savedInstanceState)
binding.mapView.getMapAsync { map ->
maplibreMap = map
val featureCollection: FeatureCollection =
fromJson(GeoParseUtil.loadStringFromAssets(this, "points-sf.geojson"))
bounds = createBounds(featureCollection)
map.getCameraForLatLngBounds(bounds, createPadding(peekHeight))?.let {
map.cameraPosition = it
}
try {
loadStyle(featureCollection)
} catch (e: URISyntaxException) {
e.printStackTrace()
}
}
}
private fun loadStyle(featureCollection: FeatureCollection) {
maplibreMap.setStyle(
Style.Builder()
.fromUri(Style.getPredefinedStyle("Streets"))
.withLayer(
SymbolLayer("symbol", "symbol")
.withProperties(
iconAllowOverlap(true),
iconIgnorePlacement(true),
iconImage("icon"),
iconAnchor(ICON_ANCHOR_CENTER)
)
)
.withSource(GeoJsonSource("symbol", featureCollection))
.withImage(
"icon",
BitmapUtils.getDrawableFromRes(
this@LatLngBoundsActivity,
R.drawable.ic_android
)!!
)
) {
initBottomSheet()
binding.fab.setOnClickListener {
bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
}
}
}
private fun initBottomSheet() {
bottomSheetBehavior = BottomSheetBehavior.from(binding.bottomSheet)
bottomSheetBehavior.setBottomSheetCallback(
object : BottomSheetBehavior.BottomSheetCallback() {
override fun onSlide(bottomSheet: View, slideOffset: Float) {
val offset = convertSlideOffset(slideOffset)
val bottomPadding = (peekHeight * offset).toInt()
maplibreMap.getCameraForLatLngBounds(bounds, createPadding(bottomPadding))
?.let { maplibreMap.cameraPosition = it }
}
override fun onStateChanged(bottomSheet: View, newState: Int) {
// no-op
}
}
)
}
// slideOffset ranges from NaN to -1.0, range from 1.0 to 0 instead
fun convertSlideOffset(slideOffset: Float): Float {
return if (slideOffset.equals(Float.NaN)) {
1.0f
} else {
1 + slideOffset
}
}
fun createPadding(bottomPadding: Int): IntArray {
return intArrayOf(additionalPadding, additionalPadding, additionalPadding, bottomPadding)
}
private fun createBounds(featureCollection: FeatureCollection): LatLngBounds {
val boundsBuilder = LatLngBounds.Builder()
featureCollection.features()?.let {
for (feature in it) {
val point = feature.geometry() as Point
boundsBuilder.include(LatLng(point.latitude(), point.longitude()))
}
}
return boundsBuilder.build()
}
override fun onStart() {
super.onStart()
binding.mapView.onStart()
}
override fun onResume() {
super.onResume()
binding.mapView.onResume()
}
override fun onPause() {
super.onPause()
binding.mapView.onPause()
}
override fun onStop() {
super.onStop()
binding.mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
binding.mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
binding.mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
binding.mapView.onSaveInstanceState(outState)
}
}
fun Int.toPx(context: Context): Int = (this * context.resources.displayMetrics.density).toInt()

View File

@@ -0,0 +1,109 @@
package org.maplibre.android.testapp.activity.camera
import android.graphics.Point
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
/**
* Test activity showcasing the zoom Camera API.
*
* This includes zoomIn, zoomOut, zoomTo, zoomBy (center and custom focal point).
*/
class ManualZoomActivity : AppCompatActivity() {
private lateinit var maplibreMap: MapLibreMap
private lateinit var mapView: MapView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_manual_zoom)
mapView = findViewById<View>(R.id.mapView) as MapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { maplibreMap: MapLibreMap ->
this@ManualZoomActivity.maplibreMap = maplibreMap
maplibreMap.setStyle(
Style.Builder().fromUri(Style.getPredefinedStyle("Satellite Hybrid"))
)
val uiSettings = this@ManualZoomActivity.maplibreMap.uiSettings
uiSettings.setAllGesturesEnabled(false)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_zoom, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_zoom_in -> {
maplibreMap.animateCamera(CameraUpdateFactory.zoomIn())
true
}
R.id.action_zoom_out -> {
maplibreMap.animateCamera(CameraUpdateFactory.zoomOut())
true
}
R.id.action_zoom_by -> {
maplibreMap.animateCamera(CameraUpdateFactory.zoomBy(2.0))
true
}
R.id.action_zoom_to -> {
maplibreMap.animateCamera(CameraUpdateFactory.zoomTo(2.0))
true
}
R.id.action_zoom_to_point -> {
val view = window.decorView
maplibreMap.animateCamera(
CameraUpdateFactory.zoomBy(
1.0,
Point(view.measuredWidth / 4, view.measuredHeight / 4)
)
)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,81 @@
package org.maplibre.android.testapp.activity.camera
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapView.OnDidFinishLoadingStyleListener
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapLibreMap.OnMapClickListener
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import timber.log.Timber
/** Test activity showcasing using maximum and minimum zoom levels to restrict camera movement. */
class MaxMinZoomActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private val clickListener = OnMapClickListener {
if (maplibreMap != null) {
maplibreMap.setStyle(Style.Builder().fromUri(Style.getPredefinedStyle("Outdoor")))
}
true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maxmin_zoom)
mapView = findViewById<MapView>(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
mapView.addOnDidFinishLoadingStyleListener(
OnDidFinishLoadingStyleListener { Timber.d("Style Loaded") }
)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
maplibreMap.setMinZoomPreference(3.0)
maplibreMap.setMaxZoomPreference(5.0)
maplibreMap.addOnMapClickListener(clickListener)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
if (maplibreMap != null) {
maplibreMap.removeOnMapClickListener(clickListener)
}
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,133 @@
package org.maplibre.android.testapp.activity.camera
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
/**
* Test activity showcasing using the scrollBy Camera API by moving x,y pixels above Grenada, Spain.
*/
class ScrollByActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private lateinit var seekBarX: SeekBar
private lateinit var seekBarY: SeekBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scroll_by)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setDisplayShowHomeEnabled(true)
}
seekBarX = findViewById(R.id.seekbar_move_x)
val textViewX = findViewById<TextView>(R.id.textview_x)
seekBarX.setOnSeekBarChangeListener(
PixelBarChangeListener(textViewX, R.string.scrollby_x_value)
)
seekBarY = findViewById(R.id.seekbar_move_y)
val textViewY = findViewById<TextView>(R.id.textview_y)
seekBarY.setOnSeekBarChangeListener(
PixelBarChangeListener(textViewY, R.string.scrollby_y_value)
)
mapView = findViewById(R.id.mapView)
mapView.setTag(true)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
maplibreMap.setStyle(Style.getPredefinedStyle("Pastel"))
val uiSettings = maplibreMap.uiSettings
uiSettings.isLogoEnabled = false
uiSettings.isAttributionEnabled = false
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setColorFilter(ContextCompat.getColor(this@ScrollByActivity, R.color.primary))
fab.setOnClickListener { view: View? ->
maplibreMap.scrollBy(
(seekBarX!!.progress * MULTIPLIER_PER_PIXEL).toFloat(),
(seekBarY!!.progress * MULTIPLIER_PER_PIXEL).toFloat()
)
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private class PixelBarChangeListener
internal constructor(
private val valueView: TextView,
@field:StringRes @param:StringRes
private val prefixTextResource: Int
) : OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
val value = progress * MULTIPLIER_PER_PIXEL
valueView.text = String.format(seekBar.resources.getString(prefixTextResource), value)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
}
companion object {
const val MULTIPLIER_PER_PIXEL = 50
}
}

View File

@@ -0,0 +1,146 @@
package org.maplibre.android.testapp.activity.customlayer
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.style.layers.CustomLayer
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.model.customlayer.ExampleCustomLayer
/**
* Test activity showcasing the Custom Layer API
*
*
* Note: experimental API, do not use.
*
*/
class CustomLayerActivity : AppCompatActivity() {
private lateinit var maplibreMap: MapLibreMap
private lateinit var mapView: MapView
private var customLayer: CustomLayer? = null
private lateinit var fab: FloatingActionButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_custom_layer)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { map: MapLibreMap? ->
maplibreMap = map!!
maplibreMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(39.91448, -243.60947),
10.0
)
)
maplibreMap.setStyle(Style.getPredefinedStyle("Streets")) { style: Style? -> initFab() }
}
)
}
private fun initFab() {
fab = findViewById(R.id.fab)
fab.setColorFilter(ContextCompat.getColor(this, R.color.primary))
fab.setOnClickListener(
View.OnClickListener { view: View? ->
if (maplibreMap != null) {
swapCustomLayer()
}
}
)
}
private fun swapCustomLayer() {
val style = maplibreMap.style
if (customLayer != null) {
style!!.removeLayer(customLayer!!)
customLayer = null
fab!!.setImageResource(R.drawable.ic_layers)
} else {
customLayer = CustomLayer(
"custom",
ExampleCustomLayer.createContext()
)
style!!.addLayerBelow(customLayer!!, "building")
fab!!.setImageResource(R.drawable.ic_layers_clear)
}
}
private fun updateLayer() {
if (maplibreMap != null) {
maplibreMap.triggerRepaint()
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_custom_layer, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_update_layer -> {
updateLayer()
true
}
R.id.action_set_color_red -> {
ExampleCustomLayer.setColor(1f, 0f, 0f, 1f)
true
}
R.id.action_set_color_green -> {
ExampleCustomLayer.setColor(0f, 1f, 0f, 1f)
true
}
R.id.action_set_color_blue -> {
ExampleCustomLayer.setColor(0f, 0f, 1f, 1f)
true
}
else -> super.onOptionsItemSelected(item)
}
}
}

View File

@@ -0,0 +1,65 @@
package org.maplibre.android.testapp.activity.espresso
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
class DeviceIndependentTestActivity : AppCompatActivity(), OnMapReadyCallback {
lateinit var mapView: MapView
lateinit var maplibreMap: MapLibreMap
protected set
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera_test)
// Initialize map as normal
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
}
public override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
public override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,56 @@
package org.maplibre.android.testapp.activity.espresso
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.testapp.R
/**
* Base activity for instrumentation testing.
*/
class EspressoTestActivity : AppCompatActivity() {
lateinit var mapView: MapView
protected lateinit var maplibreMap: MapLibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_espresso_test)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
}
public override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
public override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,66 @@
package org.maplibre.android.testapp.activity.espresso
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
/**
* Test activity used for instrumentation tests that require a specific device size.
*/
class PixelTestActivity : AppCompatActivity(), OnMapReadyCallback {
lateinit var mapView: MapView
lateinit var maplibreMap: MapLibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pixel_test)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
}
public override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
public override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,146 @@
package org.maplibre.android.testapp.activity.feature
import android.graphics.PointF
import android.graphics.RectF
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.mapbox.geojson.Feature
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.NavUtils
import timber.log.Timber
/**
* Test activity showcasing using the query rendered features API to count features in a rectangle.
*/
class QueryRenderedFeaturesBoxCountActivity : AppCompatActivity() {
lateinit var mapView: MapView
lateinit var maplibreMap: MapLibreMap
private set
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_query_features_box)
val selectionBox = findViewById<View>(R.id.selection_box)
// Initialize map as normal
mapView = findViewById<View>(R.id.mapView) as MapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { maplibreMap: MapLibreMap ->
this@QueryRenderedFeaturesBoxCountActivity.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.Builder().fromUri(Style.getPredefinedStyle("Streets")))
selectionBox.setOnClickListener { view: View? ->
// Query
val top = selectionBox.top - mapView.top
val left = selectionBox.left - mapView.left
val box = RectF(
left.toFloat(),
top.toFloat(),
(left + selectionBox.width).toFloat(),
(top + selectionBox.height).toFloat()
)
Timber.i("Querying box %s", box)
val features = maplibreMap.queryRenderedFeatures(box)
// Show count
Toast.makeText(
this@QueryRenderedFeaturesBoxCountActivity,
String.format("%s features in box", features.size),
Toast.LENGTH_SHORT
).show()
// Debug output
debugOutput(features)
}
}
}
private fun debugOutput(features: List<Feature>) {
Timber.i("Got %s features", features.size)
for (feature in features) {
Timber.i(
"Got feature %s with %s properties and Geometry %s",
feature.id(),
if (feature.properties() != null) {
feature.properties()!!
.entrySet().size
} else {
"<null>"
},
if (feature.geometry() != null) {
feature.geometry()!!::class.java.simpleName
} else {
"<null>"
}
)
if (feature.properties() != null) {
for ((key, value) in feature.properties()!!.entrySet()) {
Timber.i("Prop %s - %s", key, value)
}
}
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
if (::maplibreMap.isInitialized) {
// Regression test for #14394
maplibreMap.queryRenderedFeatures(PointF(0F, 0F))
}
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
NavUtils.navigateHome(this)
}
}

View File

@@ -0,0 +1,114 @@
package org.maplibre.android.testapp.activity.feature
import android.graphics.Color
import android.graphics.RectF
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.mapbox.geojson.FeatureCollection
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.style.expressions.Expression
import org.maplibre.android.style.layers.FillLayer
import org.maplibre.android.style.layers.Layer
import org.maplibre.android.style.layers.PropertyFactory
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.testapp.R
import timber.log.Timber
/**
* Demo's query rendered features
*/
class QueryRenderedFeaturesBoxHighlightActivity : AppCompatActivity() {
lateinit var mapView: MapView
lateinit var maplibreMap: MapLibreMap
private set
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_query_features_box)
val selectionBox = findViewById<View>(R.id.selection_box)
// Initialize map as normal
mapView = findViewById<View>(R.id.mapView) as MapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { maplibreMap: MapLibreMap ->
this@QueryRenderedFeaturesBoxHighlightActivity.maplibreMap = maplibreMap
// Add layer / source
val source = GeoJsonSource("highlighted-shapes-source")
val layer: Layer = FillLayer("highlighted-shapes-layer", "highlighted-shapes-source")
.withProperties(PropertyFactory.fillColor(Color.RED))
selectionBox.setOnClickListener { view: View? ->
// Query
val top = selectionBox.top - mapView.top
val left = selectionBox.left - mapView.left
val box = RectF(
left.toFloat(),
top.toFloat(),
(left + selectionBox.width).toFloat(),
(top + selectionBox.height).toFloat()
)
Timber.i("Querying box %s for buildings", box)
val filter = Expression.lt(
Expression.toNumber(Expression.get("height")),
Expression.literal(10)
)
val features = maplibreMap.queryRenderedFeatures(box, filter, "building")
// Show count
Toast.makeText(
this@QueryRenderedFeaturesBoxHighlightActivity,
String.format("%s features in box", features.size),
Toast.LENGTH_SHORT
).show()
// Update source data
source.setGeoJson(FeatureCollection.fromFeatures(features))
}
maplibreMap.setStyle(
Style.Builder()
.fromUri(Style.getPredefinedStyle("Streets"))
.withSource(source)
.withLayer(layer)
)
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,130 @@
package org.maplibre.android.testapp.activity.feature
import android.graphics.BitmapFactory
import android.graphics.RectF
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.style.expressions.Expression
import org.maplibre.android.style.layers.BackgroundLayer
import org.maplibre.android.style.layers.PropertyFactory
import org.maplibre.android.style.layers.SymbolLayer
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.ResourceUtils
import timber.log.Timber
import java.io.IOException
/**
* Test activity showcasing using the query rendered features API to count Symbols in a rectangle.
*/
class QueryRenderedFeaturesBoxSymbolCountActivity : AppCompatActivity() {
lateinit var mapView: MapView
lateinit var maplibreMap: MapLibreMap
private set
private lateinit var toast: Toast
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_query_features_box)
val selectionBox = findViewById<View>(R.id.selection_box)
// Initialize map as normal
mapView = findViewById<View>(R.id.mapView) as MapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { maplibreMap: MapLibreMap ->
this@QueryRenderedFeaturesBoxSymbolCountActivity.maplibreMap = maplibreMap
try {
val testPoints = ResourceUtils.readRawResource(
mapView.context,
R.raw.test_points_utrecht
)
val markerImage =
BitmapFactory.decodeResource(resources, R.drawable.maplibre_marker_icon_default)
maplibreMap.setStyle(
Style.Builder()
.withLayer(
BackgroundLayer("bg")
.withProperties(
PropertyFactory.backgroundColor(Expression.rgb(120, 161, 226))
)
)
.withLayer(
SymbolLayer("symbols-layer", "symbols-source")
.withProperties(
PropertyFactory.iconImage("test-icon")
)
)
.withSource(
GeoJsonSource("symbols-source", testPoints)
)
.withImage("test-icon", markerImage)
)
} catch (exception: IOException) {
exception.printStackTrace()
}
selectionBox.setOnClickListener { view: View? ->
// Query
val top = selectionBox.top - mapView.top
val left = selectionBox.left - mapView.left
val box = RectF(
left.toFloat(),
top.toFloat(),
(left + selectionBox.width).toFloat(),
(top + selectionBox.height).toFloat()
)
Timber.i("Querying box %s", box)
val features = maplibreMap.queryRenderedFeatures(box, "symbols-layer")
// Show count
if (toast != null) {
toast!!.cancel()
}
toast = Toast.makeText(
this@QueryRenderedFeaturesBoxSymbolCountActivity,
String.format("%s features in box", features.size),
Toast.LENGTH_SHORT
)
toast.show()
}
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,221 @@
package org.maplibre.android.testapp.activity.feature
import android.graphics.Color
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.mapbox.geojson.Feature
import org.maplibre.android.annotations.BaseMarkerOptions
import org.maplibre.android.annotations.Marker
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapLibreMap.InfoWindowAdapter
import org.maplibre.android.maps.MapLibreMap.OnMapClickListener
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import timber.log.Timber
/**
* Test activity showcasing using the query rendered features API to query feature properties on Map click.
*/
class QueryRenderedFeaturesPropertiesActivity : AppCompatActivity() {
lateinit var mapView: MapView
lateinit var maplibreMap: MapLibreMap
private set
private var marker: Marker? = null
private val mapClickListener = OnMapClickListener { point ->
val density = resources.displayMetrics.density
val pixel = maplibreMap.projection.toScreenLocation(point)
Timber.i(
"Requesting features for %sx%s (%sx%s adjusted for density)",
pixel.x,
pixel.y,
pixel.x / density,
pixel.y / density
)
val features = maplibreMap.queryRenderedFeatures(pixel)
// Debug output
debugOutput(features)
// Remove any previous markers
if (marker != null) {
maplibreMap.removeMarker(marker!!)
}
// Add a marker on the clicked point
marker = maplibreMap.addMarker(CustomMarkerOptions().position(point)!!.features(features))
maplibreMap.selectMarker(marker!!)
true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_query_features_point)
// Initialize map as normal
mapView = findViewById<View>(R.id.mapView) as MapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { maplibreMap: MapLibreMap ->
maplibreMap.setStyle(Style.getPredefinedStyle("Streets")) { style: Style? ->
this@QueryRenderedFeaturesPropertiesActivity.maplibreMap = maplibreMap
// Add custom window adapter
addCustomInfoWindowAdapter(maplibreMap)
// Add a click listener
maplibreMap.addOnMapClickListener(mapClickListener)
}
}
}
private fun debugOutput(features: List<Feature>) {
Timber.i("Got %s features", features.size)
for (feature in features) {
Timber.i(
"Got feature %s with %s properties and Geometry %s",
feature.id(),
if (feature.properties() != null) {
feature.properties()!!
.entrySet().size
} else {
"<null>"
},
if (feature.geometry() != null) {
feature.geometry()!!::class.java.simpleName
} else {
"<null>"
}
)
if (feature.properties() != null) {
for ((key, value) in feature.properties()!!.entrySet()) {
Timber.i("Prop %s - %s", key, value)
}
}
}
}
private fun addCustomInfoWindowAdapter(maplibreMap: MapLibreMap) {
maplibreMap.infoWindowAdapter = object : InfoWindowAdapter {
private fun row(text: String): TextView {
val view = TextView(this@QueryRenderedFeaturesPropertiesActivity)
view.text = text
return view
}
override fun getInfoWindow(marker: Marker): View? {
val customMarker = marker as CustomMarker
val view = LinearLayout(this@QueryRenderedFeaturesPropertiesActivity)
view.orientation = LinearLayout.VERTICAL
view.setBackgroundColor(Color.WHITE)
if (customMarker.features!!.size > 0) {
view.addView(
row(
String.format(
"Found %s features",
customMarker.features.size
)
)
)
val feature = customMarker.features[0]
for ((key, value) in feature.properties()!!.entrySet()) {
view.addView(row(String.format("%s: %s", key, value)))
}
} else {
view.addView(row("No features here"))
}
return view
}
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
if (maplibreMap != null) {
maplibreMap.removeOnMapClickListener(mapClickListener)
}
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
private class CustomMarker internal constructor(
baseMarkerOptions: BaseMarkerOptions<*, *>?,
val features: List<Feature>?
) : Marker(baseMarkerOptions)
private class CustomMarkerOptions : BaseMarkerOptions<CustomMarker?, CustomMarkerOptions?> {
private var features: List<Feature>? = null
fun features(features: List<Feature>?): CustomMarkerOptions {
this.features = features
return this
}
internal constructor() {}
private constructor(`in`: Parcel) {
// Should implement this
}
override fun getThis(): CustomMarkerOptions {
return this
}
override fun getMarker(): CustomMarker {
return CustomMarker(this, features)
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(out: Parcel, flags: Int) {
// Should implement this
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<CustomMarkerOptions?> =
object : Parcelable.Creator<CustomMarkerOptions?> {
override fun createFromParcel(`in`: Parcel): CustomMarkerOptions? {
return CustomMarkerOptions(`in`)
}
override fun newArray(size: Int): Array<CustomMarkerOptions?> {
return arrayOfNulls(size)
}
}
}
}
}

View File

@@ -0,0 +1,132 @@
package org.maplibre.android.testapp.activity.feature
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.gson.JsonObject
import com.mapbox.geojson.Feature
import com.mapbox.geojson.FeatureCollection
import com.mapbox.geojson.Point
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.style.expressions.Expression
import org.maplibre.android.style.layers.CircleLayer
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.testapp.R
/**
* Test activity showcasing using the query source features API to query feature counts
*/
class QuerySourceFeaturesActivity : AppCompatActivity() {
lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_query_source_features)
// Initialize map as normal
mapView = findViewById<View>(R.id.mapView) as MapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { map: MapLibreMap? ->
if (map != null) {
maplibreMap = map
}
maplibreMap.getStyle { style: Style -> initStyle(style) }
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
}
}
private fun initStyle(style: Style) {
val properties = JsonObject()
properties.addProperty("key1", "value1")
val source = GeoJsonSource(
"test-source",
FeatureCollection.fromFeatures(
arrayOf(
Feature.fromGeometry(Point.fromLngLat(17.1, 51.0), properties),
Feature.fromGeometry(Point.fromLngLat(17.2, 51.0), properties),
Feature.fromGeometry(Point.fromLngLat(17.3, 51.0), properties),
Feature.fromGeometry(Point.fromLngLat(17.4, 51.0), properties)
)
)
)
style.addSource(source)
val visible = Expression.eq(Expression.get("key1"), Expression.literal("value1"))
val invisible = Expression.neq(Expression.get("key1"), Expression.literal("value1"))
val layer = CircleLayer("test-layer", source.id)
.withFilter(visible)
style.addLayer(layer)
// Add a click listener
maplibreMap.addOnMapClickListener { point: LatLng? ->
// Query
val features = source.querySourceFeatures(
Expression.eq(
Expression.get("key1"),
Expression.literal("value1")
)
)
Toast.makeText(
this@QuerySourceFeaturesActivity,
String.format(
"Found %s features",
features.size
),
Toast.LENGTH_SHORT
).show()
false
}
val fab = findViewById<View>(R.id.fab) as FloatingActionButton
fab.setColorFilter(ContextCompat.getColor(this, R.color.primary))
fab.setOnClickListener { view: View? ->
val visibility = layer.filter
if (visibility != null && visibility == visible) {
layer.setFilter(invisible)
fab.setImageResource(R.drawable.ic_layers_clear)
} else {
layer.setFilter(visible)
fab.setImageResource(R.drawable.ic_layers)
}
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,69 @@
package org.maplibre.android.testapp.activity.fragment
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.maps.SupportMapFragment
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.databinding.ActivityBackstackFragmentBinding
import org.maplibre.android.testapp.utils.NavUtils
/**
* Test activity showcasing using the MapFragment API as part of a backstacked fragment.
*/
class FragmentBackStackActivity : AppCompatActivity() {
companion object {
private const val FRAGMENT_TAG = "map_fragment"
}
private lateinit var binding: ActivityBackstackFragmentBinding
private lateinit var mapFragment: SupportMapFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBackstackFragmentBinding.inflate(layoutInflater)
setContentView(binding.root)
if (savedInstanceState == null) {
mapFragment = SupportMapFragment.newInstance()
mapFragment.getMapAsync { initMap(it) }
supportFragmentManager.beginTransaction().apply {
add(R.id.container, mapFragment, FRAGMENT_TAG)
}.commit()
} else {
supportFragmentManager.findFragmentByTag(FRAGMENT_TAG)?.also { fragment ->
if (fragment is SupportMapFragment) {
fragment.getMapAsync { initMap(it) }
}
}
}
binding.button.setOnClickListener { handleClick() }
}
private fun initMap(maplibreMap: MapLibreMap) {
maplibreMap.setStyle(Style.getPredefinedStyle("Satellite Hybrid")) {
maplibreMap.setPadding(300, 300, 300, 300)
}
}
private fun handleClick() {
supportFragmentManager.beginTransaction().apply {
replace(R.id.container, NestedViewPagerActivity.ItemAdapter.EmptyFragment())
addToBackStack("map_empty_fragment")
}.commit()
}
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount == 0) {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
NavUtils.navigateHome(this)
} else {
super.onBackPressed()
}
}
}

View File

@@ -0,0 +1,93 @@
package org.maplibre.android.testapp.activity.fragment
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.* // ktlint-disable no-wildcard-imports
import org.maplibre.android.maps.MapFragment.OnMapViewReadyCallback
import org.maplibre.android.maps.MapView.OnDidFinishRenderingFrameListener
import org.maplibre.android.testapp.R
/**
* Test activity showcasing using the MapFragment API using SDK Fragments.
*
*
* Uses MapboxMapOptions to initialise the Fragment.
*
*/
class MapFragmentActivity :
AppCompatActivity(),
OnMapViewReadyCallback,
OnMapReadyCallback,
OnDidFinishRenderingFrameListener {
private lateinit var maplibreMap: MapLibreMap
private lateinit var mapView: MapView
private var initialCameraAnimation = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_fragment)
val mapFragment: MapFragment
if (savedInstanceState == null) {
mapFragment = MapFragment.newInstance(createFragmentOptions())
fragmentManager
.beginTransaction()
.add(R.id.fragment_container, mapFragment, TAG)
.commit()
} else {
mapFragment = fragmentManager.findFragmentByTag(TAG) as MapFragment
}
mapFragment.getMapAsync(this)
}
private fun createFragmentOptions(): MapLibreMapOptions {
val options = MapLibreMapOptions.createFromAttributes(this, null)
options.scrollGesturesEnabled(false)
options.zoomGesturesEnabled(false)
options.tiltGesturesEnabled(false)
options.rotateGesturesEnabled(false)
options.debugActive(false)
val dc = LatLng(38.90252, -77.02291)
options.minZoomPreference(9.0)
options.maxZoomPreference(11.0)
options.camera(
CameraPosition.Builder()
.target(dc)
.zoom(11.0)
.build()
)
return options
}
override fun onMapViewReady(map: MapView) {
mapView = map
mapView.addOnDidFinishRenderingFrameListener(this)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
maplibreMap.setStyle(Style.getPredefinedStyle("Outdoor"))
}
override fun onDestroy() {
super.onDestroy()
if (mapView != null) {
mapView.removeOnDidFinishRenderingFrameListener(this)
}
}
override fun onDidFinishRenderingFrame(fully: Boolean, frameEncodingTime: Double, frameRenderingTime: Double) {
if (initialCameraAnimation && fully && maplibreMap != null) {
maplibreMap.animateCamera(
CameraUpdateFactory.newCameraPosition(CameraPosition.Builder().tilt(45.0).build()),
5000
)
initialCameraAnimation = false
}
}
companion object {
private const val TAG = "com.mapbox.map"
}
}

View File

@@ -0,0 +1,34 @@
package org.maplibre.android.testapp.activity.fragment
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.maps.SupportMapFragment
import org.maplibre.android.testapp.R
/**
* Test Activity showcasing using multiple static map fragments in one layout.
*/
class MultiMapActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_multi_map)
val fragmentManager = supportFragmentManager
initFragmentStyle(fragmentManager, R.id.map1, Style.getPredefinedStyle("Streets"))
initFragmentStyle(fragmentManager, R.id.map2, Style.getPredefinedStyle("Bright"))
initFragmentStyle(fragmentManager, R.id.map3, Style.getPredefinedStyle("Satellite Hybrid"))
initFragmentStyle(fragmentManager, R.id.map4, Style.getPredefinedStyle("Pastel"))
}
private fun initFragmentStyle(
fragmentManager: FragmentManager,
fragmentId: Int,
styleId: String
) {
(fragmentManager.findFragmentById(fragmentId) as SupportMapFragment?)
?.getMapAsync(OnMapReadyCallback { maplibreMap: MapLibreMap -> maplibreMap.setStyle(styleId) })
}
}

View File

@@ -0,0 +1,161 @@
package org.maplibre.android.testapp.activity.fragment
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapLibreMapOptions
import org.maplibre.android.maps.Style
import org.maplibre.android.maps.SupportMapFragment
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.databinding.ActivityRecyclerviewBinding
/**
* TestActivity showcasing how to integrate a MapView in a RecyclerView.
* <p>
* It requires calling the correct lifecycle methods when detaching and attaching the View to
* the RecyclerView with onViewAttachedToWindow and onViewDetachedFromWindow.
* </p>
*/
@SuppressLint("ClickableViewAccessibility")
class NestedViewPagerActivity : AppCompatActivity() {
private lateinit var binding: ActivityRecyclerviewBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRecyclerviewBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
binding.recyclerView.adapter = ItemAdapter(this, LayoutInflater.from(this), supportFragmentManager)
}
class ItemAdapter(private val context: Context, private val inflater: LayoutInflater, private val fragmentManager: androidx.fragment.app.FragmentManager) : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {
private val items = listOf(
"one", "two", "three", ViewPagerItem(), "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen", "twenty", "twenty-one"
)
private var mapHolder: ViewPagerHolder? = null
companion object {
const val TYPE_VIEWPAGER = 0
const val TYPE_TEXT = 1
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
return if (viewType == TYPE_VIEWPAGER) {
val viewPager = inflater.inflate(R.layout.item_viewpager, parent, false) as androidx.viewpager.widget.ViewPager
mapHolder = ViewPagerHolder(context, viewPager, fragmentManager)
return mapHolder as ViewPagerHolder
} else {
TextHolder(inflater.inflate(android.R.layout.simple_list_item_1, parent, false) as TextView)
}
}
override fun getItemCount(): Int {
return items.count()
}
override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
if (holder.itemViewType == TYPE_TEXT) {
val textHolder = holder as TextHolder
textHolder.bind(items[position] as String)
}
}
override fun getItemViewType(position: Int): Int {
return if (items[position] is ViewPagerItem) {
TYPE_VIEWPAGER
} else {
TYPE_TEXT
}
}
class TextHolder(val textView: TextView) : androidx.recyclerview.widget.RecyclerView.ViewHolder(textView) {
fun bind(item: String) {
textView.text = item
}
}
class ViewPagerItem
class ViewPagerHolder(context: Context, private val viewPager: androidx.viewpager.widget.ViewPager, fragmentManager: androidx.fragment.app.FragmentManager) : androidx.recyclerview.widget.RecyclerView.ViewHolder(viewPager) {
init {
viewPager.adapter = MapPagerAdapter(context, fragmentManager)
viewPager.setOnTouchListener { view, motionEvent ->
// Disallow the touch request for recyclerView scroll
view.parent.requestDisallowInterceptTouchEvent(true)
viewPager.onTouchEvent(motionEvent)
false
}
}
}
class MapPagerAdapter(private val context: Context, fm: androidx.fragment.app.FragmentManager) : androidx.fragment.app.FragmentStatePagerAdapter(fm) {
override fun getItem(position: Int): androidx.fragment.app.Fragment {
val options = MapLibreMapOptions.createFromAttributes(context)
options.textureMode(true)
options.doubleTapGesturesEnabled(false)
options.rotateGesturesEnabled(false)
options.tiltGesturesEnabled(false)
options.scrollGesturesEnabled(false)
options.zoomGesturesEnabled(false)
when (position) {
0 -> {
options.camera(CameraPosition.Builder().target(LatLng(34.920526, 102.634774)).zoom(3.0).build())
val fragment = SupportMapFragment.newInstance(options)
fragment.getMapAsync { mapboxMap -> mapboxMap.setStyle(Style.getPredefinedStyle("Streets")) }
return fragment
}
1 -> {
return EmptyFragment.newInstance()
}
2 -> {
options.camera(CameraPosition.Builder().target(LatLng(62.326440, 92.764913)).zoom(3.0).build())
val fragment = SupportMapFragment.newInstance(options)
fragment.getMapAsync { mapboxMap -> mapboxMap.setStyle(Style.getPredefinedStyle("Pastel")) }
return fragment
}
3 -> {
return EmptyFragment.newInstance()
}
4 -> {
options.camera(CameraPosition.Builder().target(LatLng(-25.007786, 133.623852)).zoom(3.0).build())
val fragment = SupportMapFragment.newInstance(options)
fragment.getMapAsync { mapboxMap -> mapboxMap.setStyle(Style.getPredefinedStyle("Satellite Hybrid")) }
return fragment
}
5 -> {
return EmptyFragment.newInstance()
}
}
throw IllegalAccessError()
}
override fun getCount(): Int {
return 6
}
}
class EmptyFragment : androidx.fragment.app.Fragment() {
companion object {
fun newInstance(): EmptyFragment {
return EmptyFragment()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return TextView(inflater.context)
}
}
}
}

View File

@@ -0,0 +1,91 @@
package org.maplibre.android.testapp.activity.fragment
import android.os.Bundle // ktlint-disable import-ordering
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.* // ktlint-disable no-wildcard-imports
import org.maplibre.android.maps.MapFragment.OnMapViewReadyCallback
import org.maplibre.android.maps.MapView.OnDidFinishRenderingFrameListener
import org.maplibre.android.testapp.R
/**
* Test activity showcasing using the MapFragment API using Support Library Fragments.
*
*
* Uses MapboxMapOptions to initialise the Fragment.
*
*/
class SupportMapFragmentActivity :
AppCompatActivity(),
OnMapViewReadyCallback,
OnMapReadyCallback,
OnDidFinishRenderingFrameListener {
private lateinit var maplibreMap: MapLibreMap
private lateinit var mapView: MapView
private var initialCameraAnimation = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_fragment)
val mapFragment: SupportMapFragment?
if (savedInstanceState == null) {
mapFragment = SupportMapFragment.newInstance(createFragmentOptions())
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, mapFragment, TAG)
.commit()
} else {
mapFragment = supportFragmentManager.findFragmentByTag(TAG) as SupportMapFragment?
}
mapFragment!!.getMapAsync(this)
}
private fun createFragmentOptions(): MapLibreMapOptions {
val options = MapLibreMapOptions.createFromAttributes(this, null)
options.scrollGesturesEnabled(false)
options.zoomGesturesEnabled(false)
options.tiltGesturesEnabled(false)
options.rotateGesturesEnabled(false)
options.debugActive(false)
val dc = LatLng(38.90252, -77.02291)
options.minZoomPreference(9.0)
options.maxZoomPreference(11.0)
options.camera(
CameraPosition.Builder()
.target(dc)
.zoom(11.0)
.build()
)
return options
}
override fun onMapViewReady(map: MapView) {
mapView = map
mapView.addOnDidFinishRenderingFrameListener(this)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
maplibreMap.setStyle(Style.getPredefinedStyle("Satellite Hybrid"))
}
override fun onDestroy() {
super.onDestroy()
mapView.removeOnDidFinishRenderingFrameListener(this)
}
override fun onDidFinishRenderingFrame(fully: Boolean, frameEncodingTime: Double, frameRenderingTime: Double) {
if (initialCameraAnimation && fully && maplibreMap != null) {
maplibreMap.animateCamera(
CameraUpdateFactory.newCameraPosition(CameraPosition.Builder().tilt(45.0).build()),
5000
)
initialCameraAnimation = false
}
}
companion object {
private const val TAG = "com.mapbox.map"
}
}

View File

@@ -0,0 +1,102 @@
package org.maplibre.android.testapp.activity.fragment
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapLibreMapOptions
import org.maplibre.android.maps.Style
import org.maplibre.android.maps.SupportMapFragment
import org.maplibre.android.testapp.databinding.ActivityViewpagerBinding
/**
* Test activity showcasing using the Android SDK ViewPager API to show MapFragments.
*/
class ViewPagerActivity : AppCompatActivity() {
private lateinit var binding: ActivityViewpagerBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityViewpagerBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.viewPager.adapter = MapFragmentAdapter(this, supportFragmentManager)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
val currentPosition = binding.viewPager.currentItem
val offscreenLimit = binding.viewPager.offscreenPageLimit
for (i in currentPosition - offscreenLimit..currentPosition + offscreenLimit) {
if (i < 0 || i > binding.viewPager.adapter?.count ?: 0) {
continue
}
val mapFragment =
binding.viewPager.adapter?.instantiateItem(binding.viewPager, i) as SupportMapFragment
mapFragment.getMapAsync(i)
}
}
internal class MapFragmentAdapter(private val context: Context, fragmentManager: androidx.fragment.app.FragmentManager) : androidx.fragment.app.FragmentStatePagerAdapter(fragmentManager) {
override fun getCount(): Int {
return NUM_ITEMS
}
override fun getItem(position: Int): androidx.fragment.app.Fragment {
val options = MapLibreMapOptions.createFromAttributes(context)
options.textureMode(true)
options.camera(
CameraPosition.Builder()
.zoom(3.0)
.target(
when (position) {
0 -> {
LatLng(34.920526, 102.634774)
}
1 -> {
LatLng(62.326440, 92.764913)
}
2 -> {
LatLng(-25.007786, 133.623852)
}
3 -> {
LatLng(62.326440, 92.764913)
}
else -> {
LatLng(34.920526, 102.634774)
}
}
)
.build()
)
val fragment = SupportMapFragment.newInstance(options)
fragment.getMapAsync(position)
return fragment
}
override fun getPageTitle(position: Int): CharSequence? {
return "Page $position"
}
companion object {
private const val NUM_ITEMS = 5
}
}
}
fun SupportMapFragment.getMapAsync(index: Int) {
this.getMapAsync {
it.setStyle(
when (index) {
0 -> Style.getPredefinedStyle("Streets")
1 -> Style.getPredefinedStyle("Pastel")
2 -> Style.getPredefinedStyle("Satellite Hybrid")
3 -> Style.getPredefinedStyle("Bright")
else -> Style.getPredefinedStyle("Streets")
}
)
}
}

View File

@@ -0,0 +1,79 @@
package org.maplibre.android.testapp.activity.imagegenerator
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.print.PrintHelper
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
/**
* Test activity showcasing using the Snaphot API to print a Map.
*/
class PrintActivity : AppCompatActivity(), MapLibreMap.SnapshotReadyCallback {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_print)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(OnMapReadyCallback { maplibreMap: MapLibreMap -> initMap(maplibreMap) })
val fab = findViewById<View>(R.id.fab)
fab?.setOnClickListener { view: View? ->
if (maplibreMap != null && maplibreMap.style != null) {
maplibreMap.snapshot(this@PrintActivity)
}
}
}
private fun initMap(maplibreMap: MapLibreMap) {
this.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
}
override fun onSnapshotReady(snapshot: Bitmap) {
val photoPrinter = PrintHelper(this)
photoPrinter.scaleMode = PrintHelper.SCALE_MODE_FIT
photoPrinter.printBitmap("map.jpg - mapbox print job", snapshot)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,91 @@
package org.maplibre.android.testapp.activity.imagegenerator
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.log.Logger
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.databinding.ActivitySnapshotBinding
import timber.log.Timber
/**
* Test activity showcasing the Snapshot API to create and display a bitmap of the current shown Map.
*/
class SnapshotActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var binding: ActivitySnapshotBinding
private lateinit var maplibreMap: MapLibreMap
private val idleListener = object : MapView.OnDidFinishRenderingFrameListener {
override fun onDidFinishRenderingFrame(fully: Boolean, frameEncodingTime: Double, frameRenderingTime: Double) {
if (fully) {
binding.mapView.removeOnDidFinishRenderingFrameListener(this)
Logger.v(TAG, LOG_MESSAGE)
maplibreMap.snapshot { snapshot ->
binding.imageView.setImageBitmap(snapshot)
binding.mapView.addOnDidFinishRenderingFrameListener(this)
}
}
}
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySnapshotBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.mapView.onCreate(savedInstanceState)
binding.mapView.getMapAsync(this)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
maplibreMap.setStyle(Style.Builder().fromUri(Style.getPredefinedStyle("Outdoor"))) { binding.mapView.addOnDidFinishRenderingFrameListener(idleListener) }
}
override fun onStart() {
super.onStart()
binding.mapView.onStart()
}
override fun onResume() {
super.onResume()
binding.mapView.onResume()
}
override fun onPause() {
super.onPause()
maplibreMap.snapshot {
Timber.e("Regression test for https://github.com/mapbox/mapbox-gl-native/pull/11358")
}
binding.mapView.onPause()
}
override fun onStop() {
super.onStop()
binding.mapView.onStop()
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
binding.mapView.onSaveInstanceState(outState)
}
override fun onLowMemory() {
super.onLowMemory()
binding.mapView.onLowMemory()
}
public override fun onDestroy() {
super.onDestroy()
binding.mapView.removeOnDidFinishRenderingFrameListener(idleListener)
binding.mapView.onDestroy()
}
companion object {
const val TAG = "Mbgl-SnapshotActivity"
const val LOG_MESSAGE = "OnSnapshot"
}
}

View File

@@ -0,0 +1,147 @@
package org.maplibre.android.testapp.activity.infowindow
import android.graphics.Color
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat
import org.maplibre.android.annotations.Marker
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapLibreMap.InfoWindowAdapter
import org.maplibre.android.maps.MapLibreMap.OnMapClickListener
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.IconUtils
import java.util.*
/**
* Test activity showcasing how to dynamically update InfoWindow when Using an MapboxMap.InfoWindowAdapter.
*/
class DynamicInfoWindowAdapterActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var maplibreMap: MapLibreMap
private lateinit var mapView: MapView
private var marker: Marker? = null
private val mapClickListener = OnMapClickListener { point ->
if (marker == null) {
return@OnMapClickListener false
}
// Distance from click to marker
val distanceKm = marker!!.position.distanceTo(point) / 1000
// Get the info window
val infoWindow = marker!!.infoWindow
// Get the view from the info window
if (infoWindow != null && infoWindow.view != null) {
// Set the new text on the text view in the info window
val textView = infoWindow.view as TextView?
textView!!.text = String.format(Locale.getDefault(), "%.2fkm", distanceKm)
// Update the info window position (as the text length changes)
textView.post { infoWindow.update() }
}
true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_infowindow_adapter)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
map.setStyle(Style.getPredefinedStyle("Streets"))
// Add info window adapter
addCustomInfoWindowAdapter(maplibreMap!!)
// Keep info windows open on click
maplibreMap.uiSettings.isDeselectMarkersOnTap = false
// Add a marker
marker = addMarker(maplibreMap!!)
maplibreMap.selectMarker(marker!!)
// On map click, change the info window contents
maplibreMap.addOnMapClickListener(mapClickListener)
// Focus on Paris
maplibreMap.animateCamera(CameraUpdateFactory.newLatLng(PARIS))
}
private fun addMarker(maplibreMap: MapLibreMap): Marker {
return maplibreMap.addMarker(
MarkerOptions()
.position(PARIS)
.icon(
IconUtils.drawableToIcon(
this,
R.drawable.ic_location_city,
ResourcesCompat.getColor(resources, R.color.maplibre_blue, theme)
)
)
)
}
private fun addCustomInfoWindowAdapter(maplibreMap: MapLibreMap) {
val padding = resources.getDimension(R.dimen.attr_margin).toInt()
maplibreMap.infoWindowAdapter = InfoWindowAdapter { marker: Marker ->
val textView = TextView(this@DynamicInfoWindowAdapterActivity)
textView.text = marker.title
textView.setBackgroundColor(Color.WHITE)
textView.setText(R.string.action_calculate_distance)
textView.setPadding(padding, padding, padding, padding)
textView
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
if (maplibreMap != null) {
maplibreMap.removeOnMapClickListener(mapClickListener)
}
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
companion object {
private val PARIS = LatLng(48.864716, 2.349014)
}
}

View File

@@ -0,0 +1,197 @@
package org.maplibre.android.testapp.activity.infowindow
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.annotations.Marker
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapLibreMap.OnInfoWindowClickListener
import org.maplibre.android.maps.MapLibreMap.OnInfoWindowCloseListener
import org.maplibre.android.maps.MapLibreMap.OnInfoWindowLongClickListener
import org.maplibre.android.maps.MapLibreMap.OnMapLongClickListener
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import java.text.DecimalFormat
/**
* Test activity showcasing using the InfoWindow API above Washington D.C.
*
*
* Allows to test mulitple concurrently open InfoWindows.
*
*/
class InfoWindowActivity :
AppCompatActivity(),
OnMapReadyCallback,
OnInfoWindowCloseListener,
OnInfoWindowClickListener,
OnInfoWindowLongClickListener {
private lateinit var maplibreMap: MapLibreMap
private lateinit var mapView: MapView
private var customMarker: Marker? = null
private val mapLongClickListener = OnMapLongClickListener { point ->
if (customMarker != null) {
// Remove previous added marker
maplibreMap.removeAnnotation(customMarker!!)
customMarker = null
}
// Add marker on long click location with default marker image
customMarker = maplibreMap.addMarker(
MarkerOptions()
.title("Custom Marker")
.snippet(
DecimalFormat("#.#####").format(point.latitude) + ", " +
DecimalFormat("#.#####").format(point.longitude)
)
.position(point)
)
true
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_infowindow)
mapView = findViewById<View>(R.id.mapView) as MapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
}
override fun onMapReady(maplibreMap: MapLibreMap) {
this.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Streets")) { style: Style? ->
addMarkers()
addInfoWindowListeners()
}
}
private fun addMarkers() {
maplibreMap.addMarker(
MarkerOptions()
.title("Intersection")
.snippet("H St NW with 15th St NW")
.position(LatLng(38.9002073, -77.03364419))
)
maplibreMap.addMarker(
MarkerOptions().title("Intersection")
.snippet("E St NW with 17th St NW")
.position(LatLng(38.8954236, -77.0394623))
)
maplibreMap.addMarker(
MarkerOptions().title("The Ellipse").position(LatLng(38.89393, -77.03654))
)
maplibreMap.addMarker(MarkerOptions().position(LatLng(38.89596, -77.03434)))
maplibreMap.addMarker(
MarkerOptions().snippet("Lafayette Square").position(LatLng(38.89949, -77.03656))
)
val marker = maplibreMap.addMarker(
MarkerOptions()
.title("White House")
.snippet(
"The official residence and principal workplace of the President of the United States, " +
"located at 1600 Pennsylvania Avenue NW in Washington, D.C. It has been the residence of every" +
"U.S. president since John Adams in 1800."
)
.position(LatLng(38.897705003219784, -77.03655168667463))
)
// open InfoWindow at startup
maplibreMap.selectMarker(marker)
}
private fun addInfoWindowListeners() {
maplibreMap.onInfoWindowCloseListener = this
maplibreMap.addOnMapLongClickListener(mapLongClickListener)
maplibreMap.onInfoWindowClickListener = this
maplibreMap.onInfoWindowLongClickListener = this
}
private fun toggleConcurrentInfoWindow(allowConcurrentInfoWindow: Boolean) {
maplibreMap.deselectMarkers()
maplibreMap.isAllowConcurrentMultipleOpenInfoWindows = allowConcurrentInfoWindow
}
private fun toggleDeselectMarkersOnTap(deselectMarkersOnTap: Boolean) {
maplibreMap.uiSettings.isDeselectMarkersOnTap = deselectMarkersOnTap
}
override fun onInfoWindowClick(marker: Marker): Boolean {
Toast.makeText(applicationContext, "OnClick: " + marker.title, Toast.LENGTH_LONG).show()
// returning true will leave the info window open
return false
}
override fun onInfoWindowClose(marker: Marker) {
Toast.makeText(applicationContext, "OnClose: " + marker.title, Toast.LENGTH_LONG).show()
}
override fun onInfoWindowLongClick(marker: Marker) {
Toast.makeText(applicationContext, "OnLongClick: " + marker.title, Toast.LENGTH_LONG).show()
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
if (maplibreMap != null) {
maplibreMap.removeOnMapLongClickListener(mapLongClickListener)
}
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_infowindow, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_toggle_concurrent_infowindow -> {
toggleConcurrentInfoWindow(!item.isChecked)
item.isChecked = !item.isChecked
true
}
R.id.action_toggle_deselect_markers_on_tap -> {
toggleDeselectMarkersOnTap(!item.isChecked)
item.isChecked = !item.isChecked
true
}
else -> super.onOptionsItemSelected(item)
}
}
}

View File

@@ -0,0 +1,138 @@
package org.maplibre.android.testapp.activity.infowindow
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.annotations.Marker
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapLibreMap.InfoWindowAdapter
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.model.annotations.CityStateMarker
import org.maplibre.android.testapp.model.annotations.CityStateMarkerOptions
import org.maplibre.android.testapp.utils.IconUtils
/**
* Test activity showcasing using an InfoWindowAdapter to provide a custom InfoWindow content.
*/
class InfoWindowAdapterActivity : AppCompatActivity() {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_infowindow_adapter)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { map: MapLibreMap ->
maplibreMap = map
map.setStyle(Style.getPredefinedStyle("Streets")) { style: Style? ->
addMarkers()
addCustomInfoWindowAdapter()
}
}
)
}
private fun addMarkers() {
maplibreMap.addMarker(generateCityStateMarker("Andorra", 42.505777, 1.52529, "#F44336"))
maplibreMap.addMarker(generateCityStateMarker("Luxembourg", 49.815273, 6.129583, "#3F51B5"))
maplibreMap.addMarker(generateCityStateMarker("Monaco", 43.738418, 7.424616, "#673AB7"))
maplibreMap.addMarker(
generateCityStateMarker(
"Vatican City",
41.902916,
12.453389,
"#009688"
)
)
maplibreMap.addMarker(
generateCityStateMarker(
"San Marino",
43.942360,
12.457777,
"#795548"
)
)
maplibreMap.addMarker(
generateCityStateMarker(
"Liechtenstein",
47.166000,
9.555373,
"#FF5722"
)
)
}
private fun generateCityStateMarker(
title: String,
lat: Double,
lng: Double,
color: String
): CityStateMarkerOptions {
val marker = CityStateMarkerOptions()
marker.title(title)
marker.position(LatLng(lat, lng))
marker.infoWindowBackground(color)
val icon =
IconUtils.drawableToIcon(this, R.drawable.ic_location_city, Color.parseColor(color))
marker.icon(icon)
return marker
}
private fun addCustomInfoWindowAdapter() {
maplibreMap.infoWindowAdapter = object : InfoWindowAdapter {
private val tenDp = resources.getDimension(R.dimen.attr_margin).toInt()
override fun getInfoWindow(marker: Marker): View? {
val textView = TextView(this@InfoWindowAdapterActivity)
textView.text = marker.title
textView.setTextColor(Color.WHITE)
if (marker is CityStateMarker) {
textView.setBackgroundColor(Color.parseColor(marker.infoWindowBackgroundColor))
}
textView.setPadding(tenDp, tenDp, tenDp, tenDp)
return textView
}
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,210 @@
package org.maplibre.android.testapp.activity.location
import android.annotation.SuppressLint
import android.location.Location
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.location.LocationComponent
import org.maplibre.android.location.LocationComponentActivationOptions
import org.maplibre.android.location.LocationComponentOptions
import org.maplibre.android.location.engine.LocationEngineRequest
import org.maplibre.android.location.modes.CameraMode
import org.maplibre.android.location.permissions.PermissionsListener
import org.maplibre.android.location.permissions.PermissionsManager
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
/* ANCHOR: top */
/**
* This activity shows a basic usage of the LocationComponent's pulsing circle. There's no
* customization of the pulsing circle's color, radius, speed, etc.
*/
class BasicLocationPulsingCircleActivity : AppCompatActivity(), OnMapReadyCallback {
private var lastLocation: Location? = null
private lateinit var mapView: MapView
private var permissionsManager: PermissionsManager? = null
private var locationComponent: LocationComponent? = null
private lateinit var maplibreMap: MapLibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location_layer_basic_pulsing_circle)
mapView = findViewById(R.id.mapView)
if (savedInstanceState != null) {
lastLocation = savedInstanceState.getParcelable(SAVED_STATE_LOCATION)
}
mapView.onCreate(savedInstanceState)
checkPermissions()
}
/* ANCHOR_END: top */
/* ANCHOR: onMapReady */
@SuppressLint("MissingPermission")
override fun onMapReady(maplibreMap: MapLibreMap) {
this.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Streets")) { style: Style ->
locationComponent = maplibreMap.locationComponent
val locationComponentOptions =
LocationComponentOptions.builder(this@BasicLocationPulsingCircleActivity)
.pulseEnabled(true)
.build()
val locationComponentActivationOptions =
buildLocationComponentActivationOptions(style, locationComponentOptions)
locationComponent!!.activateLocationComponent(locationComponentActivationOptions)
locationComponent!!.isLocationComponentEnabled = true
locationComponent!!.cameraMode = CameraMode.TRACKING
locationComponent!!.forceLocationUpdate(lastLocation)
}
}
/* ANCHOR_END: onMapReady */
/* ANCHOR: LocationComponentActivationOptions */
private fun buildLocationComponentActivationOptions(
style: Style,
locationComponentOptions: LocationComponentOptions
): LocationComponentActivationOptions {
return LocationComponentActivationOptions
.builder(this, style)
.locationComponentOptions(locationComponentOptions)
.useDefaultLocationEngine(true)
.locationEngineRequest(
LocationEngineRequest.Builder(750)
.setFastestInterval(750)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
.build()
)
.build()
}
/* ANCHOR_END: LocationComponentActivationOptions */
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_pulsing_location_mode, menu)
return true
}
@SuppressLint("MissingPermission")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (locationComponent == null) {
return super.onOptionsItemSelected(item)
}
val id = item.itemId
if (id == R.id.action_map_style_change) {
loadNewStyle()
return true
} else if (id == R.id.action_component_disable) {
locationComponent!!.isLocationComponentEnabled = false
return true
} else if (id == R.id.action_component_enabled) {
locationComponent!!.isLocationComponentEnabled = true
return true
} else if (id == R.id.action_stop_pulsing) {
locationComponent!!.applyStyle(
LocationComponentOptions.builder(
this@BasicLocationPulsingCircleActivity
)
.pulseEnabled(false)
.build()
)
return true
} else if (id == R.id.action_start_pulsing) {
locationComponent!!.applyStyle(
LocationComponentOptions.builder(
this@BasicLocationPulsingCircleActivity
)
.pulseEnabled(true)
.build()
)
return true
}
return super.onOptionsItemSelected(item)
}
private fun loadNewStyle() {
maplibreMap.setStyle(Style.Builder().fromUri(Utils.nextStyle()))
}
/* ANCHOR: permission */
private fun checkPermissions() {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
mapView.getMapAsync(this)
} else {
permissionsManager = PermissionsManager(object : PermissionsListener {
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
Toast.makeText(
this@BasicLocationPulsingCircleActivity,
"You need to accept location permissions.",
Toast.LENGTH_SHORT
).show()
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
mapView.getMapAsync(this@BasicLocationPulsingCircleActivity)
} else {
finish()
}
}
})
permissionsManager!!.requestLocationPermissions(this)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionsManager!!.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
/* ANCHOR_END: permission */
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
@SuppressLint("MissingPermission")
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
if (locationComponent != null) {
outState.putParcelable(SAVED_STATE_LOCATION, locationComponent!!.lastKnownLocation)
}
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
companion object {
private const val SAVED_STATE_LOCATION = "saved_state_location"
private const val TAG = "Mbgl-BasicLocationPulsingCircleActivity"
}
}

View File

@@ -0,0 +1,395 @@
package org.maplibre.android.testapp.activity.location
import android.annotation.SuppressLint
import android.graphics.Color
import android.location.Location
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.view.animation.Interpolator
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.ListPopupWindow
import org.maplibre.android.location.LocationComponent
import org.maplibre.android.location.LocationComponentActivationOptions
import org.maplibre.android.location.LocationComponentOptions
import org.maplibre.android.location.engine.LocationEngineRequest
import org.maplibre.android.location.modes.CameraMode
import org.maplibre.android.location.permissions.PermissionsListener
import org.maplibre.android.location.permissions.PermissionsManager
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
/**
* This activity shows how to customize the LocationComponent's pulsing circle.
*/
class CustomizedLocationPulsingCircleActivity : AppCompatActivity(), OnMapReadyCallback {
private var lastLocation: Location? = null
private lateinit var mapView: MapView
private lateinit var pulsingCircleDurationButton: Button
private lateinit var pulsingCircleColorButton: Button
private var permissionsManager: PermissionsManager? = null
private var locationComponent: LocationComponent? = null
private lateinit var maplibreMap: MapLibreMap
private var currentPulseDuration = 0f
//endregion
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location_layer_customized_pulsing_circle)
LOCATION_CIRCLE_PULSE_COLOR = Color.BLUE
mapView = findViewById(R.id.mapView)
if (savedInstanceState != null) {
lastLocation = savedInstanceState.getParcelable(SAVED_STATE_LOCATION)
LOCATION_CIRCLE_PULSE_COLOR = savedInstanceState.getInt(
SAVED_STATE_LOCATION_CIRCLE_PULSE_COLOR
)
LOCATION_CIRCLE_PULSE_DURATION = savedInstanceState.getFloat(
SAVED_STATE_LOCATION_CIRCLE_PULSE_DURATION
)
}
pulsingCircleDurationButton = findViewById(R.id.button_location_circle_duration)
pulsingCircleDurationButton.setText(
String.format(
"%sms",
LOCATION_CIRCLE_PULSE_DURATION.toString()
)
)
pulsingCircleDurationButton.setOnClickListener(
View.OnClickListener setOnClickListener@{ v: View? ->
if (locationComponent == null) {
return@setOnClickListener
}
showDurationListDialog()
}
)
pulsingCircleColorButton = findViewById(R.id.button_location_circle_color)
pulsingCircleColorButton.setOnClickListener(
View.OnClickListener setOnClickListener@{ v: View? ->
if (locationComponent == null) {
return@setOnClickListener
}
showColorListDialog()
}
)
mapView.onCreate(savedInstanceState)
checkPermissions()
}
@SuppressLint("MissingPermission")
override fun onMapReady(maplibreMap: MapLibreMap) {
this.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Streets")) { style: Style ->
locationComponent = maplibreMap.locationComponent
val locationComponentOptions = buildLocationComponentOptions(
LOCATION_CIRCLE_PULSE_COLOR,
LOCATION_CIRCLE_PULSE_DURATION
)
.pulseEnabled(true)
.build()
val locationComponentActivationOptions =
buildLocationComponentActivationOptions(style, locationComponentOptions)
locationComponent!!.activateLocationComponent(locationComponentActivationOptions)
locationComponent!!.isLocationComponentEnabled = true
locationComponent!!.cameraMode = CameraMode.TRACKING
locationComponent!!.forceLocationUpdate(lastLocation)
}
}
private fun buildLocationComponentOptions(
pulsingCircleColor: Int,
pulsingCircleDuration: Float
): LocationComponentOptions.Builder {
currentPulseDuration = pulsingCircleDuration
return LocationComponentOptions.builder(this)
.layerBelow(LAYER_BELOW_ID)
.pulseFadeEnabled(DEFAULT_LOCATION_CIRCLE_PULSE_FADE_MODE)
.pulseInterpolator(DEFAULT_LOCATION_CIRCLE_INTERPOLATOR_PULSE_MODE)
.pulseColor(pulsingCircleColor)
.pulseAlpha(DEFAULT_LOCATION_CIRCLE_PULSE_ALPHA)
.pulseSingleDuration(pulsingCircleDuration)
.pulseMaxRadius(DEFAULT_LOCATION_CIRCLE_PULSE_RADIUS)
}
@SuppressLint("MissingPermission")
private fun setNewLocationComponentOptions(
newPulsingDuration: Float,
newPulsingColor: Int
) {
maplibreMap.getStyle { style: Style? ->
locationComponent!!.applyStyle(
buildLocationComponentOptions(
newPulsingColor,
newPulsingDuration
)
.pulseEnabled(true)
.build()
)
}
}
private fun buildLocationComponentActivationOptions(
style: Style,
locationComponentOptions: LocationComponentOptions
): LocationComponentActivationOptions {
return LocationComponentActivationOptions
.builder(this, style)
.locationComponentOptions(locationComponentOptions)
.useDefaultLocationEngine(true)
.locationEngineRequest(
LocationEngineRequest.Builder(750)
.setFastestInterval(750)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
.build()
)
.build()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_pulsing_location_mode, menu)
return true
}
@SuppressLint("MissingPermission")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (locationComponent == null) {
return super.onOptionsItemSelected(item)
}
val id = item.itemId
if (id == R.id.action_map_style_change) {
loadNewStyle()
return true
} else if (id == R.id.action_component_disable) {
locationComponent!!.isLocationComponentEnabled = false
return true
} else if (id == R.id.action_component_enabled) {
locationComponent!!.isLocationComponentEnabled = true
return true
} else if (id == R.id.action_stop_pulsing) {
locationComponent!!.applyStyle(
LocationComponentOptions.builder(
this@CustomizedLocationPulsingCircleActivity
)
.pulseEnabled(false)
.build()
)
return true
} else if (id == R.id.action_start_pulsing) {
locationComponent!!.applyStyle(
buildLocationComponentOptions(
LOCATION_CIRCLE_PULSE_COLOR,
LOCATION_CIRCLE_PULSE_DURATION
)
.pulseEnabled(true)
.build()
)
return true
}
return super.onOptionsItemSelected(item)
}
private fun loadNewStyle() {
maplibreMap.setStyle(Style.Builder().fromUri(Utils.nextStyle()))
}
private fun checkPermissions() {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
mapView.getMapAsync(this)
} else {
permissionsManager = PermissionsManager(object : PermissionsListener {
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
Toast.makeText(
this@CustomizedLocationPulsingCircleActivity,
"You need to accept location permissions.",
Toast.LENGTH_SHORT
).show()
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
mapView.getMapAsync(this@CustomizedLocationPulsingCircleActivity)
} else {
finish()
}
}
})
permissionsManager!!.requestLocationPermissions(this)
}
}
private fun showDurationListDialog() {
val modes: MutableList<String> = ArrayList()
modes.add(String.format("%sms", DEFAULT_LOCATION_CIRCLE_PULSE_DURATION_MS.toString()))
modes.add(String.format("%sms", SECOND_LOCATION_CIRCLE_PULSE_DURATION_MS.toString()))
modes.add(String.format("%sms", THIRD_LOCATION_CIRCLE_PULSE_DURATION_MS.toString()))
val profileAdapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_1,
modes
)
val listPopup = ListPopupWindow(this)
listPopup.setAdapter(profileAdapter)
listPopup.anchorView = pulsingCircleDurationButton
listPopup.setOnItemClickListener { parent: AdapterView<*>?, itemView: View?, position: Int, id: Long ->
val selectedMode = modes[position]
pulsingCircleDurationButton!!.text = selectedMode
if (selectedMode.contentEquals(
String.format(
"%sms",
DEFAULT_LOCATION_CIRCLE_PULSE_DURATION_MS.toString()
)
)
) {
LOCATION_CIRCLE_PULSE_DURATION = DEFAULT_LOCATION_CIRCLE_PULSE_DURATION_MS
setNewLocationComponentOptions(
DEFAULT_LOCATION_CIRCLE_PULSE_DURATION_MS,
LOCATION_CIRCLE_PULSE_COLOR
)
} else if (selectedMode.contentEquals(
String.format(
"%sms",
SECOND_LOCATION_CIRCLE_PULSE_DURATION_MS.toString()
)
)
) {
LOCATION_CIRCLE_PULSE_DURATION = SECOND_LOCATION_CIRCLE_PULSE_DURATION_MS
setNewLocationComponentOptions(
SECOND_LOCATION_CIRCLE_PULSE_DURATION_MS,
LOCATION_CIRCLE_PULSE_COLOR
)
} else if (selectedMode.contentEquals(
String.format(
"%sms",
THIRD_LOCATION_CIRCLE_PULSE_DURATION_MS.toString()
)
)
) {
LOCATION_CIRCLE_PULSE_DURATION = THIRD_LOCATION_CIRCLE_PULSE_DURATION_MS
setNewLocationComponentOptions(
THIRD_LOCATION_CIRCLE_PULSE_DURATION_MS,
LOCATION_CIRCLE_PULSE_COLOR
)
}
listPopup.dismiss()
}
listPopup.show()
}
private fun showColorListDialog() {
val trackingTypes: MutableList<String> = ArrayList()
trackingTypes.add("Blue")
trackingTypes.add("Red")
trackingTypes.add("Green")
trackingTypes.add("Gray")
val profileAdapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_1,
trackingTypes
)
val listPopup = ListPopupWindow(this)
listPopup.setAdapter(profileAdapter)
listPopup.anchorView = pulsingCircleColorButton
listPopup.setOnItemClickListener { parent: AdapterView<*>?, itemView: View?, position: Int, id: Long ->
val selectedTrackingType = trackingTypes[position]
pulsingCircleColorButton!!.text = selectedTrackingType
if (selectedTrackingType.contentEquals("Blue")) {
LOCATION_CIRCLE_PULSE_COLOR = Color.BLUE
setNewLocationComponentOptions(currentPulseDuration, Color.BLUE)
} else if (selectedTrackingType.contentEquals("Red")) {
LOCATION_CIRCLE_PULSE_COLOR = Color.RED
setNewLocationComponentOptions(currentPulseDuration, Color.RED)
} else if (selectedTrackingType.contentEquals("Green")) {
LOCATION_CIRCLE_PULSE_COLOR = Color.GREEN
setNewLocationComponentOptions(currentPulseDuration, Color.GREEN)
} else if (selectedTrackingType.contentEquals("Gray")) {
LOCATION_CIRCLE_PULSE_COLOR = Color.parseColor("#4a4a4a")
setNewLocationComponentOptions(currentPulseDuration, Color.parseColor("#4a4a4a"))
}
listPopup.dismiss()
}
listPopup.show()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionsManager!!.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
@SuppressLint("MissingPermission")
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
if (locationComponent != null) {
outState.putParcelable(SAVED_STATE_LOCATION, locationComponent!!.lastKnownLocation)
outState.putInt(SAVED_STATE_LOCATION_CIRCLE_PULSE_COLOR, LOCATION_CIRCLE_PULSE_COLOR)
outState.putFloat(
SAVED_STATE_LOCATION_CIRCLE_PULSE_DURATION,
LOCATION_CIRCLE_PULSE_DURATION
)
}
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
companion object {
//region
// Adjust these variables to customize the example's pulsing circle UI
private const val DEFAULT_LOCATION_CIRCLE_PULSE_DURATION_MS = 2300f
private const val SECOND_LOCATION_CIRCLE_PULSE_DURATION_MS = 800f
private const val THIRD_LOCATION_CIRCLE_PULSE_DURATION_MS = 8000f
private const val DEFAULT_LOCATION_CIRCLE_PULSE_RADIUS = 35f
private const val DEFAULT_LOCATION_CIRCLE_PULSE_ALPHA = .55f
private val DEFAULT_LOCATION_CIRCLE_INTERPOLATOR_PULSE_MODE: Interpolator =
DecelerateInterpolator()
private const val DEFAULT_LOCATION_CIRCLE_PULSE_FADE_MODE = true
//endregion
//region
private var LOCATION_CIRCLE_PULSE_COLOR = 0
private var LOCATION_CIRCLE_PULSE_DURATION = DEFAULT_LOCATION_CIRCLE_PULSE_DURATION_MS
private const val SAVED_STATE_LOCATION = "saved_state_location"
private const val SAVED_STATE_LOCATION_CIRCLE_PULSE_COLOR = "saved_state_color"
private const val SAVED_STATE_LOCATION_CIRCLE_PULSE_DURATION = "saved_state_duration"
private const val LAYER_BELOW_ID = "poi_transit"
}
}

View File

@@ -0,0 +1,123 @@
package org.maplibre.android.testapp.activity.location
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.location.LocationComponentActivationOptions
import org.maplibre.android.location.LocationComponentOptions
import org.maplibre.android.location.modes.CameraMode
import org.maplibre.android.location.modes.RenderMode
import org.maplibre.android.location.permissions.PermissionsListener
import org.maplibre.android.location.permissions.PermissionsManager
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
class LocationComponentActivationActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private var permissionsManager: PermissionsManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location_layer_activation_builder)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
if (PermissionsManager.areLocationPermissionsGranted(this)) {
mapView.getMapAsync(this)
} else {
permissionsManager = PermissionsManager(object : PermissionsListener {
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
Toast.makeText(
this@LocationComponentActivationActivity,
"You need to accept location permissions.",
Toast.LENGTH_SHORT
).show()
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
mapView.getMapAsync(this@LocationComponentActivationActivity)
} else {
finish()
}
}
})
permissionsManager!!.requestLocationPermissions(this)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionsManager!!.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onMapReady(maplibreMap: MapLibreMap) {
this.maplibreMap = maplibreMap
maplibreMap.setStyle(
Style.getPredefinedStyle("Bright")
) { style: Style -> activateLocationComponent(style) }
}
@SuppressLint("MissingPermission")
private fun activateLocationComponent(style: Style) {
val locationComponent = maplibreMap.locationComponent
val locationComponentOptions = LocationComponentOptions.builder(this)
.elevation(5f)
.accuracyAlpha(.6f)
.accuracyColor(Color.GREEN)
.foregroundDrawable(R.drawable.maplibre_logo_helmet)
.build()
val locationComponentActivationOptions = LocationComponentActivationOptions
.builder(this, style)
.locationComponentOptions(locationComponentOptions)
.useDefaultLocationEngine(true)
.build()
locationComponent.activateLocationComponent(locationComponentActivationOptions)
locationComponent.isLocationComponentEnabled = true
locationComponent.renderMode = RenderMode.NORMAL
locationComponent.cameraMode = CameraMode.TRACKING
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,184 @@
package org.maplibre.android.testapp.activity.location
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.location.LocationComponentActivationOptions
import org.maplibre.android.location.engine.LocationEngineCallback
import org.maplibre.android.location.engine.LocationEngineResult
import org.maplibre.android.location.permissions.PermissionsListener
import org.maplibre.android.location.permissions.PermissionsManager
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.databinding.ActivityLocationLayerFragmentBinding
class LocationFragmentActivity : AppCompatActivity() {
private lateinit var binding: ActivityLocationLayerFragmentBinding
private lateinit var permissionsManager: PermissionsManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLocationLayerFragmentBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.fab.setOnClickListener {
val fragment = supportFragmentManager.findFragmentByTag(EmptyFragment.TAG)
if (fragment == null) {
supportFragmentManager
.beginTransaction()
.replace(R.id.container, EmptyFragment.newInstance(), EmptyFragment.TAG)
.addToBackStack("transaction2")
.commit()
} else {
this.onBackPressed()
}
}
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (PermissionsManager.areLocationPermissionsGranted(this)) {
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.replace(R.id.container, LocationFragment.newInstance(), LocationFragment.TAG)
.commit()
}
} else {
permissionsManager = PermissionsManager(object : PermissionsListener {
override fun onExplanationNeeded(permissionsToExplain: MutableList<String>?) {
Toast.makeText(
this@LocationFragmentActivity,
"You need to accept location permissions.",
Toast.LENGTH_SHORT
).show()
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.replace(R.id.container, LocationFragment.newInstance(), LocationFragment.TAG)
.commit()
}
} else {
finish()
}
}
})
permissionsManager.requestLocationPermissions(this)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
class LocationFragment : androidx.fragment.app.Fragment(), LocationEngineCallback<LocationEngineResult> {
companion object {
const val TAG = "LFragment"
fun newInstance(): LocationFragment {
return LocationFragment()
}
}
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mapView = MapView(inflater.context)
return mapView
}
@SuppressLint("MissingPermission")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync {
maplibreMap = it
it.setStyle(Style.getPredefinedStyle("Streets")) { style ->
val component = maplibreMap.locationComponent
component.activateLocationComponent(
LocationComponentActivationOptions
.builder(requireActivity(), style)
.useDefaultLocationEngine(true)
.build()
)
component.isLocationComponentEnabled = true
component.locationEngine?.getLastLocation(this)
}
}
}
override fun onSuccess(result: LocationEngineResult?) {
if (!mapView.isDestroyed) maplibreMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(result?.lastLocation!!), 12.0))
}
override fun onFailure(exception: Exception) {
// noop
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroyView() {
super.onDestroyView()
mapView.onDestroy()
}
}
class EmptyFragment : androidx.fragment.app.Fragment() {
companion object {
const val TAG = "EmptyFragment"
fun newInstance(): EmptyFragment {
return EmptyFragment()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val textView = TextView(inflater.context)
textView.text = getString(R.string.this_is_an_empty_fragment)
return textView
}
}
}

View File

@@ -0,0 +1,135 @@
package org.maplibre.android.testapp.activity.location
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.maplibre.android.location.LocationComponentActivationOptions
import org.maplibre.android.location.modes.RenderMode
import org.maplibre.android.location.permissions.PermissionsListener
import org.maplibre.android.location.permissions.PermissionsManager
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
class LocationMapChangeActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private var permissionsManager: PermissionsManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location_layer_map_change)
mapView = findViewById(R.id.mapView)
val stylesFab = findViewById<FloatingActionButton>(R.id.fabStyles)
stylesFab.setOnClickListener { v: View? ->
if (maplibreMap != null) {
maplibreMap.setStyle(Style.Builder().fromUri(Utils.nextStyle()))
}
}
mapView.onCreate(savedInstanceState)
if (PermissionsManager.areLocationPermissionsGranted(this)) {
mapView.getMapAsync(this)
} else {
permissionsManager = PermissionsManager(object : PermissionsListener {
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
Toast.makeText(
this@LocationMapChangeActivity,
"You need to accept location permissions.",
Toast.LENGTH_SHORT
).show()
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
mapView.getMapAsync(this@LocationMapChangeActivity)
} else {
finish()
}
}
})
permissionsManager!!.requestLocationPermissions(this)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionsManager!!.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onMapReady(maplibreMap: MapLibreMap) {
this.maplibreMap = maplibreMap
maplibreMap.setStyle(
Style.Builder().fromUri(Utils.nextStyle())
) { style: Style -> activateLocationComponent(style) }
}
@SuppressLint("MissingPermission")
private fun activateLocationComponent(style: Style) {
val locationComponent = maplibreMap.locationComponent
locationComponent.activateLocationComponent(
LocationComponentActivationOptions
.builder(this, style)
.useDefaultLocationEngine(true)
.build()
)
locationComponent.isLocationComponentEnabled = true
locationComponent.renderMode = RenderMode.COMPASS
locationComponent.addOnLocationClickListener {
Toast.makeText(
this,
"Location clicked",
Toast.LENGTH_SHORT
).show()
}
locationComponent.addOnLocationLongClickListener {
Toast.makeText(
this,
"Location long clicked",
Toast.LENGTH_SHORT
).show()
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,478 @@
package org.maplibre.android.testapp.activity.location
import android.annotation.SuppressLint
import android.content.res.Configuration
import android.graphics.RectF
import android.location.Location
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.ListPopupWindow
import org.maplibre.android.location.LocationComponent
import org.maplibre.android.location.LocationComponentActivationOptions
import org.maplibre.android.location.LocationComponentOptions
import org.maplibre.android.location.OnCameraTrackingChangedListener
import org.maplibre.android.location.OnLocationCameraTransitionListener
import org.maplibre.android.location.OnLocationClickListener
import org.maplibre.android.location.engine.LocationEngineRequest
import org.maplibre.android.location.modes.CameraMode
import org.maplibre.android.location.modes.RenderMode
import org.maplibre.android.location.permissions.PermissionsListener
import org.maplibre.android.location.permissions.PermissionsManager
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.MapLibreMap.CancelableCallback
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import java.util.Random
class LocationModesActivity :
AppCompatActivity(),
OnMapReadyCallback,
OnLocationClickListener,
OnCameraTrackingChangedListener {
private lateinit var mapView: MapView
private lateinit var locationModeBtn: Button
private lateinit var locationTrackingBtn: Button
private var protectedGestureArea: View? = null
private var permissionsManager: PermissionsManager? = null
private var locationComponent: LocationComponent? = null
private lateinit var maplibreMap: MapLibreMap
private var defaultStyle = false
@CameraMode.Mode
private var cameraMode = CameraMode.TRACKING
@RenderMode.Mode
private var renderMode = RenderMode.NORMAL
private var lastLocation: Location? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location_layer_mode)
mapView = findViewById(R.id.mapView)
protectedGestureArea = findViewById(R.id.view_protected_gesture_area)
locationModeBtn = findViewById(R.id.button_location_mode)
locationModeBtn.setOnClickListener(
View.OnClickListener setOnClickListener@{ v: View? ->
if (locationComponent == null) {
return@setOnClickListener
}
showModeListDialog()
}
)
locationTrackingBtn = findViewById(R.id.button_location_tracking)
locationTrackingBtn.setOnClickListener(
View.OnClickListener setOnClickListener@{ v: View? ->
if (locationComponent == null) {
return@setOnClickListener
}
showTrackingListDialog()
}
)
if (savedInstanceState != null) {
cameraMode = savedInstanceState.getInt(SAVED_STATE_CAMERA)
renderMode = savedInstanceState.getInt(SAVED_STATE_RENDER)
lastLocation = savedInstanceState.getParcelable(SAVED_STATE_LOCATION)
}
mapView.onCreate(savedInstanceState)
if (PermissionsManager.areLocationPermissionsGranted(this)) {
mapView.getMapAsync(this)
} else {
permissionsManager = PermissionsManager(object : PermissionsListener {
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
Toast.makeText(
this@LocationModesActivity,
"You need to accept location permissions.",
Toast.LENGTH_SHORT
).show()
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
mapView.getMapAsync(this@LocationModesActivity)
} else {
finish()
}
}
})
permissionsManager!!.requestLocationPermissions(this)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionsManager!!.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
@SuppressLint("MissingPermission")
override fun onMapReady(maplibreMap: MapLibreMap) {
this.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Streets")) { style: Style? ->
locationComponent = maplibreMap.locationComponent
locationComponent!!.activateLocationComponent(
LocationComponentActivationOptions
.builder(this, style!!)
.useSpecializedLocationLayer(true)
.useDefaultLocationEngine(true)
.locationEngineRequest(
LocationEngineRequest.Builder(750)
.setFastestInterval(750)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
.build()
)
.build()
)
toggleStyle()
locationComponent!!.isLocationComponentEnabled = true
locationComponent!!.addOnLocationClickListener(this)
locationComponent!!.addOnCameraTrackingChangedListener(this)
locationComponent!!.cameraMode = cameraMode
setRendererMode(renderMode)
locationComponent!!.forceLocationUpdate(lastLocation)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_location_mode, menu)
return true
}
@SuppressLint("MissingPermission")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (locationComponent == null) {
return super.onOptionsItemSelected(item)
}
val id = item.itemId
if (id == R.id.action_style_change) {
toggleStyle()
return true
} else if (id == R.id.action_map_style_change) {
toggleMapStyle()
return true
} else if (id == R.id.action_component_disable) {
locationComponent!!.isLocationComponentEnabled = false
return true
} else if (id == R.id.action_component_enabled) {
locationComponent!!.isLocationComponentEnabled = true
return true
} else if (id == R.id.action_gestures_management_disabled) {
disableGesturesManagement()
return true
} else if (id == R.id.action_gestures_management_enabled) {
enableGesturesManagement()
return true
} else if (id == R.id.action_component_throttling_enabled) {
locationComponent!!.setMaxAnimationFps(5)
} else if (id == R.id.action_component_throttling_disabled) {
locationComponent!!.setMaxAnimationFps(Int.MAX_VALUE)
} else if (id == R.id.action_component_animate_while_tracking) {
locationComponent!!.zoomWhileTracking(
17.0,
750,
object : CancelableCallback {
override fun onCancel() {
// No impl
}
override fun onFinish() {
locationComponent!!.tiltWhileTracking(60.0)
}
}
)
if (locationComponent!!.cameraMode == CameraMode.NONE) {
Toast.makeText(this, "Not possible to animate - not tracking", Toast.LENGTH_SHORT)
.show()
}
} else if (id == R.id.action_component_padding_animation_while_tracking) {
val paddingRandom = Random()
locationComponent!!.paddingWhileTracking(
doubleArrayOf(
paddingRandom.nextDouble() * 500,
paddingRandom.nextDouble() * 500,
paddingRandom.nextDouble() * 500,
paddingRandom.nextDouble() * 500
), 1000L, object : CancelableCallback {
override fun onCancel() {
// No impl
}
override fun onFinish() {
locationComponent!!.zoomWhileTracking(16.0)
}
})
if (locationComponent!!.getCameraMode() == CameraMode.NONE) {
Toast.makeText(this, "Not possible to animate - not tracking", Toast.LENGTH_SHORT)
.show()
}
}
return super.onOptionsItemSelected(item)
}
private fun toggleStyle() {
if (locationComponent == null) {
return
}
defaultStyle = !defaultStyle
var options = LocationComponentOptions.createFromAttributes(
this,
if (defaultStyle) R.style.maplibre_LocationComponent else R.style.CustomLocationComponent
)
if (defaultStyle) {
val padding: IntArray
padding =
if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
intArrayOf(0, 750, 0, 0)
} else {
intArrayOf(0, 250, 0, 0)
}
options = options.toBuilder()
.padding(padding)
.build()
}
locationComponent!!.applyStyle(options)
}
private fun toggleMapStyle() {
if (locationComponent == null) {
return
}
maplibreMap.getStyle { style: Style ->
val styleUrl =
Style.getPredefinedStyle(
if (Style.getPredefinedStyle("Bright") == style.uri) {
"Bright"
} else {
"Pastel"
}
)
maplibreMap.setStyle(Style.Builder().fromUri(styleUrl))
}
}
private fun disableGesturesManagement() {
if (locationComponent == null) {
return
}
protectedGestureArea!!.layoutParams.height = 0
protectedGestureArea!!.layoutParams.width = 0
val options = locationComponent!!
.locationComponentOptions
.toBuilder()
.trackingGesturesManagement(false)
.build()
locationComponent!!.applyStyle(options)
}
private fun enableGesturesManagement() {
if (locationComponent == null) {
return
}
val rectF = RectF(0f, 0f, mapView.width / 2f, mapView.height / 2f)
protectedGestureArea!!.layoutParams.height = rectF.bottom.toInt()
protectedGestureArea!!.layoutParams.width = rectF.right.toInt()
val options = locationComponent!!
.locationComponentOptions
.toBuilder()
.trackingGesturesManagement(true)
.trackingMultiFingerProtectedMoveArea(rectF)
.trackingMultiFingerMoveThreshold(500f)
.build()
locationComponent!!.applyStyle(options)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
@SuppressLint("MissingPermission")
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
outState.putInt(SAVED_STATE_CAMERA, cameraMode)
outState.putInt(SAVED_STATE_RENDER, renderMode)
if (locationComponent != null) {
outState.putParcelable(SAVED_STATE_LOCATION, locationComponent!!.lastKnownLocation)
}
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onLocationComponentClick() {
Toast.makeText(this, "OnLocationComponentClick", Toast.LENGTH_LONG).show()
}
private fun showModeListDialog() {
val modes: MutableList<String> = ArrayList()
modes.add("Normal")
modes.add("Compass")
modes.add("GPS")
val profileAdapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_1,
modes
)
val listPopup = ListPopupWindow(this)
listPopup.setAdapter(profileAdapter)
listPopup.anchorView = locationModeBtn
listPopup.setOnItemClickListener { parent: AdapterView<*>?, itemView: View?, position: Int, id: Long ->
val selectedMode = modes[position]
locationModeBtn.text = selectedMode
if (selectedMode.contentEquals("Normal")) {
setRendererMode(RenderMode.NORMAL)
} else if (selectedMode.contentEquals("Compass")) {
setRendererMode(RenderMode.COMPASS)
} else if (selectedMode.contentEquals("GPS")) {
setRendererMode(RenderMode.GPS)
}
listPopup.dismiss()
}
listPopup.show()
}
@SuppressLint("SetTextI18n")
private fun setRendererMode(@RenderMode.Mode mode: Int) {
renderMode = mode
locationComponent!!.renderMode = mode
if (mode == RenderMode.NORMAL) {
locationModeBtn.text = "Normal"
} else if (mode == RenderMode.COMPASS) {
locationModeBtn.text = "Compass"
} else if (mode == RenderMode.GPS) {
locationModeBtn.text = "Gps"
}
}
private fun showTrackingListDialog() {
val trackingTypes: MutableList<String> = ArrayList()
trackingTypes.add("None")
trackingTypes.add("None Compass")
trackingTypes.add("None GPS")
trackingTypes.add("Tracking")
trackingTypes.add("Tracking Compass")
trackingTypes.add("Tracking GPS")
trackingTypes.add("Tracking GPS North")
val profileAdapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_1,
trackingTypes
)
val listPopup = ListPopupWindow(this)
listPopup.setAdapter(profileAdapter)
listPopup.anchorView = locationTrackingBtn
listPopup.setOnItemClickListener { parent: AdapterView<*>?, itemView: View?, position: Int, id: Long ->
val selectedTrackingType = trackingTypes[position]
locationTrackingBtn.text = selectedTrackingType
if (selectedTrackingType.contentEquals("None")) {
setCameraTrackingMode(CameraMode.NONE)
} else if (selectedTrackingType.contentEquals("None Compass")) {
setCameraTrackingMode(CameraMode.NONE_COMPASS)
} else if (selectedTrackingType.contentEquals("None GPS")) {
setCameraTrackingMode(CameraMode.NONE_GPS)
} else if (selectedTrackingType.contentEquals("Tracking")) {
setCameraTrackingMode(CameraMode.TRACKING)
} else if (selectedTrackingType.contentEquals("Tracking Compass")) {
setCameraTrackingMode(CameraMode.TRACKING_COMPASS)
} else if (selectedTrackingType.contentEquals("Tracking GPS")) {
setCameraTrackingMode(CameraMode.TRACKING_GPS)
} else if (selectedTrackingType.contentEquals("Tracking GPS North")) {
setCameraTrackingMode(CameraMode.TRACKING_GPS_NORTH)
}
listPopup.dismiss()
}
listPopup.show()
}
private fun setCameraTrackingMode(@CameraMode.Mode mode: Int) {
locationComponent!!.setCameraMode(
mode,
1200,
16.0,
null,
45.0,
object : OnLocationCameraTransitionListener {
override fun onLocationCameraTransitionFinished(@CameraMode.Mode cameraMode: Int) {
Toast.makeText(
this@LocationModesActivity,
"Transition finished",
Toast.LENGTH_SHORT
).show()
}
override fun onLocationCameraTransitionCanceled(@CameraMode.Mode cameraMode: Int) {
Toast.makeText(
this@LocationModesActivity,
"Transition canceled",
Toast.LENGTH_SHORT
).show()
}
}
)
}
@SuppressLint("SetTextI18n")
override fun onCameraTrackingDismissed() {
locationTrackingBtn.text = "None"
}
@SuppressLint("SetTextI18n")
override fun onCameraTrackingChanged(currentMode: Int) {
cameraMode = currentMode
if (currentMode == CameraMode.NONE) {
locationTrackingBtn.text = "None"
} else if (currentMode == CameraMode.NONE_COMPASS) {
locationTrackingBtn.text = "None Compass"
} else if (currentMode == CameraMode.NONE_GPS) {
locationTrackingBtn.text = "None GPS"
} else if (currentMode == CameraMode.TRACKING) {
locationTrackingBtn.text = "Tracking"
} else if (currentMode == CameraMode.TRACKING_COMPASS) {
locationTrackingBtn.text = "Tracking Compass"
} else if (currentMode == CameraMode.TRACKING_GPS) {
locationTrackingBtn.text = "Tracking GPS"
} else if (currentMode == CameraMode.TRACKING_GPS_NORTH) {
locationTrackingBtn.text = "Tracking GPS North"
}
}
companion object {
private const val SAVED_STATE_CAMERA = "saved_state_camera"
private const val SAVED_STATE_RENDER = "saved_state_render"
private const val SAVED_STATE_LOCATION = "saved_state_location"
}
}

View File

@@ -0,0 +1,159 @@
package org.maplibre.android.testapp.activity.location
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.maplibre.android.geometry.LatLngBounds
import org.maplibre.android.location.LocationComponent
import org.maplibre.android.location.LocationComponentActivationOptions
import org.maplibre.android.location.engine.LocationEngine
import org.maplibre.android.location.engine.LocationEngineDefault
import org.maplibre.android.location.engine.LocationEngineRequest
import org.maplibre.android.location.modes.RenderMode
import org.maplibre.android.location.permissions.PermissionsListener
import org.maplibre.android.location.permissions.PermissionsManager
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.OnMapReadyCallback
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
class ManualLocationUpdatesActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mapView: MapView
private var locationComponent: LocationComponent? = null
private var locationEngine: LocationEngine? = null
private var permissionsManager: PermissionsManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location_manual_update)
locationEngine = LocationEngineDefault.getDefaultLocationEngine(mapView.context)
val fabManualUpdate = findViewById<FloatingActionButton>(R.id.fabManualLocationChange)
fabManualUpdate.setOnClickListener { v: View? ->
if (locationComponent != null && locationComponent!!.locationEngine == null) {
locationComponent!!.forceLocationUpdate(
Utils.getRandomLocation(LatLngBounds.from(60.0, 25.0, 40.0, -5.0))
)
}
}
fabManualUpdate.isEnabled = false
val fabToggle = findViewById<FloatingActionButton>(R.id.fabToggleManualLocation)
fabToggle.setOnClickListener { v: View? ->
if (locationComponent != null) {
locationComponent!!.locationEngine =
if (locationComponent!!.locationEngine == null) locationEngine else null
if (locationComponent!!.locationEngine == null) {
fabToggle.setImageResource(R.drawable.ic_layers_clear)
fabManualUpdate.isEnabled = true
fabManualUpdate.alpha = 1f
Toast.makeText(
this@ManualLocationUpdatesActivity.applicationContext,
"LocationEngine disabled, use manual updates",
Toast.LENGTH_SHORT
).show()
} else {
fabToggle.setImageResource(R.drawable.ic_layers)
fabManualUpdate.isEnabled = false
fabManualUpdate.alpha = 0.5f
Toast.makeText(
this@ManualLocationUpdatesActivity.applicationContext,
"LocationEngine enabled",
Toast.LENGTH_SHORT
).show()
}
}
}
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
if (PermissionsManager.areLocationPermissionsGranted(this)) {
mapView.getMapAsync(this)
} else {
permissionsManager = PermissionsManager(object : PermissionsListener {
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
Toast.makeText(
this@ManualLocationUpdatesActivity.applicationContext,
"You need to accept location permissions.",
Toast.LENGTH_SHORT
).show()
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
mapView.getMapAsync(this@ManualLocationUpdatesActivity)
} else {
finish()
}
}
})
permissionsManager!!.requestLocationPermissions(this)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionsManager!!.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
@SuppressLint("MissingPermission")
override fun onMapReady(maplibreMap: MapLibreMap) {
maplibreMap.setStyle(
Style.Builder().fromUri(Style.getPredefinedStyle("Streets"))
) { style: Style? ->
locationComponent = maplibreMap.locationComponent
locationComponent!!.activateLocationComponent(
LocationComponentActivationOptions
.builder(this, style!!)
.locationEngine(locationEngine)
.locationEngineRequest(
LocationEngineRequest.Builder(500)
.setFastestInterval(500)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build()
)
.build()
)
locationComponent!!.isLocationComponentEnabled = true
locationComponent!!.renderMode = RenderMode.COMPASS
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}

View File

@@ -0,0 +1,52 @@
package org.maplibre.android.testapp.activity.location
import android.location.Location
import org.maplibre.android.geometry.LatLngBounds
import org.maplibre.android.maps.Style
import timber.log.Timber
import java.util.*
/**
* Useful utilities used throughout the test app.
*/
object Utils {
private val STYLES = arrayOf(
Style.getPredefinedStyle("Streets"),
Style.getPredefinedStyle("Outdoor"),
Style.getPredefinedStyle("Bright"),
Style.getPredefinedStyle("Pastel"),
Style.getPredefinedStyle("Satellite Hybrid")
)
private var index = 0
/**
* Utility to cycle through map styles. Useful to test if runtime styling source and layers transfer over to new
* style.
*
* @return a string ID representing the map style
*/
fun nextStyle(): String {
index++
if (index == STYLES.size) {
index = 0
}
return STYLES[index]
}
/**
* Utility for getting a random coordinate inside a provided bounds and creates a [Location] from it.
*
* @param bounds bounds of the generated location
* @return a [Location] object using the random coordinate
*/
fun getRandomLocation(bounds: LatLngBounds): Location {
val random = Random()
val randomLat = bounds.latitudeSouth + (bounds.latitudeNorth - bounds.latitudeSouth) * random.nextDouble()
val randomLon = bounds.longitudeWest + (bounds.longitudeEast - bounds.longitudeWest) * random.nextDouble()
val location = Location("random-loc")
location.longitude = randomLon
location.latitude = randomLat
Timber.d("getRandomLatLng: %s", location.toString())
return location
}
}

View File

@@ -0,0 +1,273 @@
package org.maplibre.android.testapp.activity.maplayout
import android.content.Context
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.google.android.material.bottomsheet.BottomSheetBehavior
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.*
import org.maplibre.android.testapp.R
import org.maplibre.android.utils.MapFragmentUtils
/**
* Test activity showcasing using a bottomView with a MapView and stacking map fragments below.
*/
class BottomSheetActivity : AppCompatActivity() {
private var bottomSheetFragmentAdded = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bottom_sheet)
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
findViewById<View>(R.id.fabFragment).setOnClickListener { v: View? -> addMapFragment() }
findViewById<View>(R.id.fabBottomSheet).setOnClickListener { v: View? -> toggleBottomSheetMapFragment() }
val bottomSheetBehavior: BottomSheetBehavior<*> =
BottomSheetBehavior.from(findViewById<View>(R.id.bottom_sheet))
bottomSheetBehavior.peekHeight = (64 * resources.displayMetrics.density).toInt()
bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
toggleBottomSheetMapFragment()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
val fragmentManager = supportFragmentManager
if (fragmentManager.backStackEntryCount > 0) {
fragmentManager.popBackStack()
} else {
super.onBackPressed()
}
}
private fun addMapFragment() {
val fragmentManager = supportFragmentManager
val fragmentCount = fragmentManager.backStackEntryCount
val fragmentTransaction = fragmentManager.beginTransaction()
val mainMapFragment = MainMapFragment.newInstance(this, fragmentCount)
if (fragmentCount == 0) {
fragmentTransaction.add(R.id.fragment_container, mainMapFragment, TAG_MAIN_FRAGMENT)
} else {
fragmentTransaction.replace(R.id.fragment_container, mainMapFragment, TAG_MAIN_FRAGMENT)
}
fragmentTransaction.addToBackStack(mainMapFragment.hashCode().toString())
fragmentTransaction.commit()
Toast.makeText(
applicationContext,
String.format(AMOUNT_OF_MAIN_MAP_FRAGMENTS, fragmentCount + 1),
Toast.LENGTH_SHORT
).show()
}
private fun toggleBottomSheetMapFragment() {
if (!bottomSheetFragmentAdded) {
addBottomSheetMapFragment()
} else {
removeBottomSheetFragment()
}
bottomSheetFragmentAdded = !bottomSheetFragmentAdded
}
private fun addBottomSheetMapFragment() {
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.add(
R.id.fragment_container_bottom,
BottomSheetFragment.newInstance(this),
TAG_BOTTOM_FRAGMENT
)
fragmentTransaction.commit()
}
private fun removeBottomSheetFragment() {
val fragment = supportFragmentManager.findFragmentByTag(TAG_BOTTOM_FRAGMENT)
if (fragment != null) {
supportFragmentManager.beginTransaction().remove(fragment).commit()
}
}
class MainMapFragment : Fragment(), OnMapReadyCallback {
private var map: MapView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
val context = inflater.context
return MapView(context, MapFragmentUtils.resolveArgs(context, arguments)).also {
map = it
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
map!!.onCreate(savedInstanceState)
map!!.getMapAsync(this)
}
override fun onMapReady(maplibreMap: MapLibreMap) {
maplibreMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(37.760545, -122.436055),
15.0
)
)
maplibreMap.setStyle(
Style.Builder().fromUri(
STYLES[
Math.min(
Math.max(arguments!!.getInt("mapcounter"), 0),
STYLES.size - 1
)
]
)
)
}
override fun onStart() {
super.onStart()
map!!.onStart()
}
override fun onResume() {
super.onResume()
map!!.onResume()
}
override fun onPause() {
super.onPause()
map!!.onPause()
}
override fun onStop() {
super.onStop()
map!!.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
map!!.onSaveInstanceState(outState)
}
override fun onLowMemory() {
super.onLowMemory()
map!!.onLowMemory()
}
override fun onDestroyView() {
super.onDestroyView()
map!!.onDestroy()
}
companion object {
private val STYLES = arrayOf(
Style.getPredefinedStyle("Streets"),
Style.getPredefinedStyle("Satellite Hybrid"),
Style.getPredefinedStyle("Bright"),
Style.getPredefinedStyle("Pastel"),
Style.getPredefinedStyle("Satellite Hybrid"),
Style.getPredefinedStyle("Outdoor")
)
fun newInstance(context: Context?, mapCounter: Int): MainMapFragment {
val mapFragment = MainMapFragment()
val bundle = Bundle()
bundle.putInt("mapcounter", mapCounter)
mapFragment.arguments = bundle
val maplibreMapOptions = MapLibreMapOptions.createFromAttributes(context!!)
mapFragment.arguments = MapFragmentUtils.createFragmentArgs(maplibreMapOptions)
return mapFragment
}
}
}
class BottomSheetFragment : Fragment(), OnMapReadyCallback {
private var map: MapView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
val context = inflater.context
return MapView(context, MapFragmentUtils.resolveArgs(context, arguments)).also {
map = it
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
map!!.onCreate(savedInstanceState)
map!!.getMapAsync(this)
}
override fun onMapReady(maplibreMap: MapLibreMap) {
maplibreMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(37.760545, -122.436055),
15.0
)
)
maplibreMap.setStyle(Style.getPredefinedStyle("Bright"))
}
override fun onStart() {
super.onStart()
map!!.onStart()
}
override fun onResume() {
super.onResume()
map!!.onResume()
}
override fun onPause() {
super.onPause()
map!!.onPause()
}
override fun onStop() {
super.onStop()
map!!.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
map!!.onSaveInstanceState(outState)
}
override fun onLowMemory() {
super.onLowMemory()
map!!.onLowMemory()
}
override fun onDestroyView() {
super.onDestroyView()
map!!.onDestroy()
}
companion object {
fun newInstance(context: Context?): BottomSheetFragment {
val mapFragment = BottomSheetFragment()
val maplibreMapOptions = MapLibreMapOptions.createFromAttributes(context!!)
maplibreMapOptions.renderSurfaceOnTop(true)
mapFragment.arguments = MapFragmentUtils.createFragmentArgs(maplibreMapOptions)
return mapFragment
}
}
}
companion object {
private const val TAG_MAIN_FRAGMENT = "com.mapbox.mapboxsdk.fragment.tag.main"
private const val TAG_BOTTOM_FRAGMENT = "com.mapbox.mapboxsdk.fragment.tag.bottom"
private const val AMOUNT_OF_MAIN_MAP_FRAGMENTS = "Amount of main map fragments: %s"
}
}

View File

@@ -0,0 +1,269 @@
package org.maplibre.android.testapp.activity.maplayout
import android.content.Context
import android.os.Bundle
import android.view.*
import android.widget.*
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.floatingactionbutton.FloatingActionButton
import org.maplibre.android.maps.*
import org.maplibre.android.maps.MapLibreMap.OnCameraMoveListener
import org.maplibre.android.maps.MapLibreMap.OnFpsChangedListener
import org.maplibre.android.style.layers.Layer
import org.maplibre.android.style.layers.Property
import org.maplibre.android.style.layers.PropertyFactory
import org.maplibre.android.testapp.R
import timber.log.Timber
import java.util.*
/**
* Test activity showcasing the different debug modes and allows to cycle between the default map styles.
*/
open class DebugModeActivity : AppCompatActivity(), OnMapReadyCallback, OnFpsChangedListener {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private var cameraMoveListener: OnCameraMoveListener? = null
private var actionBarDrawerToggle: ActionBarDrawerToggle? = null
private var currentStyleIndex = 0
private var isReportFps = true
private var fpsView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_debug_mode)
setupToolbar()
setupMapView(savedInstanceState)
setupDebugChangeView()
setupStyleChangeView()
}
private fun setupToolbar() {
val actionBar = supportActionBar
if (actionBar != null) {
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setHomeButtonEnabled(true)
val drawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout)
actionBarDrawerToggle = ActionBarDrawerToggle(
this,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
actionBarDrawerToggle!!.isDrawerIndicatorEnabled = true
actionBarDrawerToggle!!.syncState()
}
}
private fun setupMapView(savedInstanceState: Bundle?) {
val mapboxMapOptions = setupMapboxMapOptions()
mapView = MapView(this, mapboxMapOptions)
(findViewById<View>(R.id.coordinator_layout) as ViewGroup).addView(mapView, 0)
mapView.addOnDidFinishLoadingStyleListener {
if (maplibreMap != null) {
setupNavigationView(maplibreMap.style!!.layers)
}
}
mapView.tag = true
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
mapView.addOnDidFinishLoadingStyleListener { Timber.d("Style loaded") }
}
protected open fun setupMapboxMapOptions(): MapLibreMapOptions {
return MapLibreMapOptions.createFromAttributes(this, null)
}
override fun onMapReady(map: MapLibreMap) {
maplibreMap = map
maplibreMap.setStyle(
Style.Builder().fromUri(STYLES[currentStyleIndex])
) { style: Style -> setupNavigationView(style.layers) }
setupZoomView()
setFpsView()
}
private fun setFpsView() {
fpsView = findViewById(R.id.fpsView)
maplibreMap.setOnFpsChangedListener(this)
}
override fun onFpsChanged(fps: Double) {
fpsView!!.text = String.format(Locale.US, "FPS: %4.2f", fps)
}
private fun setupNavigationView(layerList: List<Layer>) {
Timber.v("New style loaded with JSON: %s", maplibreMap.style!!.json)
val adapter = LayerListAdapter(this, layerList)
val listView = findViewById<ListView>(R.id.listView)
listView.adapter = adapter
listView.onItemClickListener =
AdapterView.OnItemClickListener { parent: AdapterView<*>?, view: View?, position: Int, id: Long ->
val clickedLayer = adapter.getItem(position)
toggleLayerVisibility(clickedLayer)
closeNavigationView()
}
}
private fun toggleLayerVisibility(layer: Layer) {
val isVisible = layer.visibility.getValue() == Property.VISIBLE
layer.setProperties(
PropertyFactory.visibility(
if (isVisible) Property.NONE else Property.VISIBLE
)
)
}
private fun closeNavigationView() {
val drawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout)
drawerLayout.closeDrawers()
}
private fun setupZoomView() {
val textView = findViewById<TextView>(R.id.textZoom)
maplibreMap.addOnCameraMoveListener(
OnCameraMoveListener {
textView.text = String.format(
this@DebugModeActivity.getString(
R.string.debug_zoom
),
maplibreMap.cameraPosition.zoom
)
}.also { cameraMoveListener = it }
)
}
private fun setupDebugChangeView() {
val fabDebug = findViewById<FloatingActionButton>(R.id.fabDebug)
fabDebug.setOnClickListener { view: View? ->
if (maplibreMap != null) {
maplibreMap.isDebugActive = !maplibreMap.isDebugActive
Timber.d("Debug FAB: isDebug Active? %s", maplibreMap.isDebugActive)
}
}
}
private fun setupStyleChangeView() {
val fabStyles = findViewById<FloatingActionButton>(R.id.fabStyles)
fabStyles.setOnClickListener { view: View? ->
if (maplibreMap != null) {
currentStyleIndex++
if (currentStyleIndex == STYLES.size) {
currentStyleIndex = 0
}
maplibreMap.setStyle(Style.Builder().fromUri(STYLES[currentStyleIndex]))
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val itemId = item.itemId
if (itemId == R.id.menu_action_toggle_report_fps) {
isReportFps = !isReportFps
fpsView!!.visibility = if (isReportFps) View.VISIBLE else View.GONE
maplibreMap.setOnFpsChangedListener(if (isReportFps) this else null)
} else if (itemId == R.id.menu_action_limit_to_30_fps) {
mapView.setMaximumFps(30)
} else if (itemId == R.id.menu_action_limit_to_60_fps) {
mapView.setMaximumFps(60)
}
return actionBarDrawerToggle!!.onOptionsItemSelected(item) || super.onOptionsItemSelected(
item
)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_debug, menu)
return true
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
if (maplibreMap != null) {
maplibreMap.removeOnCameraMoveListener(cameraMoveListener!!)
}
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
private class LayerListAdapter(context: Context?, layers: List<Layer>) :
BaseAdapter() {
private val layoutInflater: LayoutInflater
private val layers: List<Layer>
override fun getCount(): Int {
return layers.size
}
override fun getItem(position: Int): Layer {
return layers[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val layer = layers[position]
var view = convertView
if (view == null) {
view = layoutInflater.inflate(android.R.layout.simple_list_item_2, parent, false)
val holder = ViewHolder(
view.findViewById(android.R.id.text1),
view.findViewById(android.R.id.text2)
)
view.tag = holder
}
val holder = view!!.tag as ViewHolder
holder.text.text = layer.javaClass.simpleName
holder.subText.text = layer.id
return view
}
private class ViewHolder(val text: TextView, val subText: TextView)
init {
layoutInflater = LayoutInflater.from(context)
this.layers = layers
}
}
companion object {
private val STYLES = arrayOf(
Style.getPredefinedStyle("Streets"),
Style.getPredefinedStyle("Outdoor"),
Style.getPredefinedStyle("Bright"),
Style.getPredefinedStyle("Pastel"),
Style.getPredefinedStyle("Satellite Hybrid"),
Style.getPredefinedStyle("Satellite Hybrid")
)
}
}

View File

@@ -0,0 +1,157 @@
package org.maplibre.android.testapp.activity.maplayout
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.*
import org.maplibre.android.testapp.R
import org.maplibre.android.utils.MapFragmentUtils
/**
* Test activity showcasing having 2 maps on top of each other.
*
*
* The small map is using the `maplibre_enableZMediaOverlay="true"` configuration
*
*/
class DoubleMapActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_fragment)
if (savedInstanceState == null) {
val options = MapLibreMapOptions.createFromAttributes(this, null)
options.camera(
CameraPosition.Builder()
.target(MACHU_PICCHU)
.zoom(ZOOM_IN)
.build()
)
val doubleMapFragment = DoubleMapFragment()
doubleMapFragment.arguments = MapFragmentUtils.createFragmentArgs(options)
val transaction = supportFragmentManager.beginTransaction()
transaction.add(R.id.fragment_container, doubleMapFragment, TAG_FRAGMENT)
transaction.commit()
}
}
/**
* Custom fragment containing 2 MapViews.
*/
class DoubleMapFragment : Fragment() {
private lateinit var mapView: MapView
private lateinit var mapViewMini: MapView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_double_map, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// MapView large
mapView = MapView(view.context, MapFragmentUtils.resolveArgs(view.context, arguments))
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { maplibreMap: MapLibreMap ->
maplibreMap.setStyle(
Style.getPredefinedStyle(
"Streets"
)
)
}
(view.findViewById<View>(R.id.container) as ViewGroup).addView(mapView, 0)
// MapView mini
mapViewMini = view.findViewById(R.id.mini_map)
mapViewMini.onCreate(savedInstanceState)
mapViewMini.getMapAsync(
OnMapReadyCallback { maplibreMap: MapLibreMap ->
maplibreMap.moveCamera(
CameraUpdateFactory.newCameraPosition(
CameraPosition.Builder().target(MACHU_PICCHU)
.zoom(ZOOM_OUT)
.build()
)
)
maplibreMap.setStyle(Style.Builder().fromUri(Style.getPredefinedStyle("Bright")))
val uiSettings = maplibreMap.uiSettings
uiSettings.setAllGesturesEnabled(false)
uiSettings.isCompassEnabled = false
uiSettings.isAttributionEnabled = false
uiSettings.isLogoEnabled = false
maplibreMap.addOnMapClickListener { point: LatLng? ->
// test if we can open 2 activities after each other
Toast.makeText(
mapViewMini.getContext(),
"Creating a new Activity instance",
Toast.LENGTH_SHORT
).show()
startActivity(Intent(mapViewMini.getContext(), DoubleMapActivity::class.java))
false
}
}
)
}
override fun onResume() {
super.onResume()
mapView.onResume()
mapViewMini!!.onResume()
}
override fun onStart() {
super.onStart()
mapView.onStart()
mapViewMini!!.onStart()
}
override fun onPause() {
super.onPause()
mapView.onPause()
mapViewMini!!.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
mapViewMini!!.onStop()
}
override fun onDestroyView() {
super.onDestroyView()
mapView.onDestroy()
mapViewMini!!.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
mapViewMini!!.onLowMemory()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
// Mini map view is not interactive in this case, so we shouldn't save the instance.
// If we'd like to support state saving for both maps, they'd have to be kept in separate fragments.
// mapViewMini.onSaveInstanceState(outState);
}
}
companion object {
private const val TAG_FRAGMENT = "map"
private val MACHU_PICCHU = LatLng(-13.1650709, -72.5447154)
private const val ZOOM_IN = 12.0
private const val ZOOM_OUT = 4.0
}
}

View File

@@ -0,0 +1,160 @@
package org.maplibre.android.testapp.activity.maplayout
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.databinding.ActivityRecyclerviewBinding
/**
* TestActivity showcasing how to integrate multiple GLSurfaceView MapViews in a RecyclerView.
* <p>
* It requires calling the correct lifecycle methods when detaching and attaching the View to
* the RecyclerView with onViewAttachedToWindow and onViewDetachedFromWindow.
* </p>
*/
@SuppressLint("ClickableViewAccessibility")
open class GLSurfaceRecyclerViewActivity : AppCompatActivity() {
lateinit var binding: ActivityRecyclerviewBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRecyclerviewBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
binding.recyclerView.adapter = ItemAdapter(this, LayoutInflater.from(this))
}
override fun onLowMemory() {
super.onLowMemory()
// to release memory, we need to call MapView#onLowMemory
(binding.recyclerView.adapter as ItemAdapter).onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
// to perform cleanup, we need to call MapView#onDestroy
(binding.recyclerView.adapter as ItemAdapter).onDestroy()
}
open fun getMapItemLayoutId(): Int {
return R.layout.item_map_gl
}
class ItemAdapter(private val activity: GLSurfaceRecyclerViewActivity, private val inflater: LayoutInflater) : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {
private val items = listOf(
"one", "two", "three", MapItem(Style.getPredefinedStyle("Streets")), "four", "five", MapItem(Style.getPredefinedStyle("Pastel")), "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen", "twenty", "twenty-one"
)
private var mapHolders: MutableList<MapHolder> = mutableListOf()
companion object {
const val TYPE_MAP = 0
const val TYPE_TEXT = 1
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
return if (viewType == TYPE_MAP) {
val mapView = inflater.inflate(activity.getMapItemLayoutId(), parent, false) as MapView
val mapHolder = MapHolder(mapView)
mapHolders.add(mapHolder)
return mapHolder
} else {
TextHolder(inflater.inflate(android.R.layout.simple_list_item_1, parent, false) as TextView)
}
}
override fun onViewAttachedToWindow(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder) {
super.onViewAttachedToWindow(holder)
if (holder is MapHolder) {
val mapView = holder.mapView
mapView.isEnabled = false
mapView.onStart()
mapView.onResume()
}
}
override fun onViewDetachedFromWindow(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder) {
super.onViewDetachedFromWindow(holder)
if (holder is MapHolder) {
val mapView = holder.mapView
mapView.onPause()
mapView.onStop()
}
}
override fun getItemCount(): Int {
return items.count()
}
override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
if (holder is TextHolder) {
holder.bind(items[position] as String)
} else if (holder is MapHolder) {
holder.bind(items[position] as MapItem)
}
}
override fun getItemViewType(position: Int): Int {
return if (items[position] is MapItem) {
TYPE_MAP
} else {
TYPE_TEXT
}
}
fun onLowMemory() {
for (mapHolder in mapHolders) {
mapHolder.mapView.onLowMemory()
}
}
fun onDestroy() {
for (mapHolder in mapHolders) {
mapHolder.mapView.let {
it.onPause()
it.onStop()
it.onDestroy()
}
}
}
data class MapItem(val style: String)
class MapHolder(val mapView: MapView) : androidx.recyclerview.widget.RecyclerView.ViewHolder(mapView) {
init {
// unfortunately, if there are multiple maps hosted in one activity, state saving is not possible
mapView.onCreate(null)
mapView.setOnTouchListener { view, motionEvent ->
// Disallow the touch request for recyclerView scroll
view.parent.requestDisallowInterceptTouchEvent(true)
mapView.onTouchEvent(motionEvent)
true
}
}
fun bind(mapItem: MapItem) {
mapView.getMapAsync { mapboxMap ->
mapboxMap.setStyle(mapItem.style) {
mapboxMap.snapshot { }
}
}
}
}
class TextHolder(val textView: TextView) : androidx.recyclerview.widget.RecyclerView.ViewHolder(textView) {
fun bind(item: String) {
textView.text = item
}
}
}
}

View File

@@ -0,0 +1,135 @@
package org.maplibre.android.testapp.activity.maplayout
import android.graphics.Color
import android.os.Bundle
import android.view.*
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.annotations.PolygonOptions
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.geometry.LatLngBounds
import org.maplibre.android.maps.*
import org.maplibre.android.testapp.R
/**
* Test activity showcasing restricting user gestures to a bounds around Iceland, almost worldview and IDL.
*/
class LatLngBoundsForCameraActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_restricted_bounds)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
}
override fun onMapReady(maplibreMap: MapLibreMap) {
this.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Satellite Hybrid"))
maplibreMap.setMinZoomPreference(2.0)
maplibreMap.uiSettings.isFlingVelocityAnimationEnabled = false
showCrosshair()
setupBounds(ICELAND_BOUNDS)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_bounds, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_action_allmost_world_bounds -> {
setupBounds(ALMOST_WORLD_BOUNDS)
return true
}
R.id.menu_action_cross_idl -> {
setupBounds(CROSS_IDL_BOUNDS)
return true
}
R.id.menu_action_reset -> {
setupBounds(null)
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun setupBounds(bounds: LatLngBounds?) {
maplibreMap.setLatLngBoundsForCameraTarget(bounds)
showBoundsArea(bounds)
}
private fun showBoundsArea(bounds: LatLngBounds?) {
maplibreMap.clear()
if (bounds != null) {
val boundsArea = PolygonOptions()
.add(bounds.northWest)
.add(bounds.northEast)
.add(bounds.southEast)
.add(bounds.southWest)
boundsArea.alpha(0.25f)
boundsArea.fillColor(Color.RED)
maplibreMap.addPolygon(boundsArea)
}
}
private fun showCrosshair() {
val crosshair = View(this)
crosshair.layoutParams = FrameLayout.LayoutParams(10, 10, Gravity.CENTER)
crosshair.setBackgroundColor(Color.BLUE)
mapView.addView(crosshair)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
companion object {
private val ICELAND_BOUNDS = LatLngBounds.Builder()
.include(LatLng(66.852863, -25.985652))
.include(LatLng(62.985661, -12.626277))
.build()
private val ALMOST_WORLD_BOUNDS = LatLngBounds.Builder()
.include(LatLng(20.0, 170.0))
.include(LatLng((-20).toDouble(), -170.0))
.build()
private val CROSS_IDL_BOUNDS = LatLngBounds.Builder()
.include(LatLng(20.0, 170.0))
.include(LatLng((-20).toDouble(), 190.0))
.build()
}
}

View File

@@ -0,0 +1,74 @@
package org.maplibre.android.testapp.activity.maplayout
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.*
import org.maplibre.android.testapp.R
/**
* Test activity that displays the city of Suzhou with a mixture of server-generated
* latin glyphs and CJK glyphs generated locally using "Droid Sans" as a font family.
*/
class LocalGlyphActivity : AppCompatActivity() {
private lateinit var mapView: MapView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_local_glyph)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { maplibreMap: MapLibreMap ->
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
// Set initial position to Suzhou
maplibreMap.moveCamera(
CameraUpdateFactory.newCameraPosition(
CameraPosition.Builder()
.target(LatLng(31.3003, 120.7457))
.zoom(11.0)
.bearing(0.0)
.tilt(0.0)
.build()
)
)
}
)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
}

View File

@@ -0,0 +1,137 @@
package org.maplibre.android.testapp.activity.maplayout
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.*
import org.maplibre.android.maps.MapView.OnCameraDidChangeListener
import org.maplibre.android.maps.MapView.OnCameraIsChangingListener
import org.maplibre.android.maps.MapView.OnCameraWillChangeListener
import org.maplibre.android.maps.MapView.OnDidBecomeIdleListener
import org.maplibre.android.maps.MapView.OnDidFailLoadingMapListener
import org.maplibre.android.maps.MapView.OnDidFinishLoadingMapListener
import org.maplibre.android.maps.MapView.OnDidFinishLoadingStyleListener
import org.maplibre.android.maps.MapView.OnDidFinishRenderingFrameListener
import org.maplibre.android.maps.MapView.OnDidFinishRenderingMapListener
import org.maplibre.android.maps.MapView.OnSourceChangedListener
import org.maplibre.android.maps.MapView.OnWillStartLoadingMapListener
import org.maplibre.android.maps.MapView.OnWillStartRenderingFrameListener
import org.maplibre.android.maps.MapView.OnWillStartRenderingMapListener
import org.maplibre.android.testapp.R
import timber.log.Timber
/**
* Test activity showcasing how to listen to map change events.
*/
class MapChangeActivity : AppCompatActivity() {
private lateinit var mapView: MapView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_simple)
mapView = findViewById(R.id.mapView)
mapView.addOnCameraIsChangingListener(OnCameraIsChangingListener { Timber.v("OnCameraIsChanging") })
mapView.addOnCameraDidChangeListener(
OnCameraDidChangeListener { animated: Boolean ->
Timber.v(
"OnCamaraDidChange: animated: %s",
animated
)
}
)
mapView.addOnCameraWillChangeListener(
OnCameraWillChangeListener { animated: Boolean ->
Timber.v(
"OnCameraWilChange: animated: %s",
animated
)
}
)
mapView.addOnDidFailLoadingMapListener(
OnDidFailLoadingMapListener { errorMessage: String? ->
Timber.v(
"OnDidFailLoadingMap: %s",
errorMessage
)
}
)
mapView.addOnDidFinishLoadingMapListener(OnDidFinishLoadingMapListener { Timber.v("OnDidFinishLoadingMap") })
mapView.addOnDidFinishLoadingStyleListener(OnDidFinishLoadingStyleListener { Timber.v("OnDidFinishLoadingStyle") })
mapView.addOnDidFinishRenderingFrameListener(
OnDidFinishRenderingFrameListener { fully: Boolean, frameEncodingTime: Double, frameRenderingTime: Double ->
Timber.v(
"OnDidFinishRenderingFrame: fully: %s",
fully
)
}
)
mapView.addOnDidFinishRenderingMapListener(
OnDidFinishRenderingMapListener { fully: Boolean ->
Timber.v(
"OnDidFinishRenderingMap: fully: %s",
fully
)
}
)
mapView.addOnDidBecomeIdleListener(OnDidBecomeIdleListener { Timber.v("OnDidBecomeIdle") })
mapView.addOnSourceChangedListener(
OnSourceChangedListener { sourceId: String? ->
Timber.v(
"OnSourceChangedListener: source with id: %s",
sourceId
)
}
)
mapView.addOnWillStartLoadingMapListener(OnWillStartLoadingMapListener { Timber.v("OnWillStartLoadingMap") })
mapView.addOnWillStartRenderingFrameListener(OnWillStartRenderingFrameListener { Timber.v("OnWillStartRenderingFrame") })
mapView.addOnWillStartRenderingMapListener(OnWillStartRenderingMapListener { Timber.v("OnWillStartRenderingMap") })
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { maplibreMap: MapLibreMap ->
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
maplibreMap.animateCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(55.754020, 37.620948),
12.0
),
9000
)
}
)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
}

View File

@@ -0,0 +1,100 @@
package org.maplibre.android.testapp.activity.maplayout
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import org.maplibre.android.maps.*
import org.maplibre.android.testapp.R
/**
* Test activity showcasing showing a Map inside of a DialogFragment.
*/
class MapInDialogActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_in_dialog)
val button = findViewById<Button>(R.id.button_open_dialog)
button.setOnClickListener { view: View? ->
val fm = supportFragmentManager
val editNameDialogFragment = MapDialogFragment.newInstance("Map Dialog")
editNameDialogFragment.show(fm, "fragment_dialog_map")
}
}
class MapDialogFragment : DialogFragment() {
private lateinit var mapView: MapView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_dialog_map, container)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mapView = view.findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { maplibreMap: MapLibreMap ->
maplibreMap.setStyle(
Style.getPredefinedStyle("Outdoor")
)
}
)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onDestroyView() {
super.onDestroyView()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
if (mapView != null) {
mapView.onLowMemory()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (mapView != null) {
mapView.onSaveInstanceState(outState)
}
}
companion object {
fun newInstance(title: String?): MapDialogFragment {
val frag = MapDialogFragment()
val args = Bundle()
args.putString("title", title)
frag.arguments = args
return frag
}
}
}
}

View File

@@ -0,0 +1,107 @@
package org.maplibre.android.testapp.activity.maplayout
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.annotations.MarkerOptions
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.*
import org.maplibre.android.testapp.R
/**
* Test activity showcasing using the map padding API.
*/
class MapPaddingActivity : AppCompatActivity() {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_padding)
mapView = findViewById(R.id.mapView)
mapView.setTag(true)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { maplibreMap: MapLibreMap ->
this@MapPaddingActivity.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
val paddingLeft = resources.getDimension(R.dimen.map_padding_left).toInt()
val paddingBottom = resources.getDimension(R.dimen.map_padding_bottom).toInt()
val paddingRight = resources.getDimension(R.dimen.map_padding_right).toInt()
val paddingTop = resources.getDimension(R.dimen.map_padding_top).toInt()
maplibreMap.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom)
val settings = maplibreMap.uiSettings
settings.setLogoMargins(paddingLeft, 0, 0, paddingBottom)
settings.setCompassMargins(0, paddingTop, paddingRight, 0)
settings.isAttributionEnabled = false
moveToBangalore()
}
)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_padding, menu)
return true
}
private fun moveToBangalore() {
val bangalore = LatLng(12.9810816, 77.6368034)
val cameraPosition = CameraPosition.Builder()
.zoom(16.0)
.target(bangalore)
.bearing(40.0)
.tilt(45.0)
.build()
maplibreMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
maplibreMap.addMarker(MarkerOptions().title("Center map").position(bangalore))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_bangalore -> {
if (maplibreMap != null) {
moveToBangalore()
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
}

View File

@@ -0,0 +1,95 @@
package org.maplibre.android.testapp.activity.maplayout
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.os.PersistableBundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.Style
import org.maplibre.android.testapp.databinding.ActivityOverlayBinding
/**
* Test overlaying a Map with a View that uses a radial gradient shader.
*/
class OverlayMapActivity : AppCompatActivity() {
private lateinit var binding: ActivityOverlayBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityOverlayBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.mapView.onCreate(savedInstanceState)
binding.parentView.addView(OverlayView(this))
binding.mapView.getMapAsync {
it.setStyle(Style.getPredefinedStyle("Streets"))
}
}
override fun onStart() {
super.onStart()
binding.mapView.onStart()
}
override fun onResume() {
super.onResume()
binding.mapView.onResume()
}
override fun onPause() {
super.onPause()
binding.mapView.onPause()
}
override fun onStop() {
super.onStop()
binding.mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
binding.mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
binding.mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
super.onSaveInstanceState(outState, outPersistentState)
outState.let {
binding.mapView.onSaveInstanceState(it)
}
}
class OverlayView(context: Context) : View(context) {
private lateinit var paint: Paint
@SuppressLint("DrawAllocation") // only happens once
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.let {
if (!::paint.isInitialized) {
paint = Paint()
paint.color = Color.BLACK
paint.strokeWidth = 1.0f
paint.style = Paint.Style.FILL_AND_STROKE
paint.shader = RadialGradient(
width / 2.0f,
height / 2.0f,
height / 3.0f,
Color.TRANSPARENT,
Color.BLACK,
Shader.TileMode.CLAMP
)
}
it.drawRect(0.0f, 0.0f, width.toFloat(), height.toFloat(), paint)
}
}
}
}

View File

@@ -0,0 +1,89 @@
package org.maplibre.android.testapp.activity.maplayout
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.*
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.ApiKeyUtils
import org.maplibre.android.testapp.utils.NavUtils
/**
* Test activity showcasing a simple MapView without any MapLibreMap interaction.
*/
class SimpleMapActivity : AppCompatActivity() {
private lateinit var mapView: MapView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_simple)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { maplibreMap: MapLibreMap ->
var key = ApiKeyUtils.getApiKey(applicationContext)
if (key == null || key == "YOUR_API_KEY_GOES_HERE") {
maplibreMap.setStyle(Style.Builder().fromUri("https://demotiles.maplibre.org/style.json"))
} else {
val styles = Style.getPredefinedStyles()
if (styles != null && styles.size > 0) {
val styleUrl = styles[0].url
maplibreMap.setStyle(Style.Builder().fromUri(styleUrl))
}
}
}
)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
NavUtils.navigateHome(this)
}
}

View File

@@ -0,0 +1,15 @@
package org.maplibre.android.testapp.activity.maplayout
import android.annotation.SuppressLint
import org.maplibre.android.testapp.R
/**
* TestActivity showcasing how to integrate multiple TexureView MapViews in a RecyclerView.
*/
@SuppressLint("ClickableViewAccessibility")
class TextureRecyclerViewActivity : GLSurfaceRecyclerViewActivity() {
override fun getMapItemLayoutId(): Int {
return R.layout.item_map_texture
}
}

View File

@@ -0,0 +1,128 @@
package org.maplibre.android.testapp.activity.maplayout
import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.*
import org.maplibre.android.testapp.R
/**
* Test activity showcasing visibility changes to the mapview.
*/
class VisibilityChangeActivity : AppCompatActivity() {
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private val handler = Handler()
private var runnable: Runnable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_visibility)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(
OnMapReadyCallback { map: MapLibreMap? ->
if (map != null) {
maplibreMap = map
}
maplibreMap.setStyle(Style.getPredefinedStyle("Streets"))
maplibreMap.animateCamera(
CameraUpdateFactory.newLatLngZoom(
LatLng(55.754020, 37.620948),
12.0
),
9000
)
}
)
}
override fun onStart() {
super.onStart()
mapView.onStart()
handler.post(
VisibilityRunner(
mapView,
findViewById(R.id.viewParent),
handler
).also { runnable = it }
)
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
private class VisibilityRunner internal constructor(
private val mapView: MapView?,
private val viewParent: View?,
private val handler: Handler
) : Runnable {
private var currentStep = 0
override fun run() {
if (isViewHiearchyReady) {
if (isEvenStep) {
viewParent!!.visibility = View.VISIBLE
mapView?.visibility = View.VISIBLE
} else if (isFirstOrThirdStep) {
mapView?.visibility = visibilityForStep
} else if (isFifthOrSeventhStep) {
viewParent!!.visibility = visibilityForStep
}
updateStep()
}
handler.postDelayed(this, 1500)
}
private fun updateStep() {
if (currentStep == 7) {
currentStep = 0
} else {
currentStep++
}
}
private val visibilityForStep: Int
get() = if (currentStep == 1 || currentStep == 5) View.GONE else View.INVISIBLE
private val isFifthOrSeventhStep: Boolean
get() = currentStep == 5 || currentStep == 7
private val isFirstOrThirdStep: Boolean
get() = currentStep == 1 || currentStep == 3
private val isEvenStep: Boolean
get() = currentStep == 0 || currentStep % 2 == 0
private val isViewHiearchyReady: Boolean
get() = mapView != null && viewParent != null
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
runnable?.let {
handler.removeCallbacks(it)
runnable = null
}
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
}

View File

@@ -0,0 +1,159 @@
package org.maplibre.android.testapp.activity.offline
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.BaseAdapter
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.log.Logger
import org.maplibre.android.offline.OfflineManager
import org.maplibre.android.offline.OfflineRegion
import org.maplibre.android.storage.FileSource
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.databinding.ActivityChangeResourcesCachePathBinding
import java.io.File
class ChangeResourcesCachePathActivity :
AppCompatActivity(),
AdapterView.OnItemClickListener,
FileSource.ResourcesCachePathChangeCallback {
companion object {
private const val TAG = "Mbgl-ChangeResourcesCachePathActivity"
}
private lateinit var binding: ActivityChangeResourcesCachePathBinding
private lateinit var adapter: PathAdapter
private lateinit var offlineManager: OfflineManager
private val callback = PathChangeCallback(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityChangeResourcesCachePathBinding.inflate(layoutInflater)
setContentView(binding.root)
adapter = PathAdapter(this, obtainExternalFilesPaths())
binding.listView.adapter = adapter
binding.listView.emptyView = binding.empty
binding.listView.onItemClickListener = this
offlineManager = OfflineManager.getInstance(this)
}
override fun onStart() {
super.onStart()
val path: String? = FileSource.getResourcesCachePath(this)
Toast.makeText(this, "Current path: $path", Toast.LENGTH_LONG).show()
}
override fun onDestroy() {
super.onDestroy()
callback.onActivityDestroy()
}
override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
binding.listView.onItemClickListener = null
val path: String = adapter.getItem(position) as String
FileSource.setResourcesCachePath(path, callback)
}
override fun onError(message: String) {
binding.listView.onItemClickListener = this
Toast.makeText(this, "Error: $message", Toast.LENGTH_LONG).show()
}
override fun onSuccess(path: String) {
binding.listView.onItemClickListener = this
Toast.makeText(this, "New path: $path", Toast.LENGTH_LONG).show()
offlineManager.listOfflineRegions(object : OfflineManager.ListOfflineRegionsCallback {
override fun onList(offlineRegions: Array<OfflineRegion>?) {
Logger.i(TAG, "Number of saved offline regions in the new path: ${offlineRegions?.size}")
}
override fun onError(error: String) {
Logger.e(TAG, error)
}
})
}
private fun Context.obtainExternalFilesPaths(): List<String> {
val paths = ArrayList<String>()
paths.add(this.filesDir.absolutePath)
paths.addAll(obtainExternalFilesPathsKitKat())
paths.add("${File.separator}invalid${File.separator}cache${File.separator}path")
return paths
}
private fun Context.obtainExternalFilesPathsKitKat(): List<String> {
val paths = ArrayList<String>()
val extDirs = this.getExternalFilesDirs(null)
for (dir in extDirs) {
if (dir != null) {
paths.add(dir.absolutePath)
}
}
return paths
}
private class PathChangeCallback(private var activity: ChangeResourcesCachePathActivity?) : FileSource.ResourcesCachePathChangeCallback {
override fun onSuccess(path: String) {
activity?.onSuccess(path)
}
override fun onError(message: String) {
activity?.onError(message)
}
fun onActivityDestroy() {
activity = null
}
}
class PathAdapter(private val context: Context, private val paths: List<String>) : BaseAdapter() {
override fun getItem(position: Int): Any {
return paths[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return paths.size
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val viewHolder: ViewHolder
val view: View
if (convertView == null) {
viewHolder = ViewHolder()
view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false)
viewHolder.textView = view.findViewById(android.R.id.text1)
view?.tag = viewHolder
} else {
view = convertView
viewHolder = view.tag as ViewHolder
}
viewHolder.textView?.text = paths[position]
return view
}
class ViewHolder {
var textView: TextView? = null
}
}
}

View File

@@ -0,0 +1,164 @@
package org.maplibre.android.testapp.activity.offline
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.offline.OfflineManager
import org.maplibre.android.offline.OfflineManager.ListOfflineRegionsCallback
import org.maplibre.android.offline.OfflineRegion
import org.maplibre.android.offline.OfflineRegion.OfflineRegionDeleteCallback
import org.maplibre.android.offline.OfflineRegion.OfflineRegionInvalidateCallback
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.activity.offline.DeleteRegionActivity.OfflineRegionAdapter
import org.maplibre.android.testapp.utils.OfflineUtils
import java.util.*
/**
* Test activity showing integration of deleting an OfflineRegion.
*/
class DeleteRegionActivity :
AppCompatActivity(),
AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener {
private var adapter: OfflineRegionAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_offline_region_delete)
val listView = findViewById<ListView>(R.id.listView)
listView.adapter = OfflineRegionAdapter(this).also { adapter = it }
listView.emptyView = findViewById(android.R.id.empty)
listView.onItemClickListener = this
listView.onItemLongClickListener = this
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
val region = adapter!!.getItem(position)
val metadata = OfflineUtils.convertRegionName(region.metadata)
val builder = AlertDialog.Builder(this)
builder.setTitle("Delete region")
val input = TextView(this)
input.text = metadata
builder.setView(input)
builder.setPositiveButton("OK") { dialog: DialogInterface?, which: Int -> delete(region) }
builder.setNegativeButton("Cancel") { dialog: DialogInterface, which: Int -> dialog.cancel() }
builder.show()
}
override fun onItemLongClick(
parent: AdapterView<*>?,
view: View,
position: Int,
id: Long
): Boolean {
val region = adapter!!.getItem(position)
region.invalidate(object : OfflineRegionInvalidateCallback {
override fun onInvalidate() {
Toast.makeText(
this@DeleteRegionActivity,
"Invalidate region success",
Toast.LENGTH_SHORT
).show()
}
override fun onError(error: String) {
Toast.makeText(this@DeleteRegionActivity, "Error:$error", Toast.LENGTH_LONG).show()
}
})
return true
}
private fun delete(region: OfflineRegion) {
region.delete(object : OfflineRegionDeleteCallback {
override fun onDelete() {
Toast.makeText(
this@DeleteRegionActivity,
"Region deleted",
Toast.LENGTH_SHORT
).show()
loadOfflineRegions()
}
override fun onError(error: String) {
Toast.makeText(
this@DeleteRegionActivity,
"Region deletion failed with $error",
Toast.LENGTH_LONG
).show()
}
})
}
override fun onStart() {
super.onStart()
loadOfflineRegions()
}
private fun loadOfflineRegions() {
OfflineManager.getInstance(this).listOfflineRegions(object : ListOfflineRegionsCallback {
override fun onList(offlineRegions: Array<OfflineRegion>?) {
if (offlineRegions != null && offlineRegions.isNotEmpty()) {
adapter!!.setOfflineRegions(Arrays.asList(*offlineRegions))
}
}
override fun onError(error: String) {
Toast.makeText(
this@DeleteRegionActivity,
"Error loading regions $error",
Toast.LENGTH_LONG
).show()
}
})
}
private class OfflineRegionAdapter internal constructor(private val context: Context) :
BaseAdapter() {
private var offlineRegions: List<OfflineRegion>
fun setOfflineRegions(offlineRegions: List<OfflineRegion>) {
this.offlineRegions = offlineRegions
notifyDataSetChanged()
}
override fun getCount(): Int {
return offlineRegions.size
}
override fun getItem(position: Int): OfflineRegion {
return offlineRegions[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
val holder: ViewHolder
if (convertView == null) {
holder = ViewHolder()
convertView = LayoutInflater.from(context)
.inflate(android.R.layout.simple_list_item_1, parent, false)
holder.text = convertView.findViewById<View>(android.R.id.text1) as TextView
convertView.tag = holder
} else {
holder = convertView.tag as ViewHolder
}
holder.text!!.text = OfflineUtils.convertRegionName(getItem(position).metadata)
return convertView!!
}
internal class ViewHolder {
var text: TextView? = null
}
init {
offlineRegions = ArrayList()
}
}
}

View File

@@ -0,0 +1,330 @@
package org.maplibre.android.testapp.activity.offline
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.ArrayAdapter
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.constants.MapLibreConstants
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.geometry.LatLngBounds
import org.maplibre.android.maps.Style
import org.maplibre.android.offline.*
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.databinding.ActivityRegionDownloadBinding
import timber.log.Timber
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Example showcasing how to download an offline region headless, allows to test pausing and resuming the download.
*/
class DownloadRegionActivity : AppCompatActivity(), OfflineRegion.OfflineRegionObserver {
companion object {
const val STATUS_UPDATE_TIMEOUT_MS = 10_000L
}
private val handler: Handler = Handler()
private lateinit var offlineManager: OfflineManager
private lateinit var binding: ActivityRegionDownloadBinding
private var offlineRegion: OfflineRegion? = null
private var downloading = false
private var previousCompletedResourceCount: Long = 0
private var previousUpdateTimestamp: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRegionDownloadBinding.inflate(layoutInflater)
setContentView(binding.root)
offlineManager = OfflineManager.getInstance(this)
offlineManager.setOfflineMapboxTileCountLimit(Long.MAX_VALUE)
initUi()
deleteOldOfflineRegions {
binding.container.visibility = View.VISIBLE
binding.fab.visibility = View.VISIBLE
}
}
override fun onDestroy() {
handler.removeCallbacksAndMessages(null)
offlineRegion?.setObserver(null)
super.onDestroy()
}
private fun createOfflineRegion() {
val latitudeNorth = binding.editTextLatNorth.text.toString().toDouble()
val longitudeEast = binding.editTextLonEast.text.toString().toDouble()
val latitudeSouth = binding.editTextLatSouth.text.toString().toDouble()
val longitudeWest = binding.editTextLonWest.text.toString().toDouble()
val styleUrl = binding.spinnerStyleUrl.selectedItem as String
val maxZoom = binding.seekbarMaxZoom.progress.toFloat()
val minZoom = binding.seekbarMinZoom.progress.toFloat()
if (!validCoordinates(latitudeNorth, longitudeEast, latitudeSouth, longitudeWest)) {
Toast.makeText(this, "coordinates need to be in valid range", Toast.LENGTH_LONG).show()
return
}
// create offline definition from data
val definition = OfflineTilePyramidRegionDefinition(
styleUrl,
LatLngBounds.Builder()
.include(LatLng(latitudeNorth, longitudeEast))
.include(LatLng(latitudeSouth, longitudeWest))
.build(),
minZoom.toDouble(),
maxZoom.toDouble(),
resources.displayMetrics.density
)
logMessage("Creating offline region")
offlineManager.createOfflineRegion(
definition,
byteArrayOf(),
object : OfflineManager.CreateOfflineRegionCallback {
override fun onCreate(offlineRegion: OfflineRegion) {
logMessage("Region with id ${offlineRegion.id} created")
this@DownloadRegionActivity.offlineRegion = offlineRegion
startDownload(offlineRegion)
binding.fab.visibility = View.VISIBLE
}
override fun onError(error: String) {
logMessage("Failed to create offline region: $error")
}
}
)
}
private fun startDownload(region: OfflineRegion) {
downloading = true
binding.fab.setImageResource(R.drawable.ic_pause_black_24dp)
logMessage("Downloading...")
region.setObserver(this)
region.setDownloadState(OfflineRegion.STATE_ACTIVE)
previousUpdateTimestamp = System.currentTimeMillis()
handler.postDelayed(
object : Runnable {
override fun run() {
if (System.currentTimeMillis() > previousUpdateTimestamp + STATUS_UPDATE_TIMEOUT_MS) {
logMessage("FAILURE! No progress in ${TimeUnit.MILLISECONDS.toSeconds(STATUS_UPDATE_TIMEOUT_MS)} seconds")
} else {
handler.postDelayed(this, 1000)
}
}
},
1000
)
}
private fun pauseDownload(region: OfflineRegion) {
downloading = false
binding.fab.setImageResource(R.drawable.ic_play_arrow_black_24dp)
handler.removeCallbacksAndMessages(null)
region.setDownloadState(OfflineRegion.STATE_INACTIVE)
"Paused".let {
logMessage(it)
binding.downloadStatus.text = it
}
}
override fun onStatusChanged(status: OfflineRegionStatus) {
if (status.isComplete) {
"Completed".let {
logMessage("SUCCESS! $it")
binding.downloadStatus.text = it
}
binding.fab.setImageResource(R.drawable.ic_play_arrow_black_24dp)
handler.removeCallbacksAndMessages(null)
offlineRegion?.setObserver(null)
offlineRegion?.setDownloadState(OfflineRegion.STATE_INACTIVE)
} else {
val statusText = "Downloaded ${status.completedResourceCount}/${status.requiredResourceCount}"
statusText.let {
logMessage(it)
binding.downloadStatus.text = it
}
if (status.completedResourceCount > status.requiredResourceCount &&
previousCompletedResourceCount <= status.requiredResourceCount
) {
logMessage("FAILURE! Completed > required")
}
}
previousCompletedResourceCount = status.completedResourceCount
previousUpdateTimestamp = System.currentTimeMillis()
}
override fun onError(error: OfflineRegionError) {
logMessage("Error: $error")
}
override fun mapboxTileCountLimitExceeded(limit: Long) {
logMessage("Error: tile count limit exceeded")
}
protected fun logMessage(message: String) {
Timber.d(message)
logView.append(message)
logView.append("\n")
}
fun deleteOldOfflineRegions(onCompleted: () -> Unit) {
offlineManager.listOfflineRegions(object : OfflineManager.ListOfflineRegionsCallback {
override fun onList(offlineRegions: Array<OfflineRegion>?) {
val count = offlineRegions?.size ?: 0
var remainingCount = count
if (count > 0) {
logMessage("Deleting $count old region...")
offlineRegions?.forEach {
it.delete(object : OfflineRegion.OfflineRegionDeleteCallback {
override fun onDelete() {
Timber.d("Deleted region with id ${it.id}")
onProcessed()
}
override fun onError(error: String) {
Timber.e("Failed to delete region: $error")
onProcessed()
}
private fun onProcessed() {
remainingCount--
if (remainingCount == 0) {
logMessage("Done deleting")
onCompleted()
}
}
})
}
} else {
onCompleted()
}
}
override fun onError(error: String) {
logMessage("Failed to list offline regions: $error")
onCompleted()
}
})
}
// ui
private val logView: TextView by lazy {
findViewById<TextView>(R.id.log_text)
}
private fun initUi() {
initEditTexts()
initSeekbars()
initSpinner()
initZoomLevelTextviews()
initSeekbarListeners()
initFab()
}
@SuppressLint("SetTextI18n")
private fun initEditTexts() {
binding.editTextLatNorth.setText("62.0")
binding.editTextLonEast.setText("24.0")
binding.editTextLatSouth.setText("60.0")
binding.editTextLonWest.setText("22.5")
}
private fun initSeekbars() {
val maxZoom = MapLibreConstants.MAXIMUM_ZOOM.toInt()
binding.seekbarMinZoom.max = maxZoom
binding.seekbarMinZoom.progress = 1
binding.seekbarMaxZoom.max = maxZoom
binding.seekbarMaxZoom.progress = 15
}
private fun initSpinner() {
val styles = ArrayList<String>()
styles.add(Style.getPredefinedStyle("Streets"))
styles.add(Style.getPredefinedStyle("Pastel"))
styles.add(Style.getPredefinedStyle("Bright"))
styles.add(Style.getPredefinedStyle("Outdoor"))
val spinnerArrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, styles)
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.spinnerStyleUrl.adapter = spinnerArrayAdapter
}
private fun initZoomLevelTextviews() {
binding.textViewMaxText.text = String.format("Max zoom: %s", binding.seekbarMaxZoom.progress)
binding.textViewMinText.text = String.format("Min zoom: %s", binding.seekbarMinZoom.progress)
}
private fun initFab() {
binding.fab.setOnClickListener {
binding.container.visibility = View.GONE
if (offlineRegion == null) {
binding.fab.visibility = View.GONE
createOfflineRegion()
} else {
offlineRegion?.let {
if (downloading) {
pauseDownload(it)
} else {
startDownload(it)
}
}
}
}
}
private fun initSeekbarListeners() {
binding.seekbarMaxZoom.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
binding.textViewMaxText.text = String.format("Max zoom: %s", progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
})
binding.seekbarMinZoom.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
binding.textViewMinText.text = String.format("Min zoom: %s", progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
})
}
private fun validCoordinates(
latitudeNorth: Double,
longitudeEast: Double,
latitudeSouth: Double,
longitudeWest: Double
): Boolean {
if (latitudeNorth < -90 || latitudeNorth > 90) {
return false
} else if (longitudeEast < -180 || longitudeEast > 180) {
return false
} else if (latitudeSouth < -90 || latitudeSouth > 90) {
return false
} else if (longitudeWest < -180 || longitudeWest > 180) {
return false
}
return true
}
}

View File

@@ -0,0 +1,155 @@
package org.maplibre.android.testapp.activity.offline
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.MapLibre
import org.maplibre.android.log.Logger
import org.maplibre.android.maps.Style
import org.maplibre.android.offline.OfflineManager
import org.maplibre.android.offline.OfflineRegion
import org.maplibre.android.storage.FileSource
import org.maplibre.android.testapp.databinding.ActivityMergeOfflineRegionsBinding
import org.maplibre.android.testapp.utils.FileUtils
class MergeOfflineRegionsActivity : AppCompatActivity() {
private lateinit var binding: ActivityMergeOfflineRegionsBinding
companion object {
private const val LOG_TAG = "Mbgl-MergeOfflineRegionsActivity"
private const val TEST_DB_FILE_NAME = "offline_test.db"
private var TEST_STYLE = Style.getPredefinedStyle("Satellite Hybrid")
}
private val onFileCopiedListener = object : FileUtils.OnFileCopiedFromAssetsListener {
override fun onFileCopiedFromAssets() {
Toast.makeText(
this@MergeOfflineRegionsActivity,
String.format("OnFileCopied."),
Toast.LENGTH_LONG
).show()
mergeDb()
}
override fun onError() {
Toast.makeText(
this@MergeOfflineRegionsActivity,
String.format("Error copying DB file."),
Toast.LENGTH_LONG
).show()
}
}
private val onRegionMergedListener = object : OfflineManager.MergeOfflineRegionsCallback {
override fun onMerge(offlineRegions: Array<OfflineRegion>?) {
binding.mapView.getMapAsync {
it.setStyle(Style.Builder().fromUri(TEST_STYLE))
}
Toast.makeText(
this@MergeOfflineRegionsActivity,
String.format("Merged %d regions.", offlineRegions?.size ?: 0),
Toast.LENGTH_LONG
).show()
}
override fun onError(error: String) {
Toast.makeText(
this@MergeOfflineRegionsActivity,
String.format("Offline DB merge error."),
Toast.LENGTH_LONG
).show()
Logger.e(LOG_TAG, error)
}
}
/**
* Since we expect from the results of the offline merge callback to interact with the hosting activity,
* we need to ensure that we are not interacting with a destroyed activity.
*/
private class MergeCallback(private var activityCallback: OfflineManager.MergeOfflineRegionsCallback?) : OfflineManager.MergeOfflineRegionsCallback {
override fun onMerge(offlineRegions: Array<OfflineRegion>?) {
activityCallback?.onMerge(offlineRegions)
}
override fun onError(error: String) {
activityCallback?.onError(error)
}
fun onActivityDestroy() {
activityCallback = null
}
}
private val mergeCallback = MergeCallback(onRegionMergedListener)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMergeOfflineRegionsBinding.inflate(layoutInflater)
setContentView(binding.root)
// forcing offline state
MapLibre.setConnected(false)
binding.mapView.onCreate(savedInstanceState)
binding.loadRegionBtn.setOnClickListener {
copyAsset()
}
binding.mapView.getMapAsync {
it.isDebugActive = true
it.setStyle(Style.Builder().fromUri(TEST_STYLE))
}
}
private fun copyAsset() {
// copy db asset to internal memory
FileUtils.CopyFileFromAssetsTask(this, onFileCopiedListener).execute(TEST_DB_FILE_NAME, FileSource.getResourcesCachePath(this))
}
private fun mergeDb() {
OfflineManager.getInstance(this).mergeOfflineRegions(
FileSource.getResourcesCachePath(this) + "/" + TEST_DB_FILE_NAME,
mergeCallback
)
}
override fun onStart() {
super.onStart()
binding.mapView.onStart()
}
override fun onResume() {
super.onResume()
binding.mapView.onResume()
}
override fun onPause() {
super.onPause()
binding.mapView.onPause()
}
override fun onStop() {
super.onStop()
binding.mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
binding.mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mergeCallback.onActivityDestroy()
binding.mapView.onDestroy()
// restoring connectivity state
MapLibre.setConnected(null)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
binding.mapView.onSaveInstanceState(outState)
}
}

View File

@@ -0,0 +1,319 @@
package org.maplibre.android.testapp.activity.offline
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.MapLibre
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.camera.CameraUpdateFactory
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.offline.OfflineManager
import org.maplibre.android.offline.OfflineManager.CreateOfflineRegionCallback
import org.maplibre.android.offline.OfflineManager.ListOfflineRegionsCallback
import org.maplibre.android.offline.OfflineRegion
import org.maplibre.android.offline.OfflineRegion.OfflineRegionObserver
import org.maplibre.android.offline.OfflineRegionError
import org.maplibre.android.offline.OfflineRegionStatus
import org.maplibre.android.offline.OfflineTilePyramidRegionDefinition
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.model.other.OfflineDownloadRegionDialog
import org.maplibre.android.testapp.model.other.OfflineDownloadRegionDialog.DownloadRegionDialogListener
import org.maplibre.android.testapp.model.other.OfflineListRegionsDialog
import org.maplibre.android.testapp.utils.OfflineUtils
import timber.log.Timber
import java.util.ArrayList
/**
* Test activity showcasing the Offline API.
*
*
* Shows a map of Manhattan and allows the user to download and name a region.
*
*/
class OfflineActivity : AppCompatActivity(), DownloadRegionDialogListener {
/*
* UI elements
*/
private lateinit var mapView: MapView
private lateinit var maplibreMap: MapLibreMap
private var progressBar: ProgressBar? = null
private var downloadRegion: Button? = null
private var listRegions: Button? = null
private var isEndNotified = false
/*
* Offline objects
*/
private var offlineManager: OfflineManager? = null
private var offlineRegion: OfflineRegion? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_offline)
// You can use MapLibre.setConnected(Boolean) to manually set the connectivity
// state of your app. This will override any checks performed via the ConnectivityManager.
// MapLibre.getInstance().setConnected(false);
val connected = MapLibre.isConnected()
Timber.d("MapLibre is connected: %s", connected)
// Set up map
mapView = findViewById<View>(R.id.mapView) as MapView
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { maplibreMap: MapLibreMap ->
Timber.d("Map is ready")
this@OfflineActivity.maplibreMap = maplibreMap
maplibreMap.setStyle(Style.Builder().fromUri(STYLE_URL))
// Set initial position to UNHQ in NYC
maplibreMap.moveCamera(
CameraUpdateFactory.newCameraPosition(
CameraPosition.Builder()
.target(LatLng(40.749851, -73.967966))
.zoom(14.0)
.bearing(0.0)
.tilt(0.0)
.build()
)
)
}
// The progress bar
progressBar = findViewById<View>(R.id.progress_bar) as ProgressBar
// Set up button listeners
downloadRegion = findViewById<View>(R.id.button_download_region) as Button
downloadRegion!!.setOnClickListener { view: View? -> handleDownloadRegion() }
listRegions = findViewById<View>(R.id.button_list_regions) as Button
listRegions!!.setOnClickListener { view: View? -> handleListRegions() }
// Set up the OfflineManager
offlineManager = OfflineManager.getInstance(this)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
/*
* Buttons logic
*/
private fun handleDownloadRegion() {
Timber.d("handleDownloadRegion")
// Show dialog
val offlineDownloadRegionDialog = OfflineDownloadRegionDialog()
offlineDownloadRegionDialog.show(supportFragmentManager, "download")
}
private fun handleListRegions() {
Timber.d("handleListRegions")
// Query the DB asynchronously
offlineManager!!.listOfflineRegions(object : ListOfflineRegionsCallback {
override fun onList(offlineRegions: Array<OfflineRegion>?) {
// Check result
if (offlineRegions == null || offlineRegions.isEmpty()) {
Toast.makeText(
this@OfflineActivity,
"You have no regions yet.",
Toast.LENGTH_SHORT
).show()
return
}
// Get regions info
val offlineRegionsNames = ArrayList<String>()
for (offlineRegion in offlineRegions) {
offlineRegionsNames.add(OfflineUtils.convertRegionName(offlineRegion.metadata))
}
// Create args
val args = Bundle()
args.putStringArrayList(OfflineListRegionsDialog.ITEMS, offlineRegionsNames)
// Show dialog
val offlineListRegionsDialog = OfflineListRegionsDialog()
offlineListRegionsDialog.arguments = args
offlineListRegionsDialog.show(supportFragmentManager, "list")
}
override fun onError(error: String) {
Timber.e("Error: %s", error)
}
})
}
/*
* Dialogs
*/
override fun onDownloadRegionDialogPositiveClick(regionName: String?) {
if (TextUtils.isEmpty(regionName)) {
Toast.makeText(this@OfflineActivity, "Region name cannot be empty.", Toast.LENGTH_SHORT)
.show()
return
}
// Start progress bar
Timber.d("Download started: %s", regionName)
startProgress()
// Definition
val bounds = maplibreMap.projection.visibleRegion.latLngBounds
val minZoom = maplibreMap.cameraPosition.zoom
val maxZoom = maplibreMap.maxZoomLevel
val pixelRatio = this.resources.displayMetrics.density
val definition = OfflineTilePyramidRegionDefinition(
STYLE_URL,
bounds,
minZoom,
maxZoom,
pixelRatio
)
// Sample way of encoding metadata from a JSONObject
val metadata = OfflineUtils.convertRegionName(regionName)
// Create region
if (metadata != null) {
offlineManager!!.createOfflineRegion(
definition,
metadata,
object : CreateOfflineRegionCallback {
override fun onCreate(offlineRegion: OfflineRegion) {
Timber.d("Offline region created: %s", regionName)
this@OfflineActivity.offlineRegion = offlineRegion
launchDownload()
}
override fun onError(error: String) {
Timber.e("Error: %s", error)
}
}
)
}
}
private fun launchDownload() {
// Set an observer
offlineRegion!!.setObserver(object : OfflineRegionObserver {
override fun onStatusChanged(status: OfflineRegionStatus) {
// Compute a percentage
val percentage =
if (status.requiredResourceCount >= 0) 100.0 * status.completedResourceCount / status.requiredResourceCount else 0.0
if (status.isComplete) {
// Download complete
endProgress("Region downloaded successfully.")
offlineRegion!!.setDownloadState(OfflineRegion.STATE_INACTIVE)
offlineRegion!!.setObserver(null)
return
} else if (status.isRequiredResourceCountPrecise) {
// Switch to determinate state
setPercentage(Math.round(percentage).toInt())
}
// Debug
Timber.d(
"%s/%s resources; %s bytes downloaded.",
status.completedResourceCount.toString(),
status.requiredResourceCount.toString(),
status.completedResourceSize.toString()
)
}
override fun onError(error: OfflineRegionError) {
Timber.e("onError: %s, %s", error.reason, error.message)
offlineRegion!!.setDownloadState(OfflineRegion.STATE_INACTIVE)
}
override fun mapboxTileCountLimitExceeded(limit: Long) {
Timber.e("MapLibre tile count limit exceeded: %s", limit)
offlineRegion!!.setDownloadState(OfflineRegion.STATE_INACTIVE)
}
})
// Change the region state
offlineRegion!!.setDownloadState(OfflineRegion.STATE_ACTIVE)
}
/*
* Progress bar
*/
private fun startProgress() {
// Disable buttons
downloadRegion!!.isEnabled = false
listRegions!!.isEnabled = false
// Start and show the progress bar
isEndNotified = false
progressBar!!.isIndeterminate = true
progressBar!!.visibility = View.VISIBLE
}
private fun setPercentage(percentage: Int) {
progressBar!!.isIndeterminate = false
progressBar!!.progress = percentage
}
private fun endProgress(message: String) {
// Don't notify more than once
if (isEndNotified) {
return
}
// Enable buttons
downloadRegion!!.isEnabled = true
listRegions!!.isEnabled = true
// Stop and hide the progress bar
isEndNotified = true
progressBar!!.isIndeterminate = false
progressBar!!.visibility = View.GONE
// Show a toast
Toast.makeText(this@OfflineActivity, message, Toast.LENGTH_LONG).show()
}
companion object {
// JSON encoding/decoding
val JSON_CHARSET = Charsets.UTF_8
const val JSON_FIELD_REGION_NAME = "FIELD_REGION_NAME"
// Style URL
val STYLE_URL = Style.getPredefinedStyle("Streets")
}
}

View File

@@ -0,0 +1,183 @@
package org.maplibre.android.testapp.activity.offline
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.maps.MapView
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.offline.OfflineManager
import org.maplibre.android.offline.OfflineManager.ListOfflineRegionsCallback
import org.maplibre.android.offline.OfflineRegion
import org.maplibre.android.offline.OfflineRegion.OfflineRegionUpdateMetadataCallback
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.OfflineUtils
import java.util.*
/**
* Test activity showing integration of updating metadata of an OfflineRegion.
*/
class UpdateMetadataActivity :
AppCompatActivity(),
AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener {
private var adapter: OfflineRegionMetadataAdapter? = null
private lateinit var mapView: MapView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_metadata_update)
val listView = findViewById<ListView>(R.id.listView)
listView.adapter = OfflineRegionMetadataAdapter(this).also { adapter = it }
listView.emptyView = findViewById(android.R.id.empty)
listView.onItemClickListener = this
listView.onItemLongClickListener = this
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
val region = adapter!!.getItem(position)
val metadata = OfflineUtils.convertRegionName(region.metadata)
val builder = AlertDialog.Builder(this)
builder.setTitle("Rename metadata")
val input = EditText(this)
input.setText(metadata)
input.inputType = InputType.TYPE_CLASS_TEXT
if (metadata != null) {
input.setSelection(metadata.length)
}
builder.setView(input)
builder.setPositiveButton(
"OK"
) { dialog: DialogInterface?, which: Int ->
OfflineUtils.convertRegionName(input.text.toString())?.let {
updateMetadata(
region,
it
)
}
}
builder.setNegativeButton("Cancel") { dialog: DialogInterface, which: Int -> dialog.cancel() }
builder.show()
}
override fun onItemLongClick(
parent: AdapterView<*>?,
view: View,
position: Int,
id: Long
): Boolean {
val container = findViewById<ViewGroup>(R.id.container)
container.removeAllViews()
container.addView(MapView(view.context).also { mapView = it })
mapView.onCreate(null)
mapView.getMapAsync { map: MapLibreMap ->
map.setOfflineRegionDefinition(
adapter!!.getItem(position).definition
)
}
mapView.onStart()
mapView.onResume()
return true
}
private fun updateMetadata(region: OfflineRegion, metadata: ByteArray) {
region.updateMetadata(
metadata,
object : OfflineRegionUpdateMetadataCallback {
override fun onUpdate(metadata: ByteArray) {
adapter!!.notifyDataSetChanged()
}
override fun onError(error: String) {
Toast.makeText(
this@UpdateMetadataActivity,
"Region metadata update failed with $error",
Toast.LENGTH_LONG
).show()
}
}
)
}
override fun onStart() {
super.onStart()
loadOfflineRegions()
}
private fun loadOfflineRegions() {
OfflineManager.getInstance(this).listOfflineRegions(object : ListOfflineRegionsCallback {
override fun onList(offlineRegions: Array<OfflineRegion>?) {
if (offlineRegions != null && offlineRegions.size > 0) {
adapter!!.setOfflineRegions(Arrays.asList(*offlineRegions))
}
}
override fun onError(error: String) {
Toast.makeText(
this@UpdateMetadataActivity,
"Error loading regions $error",
Toast.LENGTH_LONG
).show()
}
})
}
override fun onDestroy() {
super.onDestroy()
if (mapView != null) {
mapView.onPause()
mapView.onStop()
mapView.onDestroy()
}
}
private class OfflineRegionMetadataAdapter(private val context: Context) :
BaseAdapter() {
private var offlineRegions: List<OfflineRegion>
fun setOfflineRegions(offlineRegions: List<OfflineRegion>) {
this.offlineRegions = offlineRegions
notifyDataSetChanged()
}
override fun getCount(): Int {
return offlineRegions.size
}
override fun getItem(position: Int): OfflineRegion {
return offlineRegions[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertViewParam: View?, parent: ViewGroup): View {
var convertView = convertViewParam
val holder: ViewHolder
if (convertView == null) {
holder = ViewHolder()
convertView = LayoutInflater.from(context)
.inflate(android.R.layout.simple_list_item_1, parent, false)
holder.text = convertView.findViewById<View>(android.R.id.text1) as TextView
convertView.tag = holder
} else {
holder = convertView.tag as ViewHolder
}
holder.text!!.text = OfflineUtils.convertRegionName(getItem(position).metadata)
return convertView!!
}
internal class ViewHolder {
var text: TextView? = null
}
init {
offlineRegions = ArrayList()
}
}
}

View File

@@ -0,0 +1,380 @@
package org.maplibre.android.testapp.activity.render
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.os.AsyncTask
import android.os.Bundle
import android.os.Environment
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.JsonObject
import org.maplibre.android.snapshotter.MapSnapshot
import org.maplibre.android.snapshotter.MapSnapshotter
import okio.buffer
import okio.source
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.lang.ref.WeakReference
import java.nio.charset.Charset
/**
* Activity that generates map snapshots based on the node render test suite.
*/
class RenderTestActivity : AppCompatActivity() {
private val renderResultMap: MutableMap<RenderTestDefinition, Bitmap> = HashMap()
private var renderTestDefinitions: List<RenderTestDefinition>? = null
private var onRenderTestCompletionListener: OnRenderTestCompletionListener? = null
private lateinit var mapSnapshotter: MapSnapshotter
private var imageView: ImageView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(ImageView(this@RenderTestActivity).also { imageView = it })
imageView!!.layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER
)
}
override fun onStop() {
super.onStop()
if (mapSnapshotter != null) {
mapSnapshotter!!.cancel()
}
}
//
// Loads the ignore tests from assets folder
//
private class LoadRenderIgnoreTask internal constructor(renderTestActivity: RenderTestActivity?) :
AsyncTask<Void?, Void?, List<String>>() {
private val renderTestActivityWeakReference: WeakReference<RenderTestActivity?>
protected override fun doInBackground(vararg p0: Void?): List<String>? {
return loadIgnoreList(
renderTestActivityWeakReference.get()!!.assets
)
}
override fun onPostExecute(strings: List<String>) {
super.onPostExecute(strings)
if (renderTestActivityWeakReference.get() != null) {
renderTestActivityWeakReference.get()!!.onLoadIgnoreList(strings)
}
}
init {
renderTestActivityWeakReference = WeakReference(renderTestActivity)
}
}
//
// Loads the render test definitions from assets folder
//
private class LoadRenderDefinitionTask internal constructor(renderTestActivity: RenderTestActivity) :
AsyncTask<Void?, Void?, List<RenderTestDefinition>>() {
private val renderTestActivityWeakReference: WeakReference<RenderTestActivity>
protected override fun doInBackground(vararg p0: Void?): List<RenderTestDefinition>? {
val definitions: MutableList<RenderTestDefinition> = ArrayList()
val assetManager = renderTestActivityWeakReference.get()!!.assets
val categories =
try {
assetManager.list(RENDER_TEST_BASE_PATH)
} catch (exception: IOException) {
Timber.e(exception)
throw exception
}
for (counter in categories!!.indices.reversed()) {
try {
val tests = assetManager.list(
String.format(
"%s/%s",
RENDER_TEST_BASE_PATH,
categories[counter]
)
)
for (test in tests!!) {
val styleJson = loadStyleJson(assetManager, categories[counter], test)
val renderTestStyleDefinition = Gson()
.fromJson(styleJson, RenderTestStyleDefinition::class.java)
val definition = RenderTestDefinition(
categories[counter],
test,
styleJson,
renderTestStyleDefinition
)
if (!definition.hasOperations()) {
if (!EXCLUDED_TESTS.contains(definition.name + "," + definition.category)) {
definitions.add(definition)
}
} else {
Timber.e(
"could not add test, test requires operations: %s from %s",
test,
categories[counter]
)
}
}
} catch (exception: Exception) {
Timber.e(exception)
}
}
return definitions
}
override fun onPostExecute(renderTestDefinitions: List<RenderTestDefinition>) {
super.onPostExecute(renderTestDefinitions)
val renderTestActivity = renderTestActivityWeakReference.get()
renderTestActivity?.startRenderTests(renderTestDefinitions)
}
init {
renderTestActivityWeakReference = WeakReference(renderTestActivity)
}
}
private fun startRenderTests(renderTestDefinitions: List<RenderTestDefinition>) {
this.renderTestDefinitions = renderTestDefinitions
if (!renderTestDefinitions.isEmpty()) {
render(renderTestDefinitions[0], renderTestDefinitions.size)
} else {
// no definitions, finish test without rendering
onRenderTestCompletionListener!!.onFinish()
}
}
private fun render(renderTestDefinition: RenderTestDefinition, testSize: Int) {
Timber.d("Render test %s,%s", renderTestDefinition.name, renderTestDefinition.category)
mapSnapshotter = RenderTestSnapshotter(this, renderTestDefinition.toOptions())
mapSnapshotter.start(
object : MapSnapshotter.SnapshotReadyCallback {
override fun onSnapshotReady(snapshot: MapSnapshot) {
imageView!!.setImageBitmap(snapshot.bitmap)
renderResultMap[renderTestDefinition] = snapshot.bitmap
if (renderResultMap.size != testSize) {
continueTesting(renderTestDefinition)
} else {
finishTesting()
}
}
},
object : MapSnapshotter.ErrorHandler {
override fun onError(error: String) {
Timber.e(error)
}
}
)
}
private fun continueTesting(renderTestDefinition: RenderTestDefinition) {
val next = renderTestDefinitions!!.indexOf(renderTestDefinition) + 1
Timber.d("Next test: %s / %s", next, renderTestDefinitions!!.size)
render(renderTestDefinitions!![next], renderTestDefinitions!!.size)
}
private fun finishTesting() {
SaveResultToDiskTask(onRenderTestCompletionListener, renderResultMap).execute()
}
//
// Save tests results to disk
//
private class SaveResultToDiskTask internal constructor(
private val onRenderTestCompletionListener: OnRenderTestCompletionListener?,
private val renderResultMap: Map<RenderTestDefinition, Bitmap>
) : AsyncTask<Void?, Void?, Void?>() {
protected override fun doInBackground(vararg p0: Void?): Void? {
if (isExternalStorageWritable) {
try {
val testResultDir = FileUtils.createTestResultRootFolder()
val basePath = testResultDir.absolutePath
for (testResult in renderResultMap.entries) {
writeResultToDisk(basePath, testResult)
}
} catch (exception: Exception) {
Timber.e(exception)
}
}
return null
}
private fun writeResultToDisk(
path: String,
result: Map.Entry<RenderTestDefinition, Bitmap>
) {
val definition = result.key
val categoryName = definition.category
val categoryPath = String.format("%s/%s", path, categoryName)
FileUtils.createCategoryDirectory(categoryPath)
val testName = result.key.name
val testDir = FileUtils.createTestDirectory(categoryPath, testName)
FileUtils.writeTestResultToDisk(testDir, result.value)
}
private val isExternalStorageWritable: Boolean
private get() = Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()
override fun onPostExecute(aVoid: Void?) {
super.onPostExecute(aVoid)
onRenderTestCompletionListener?.onFinish()
}
}
//
// Callback configuration to notify test executor of test finishing
//
interface OnRenderTestCompletionListener {
fun onFinish()
}
fun setOnRenderTestCompletionListener(listener: OnRenderTestCompletionListener?) {
onRenderTestCompletionListener = listener
LoadRenderIgnoreTask(this).execute()
}
fun onLoadIgnoreList(ignoreList: List<String>) {
Timber.e("We loaded %s of tests to be ignored", ignoreList.size)
EXCLUDED_TESTS.addAll(ignoreList)
LoadRenderDefinitionTask(this).execute()
}
//
// FileUtils
//
private object FileUtils {
fun createCategoryDirectory(catPath: String) {
val testResultDir = File(catPath)
if (testResultDir.exists()) {
return
}
if (!testResultDir.mkdirs()) {
throw RuntimeException("can't create root test directory")
}
}
fun createTestResultRootFolder(): File {
val testResultDir = File(
Environment.getExternalStorageDirectory()
.toString() + File.separator + "mapbox" + File.separator + "render"
)
if (testResultDir.exists()) {
// cleanup old files
deleteRecursive(testResultDir)
}
if (!testResultDir.mkdirs()) {
throw RuntimeException("can't create root test directory")
}
return testResultDir
}
private fun deleteRecursive(fileOrDirectory: File) {
if (fileOrDirectory.isDirectory) {
val files = fileOrDirectory.listFiles()
if (files != null) {
for (file in files) {
deleteRecursive(file)
}
}
}
if (!fileOrDirectory.delete()) {
Timber.e("can't delete directory")
}
}
fun createTestDirectory(basePath: String, testName: String?): String {
val testDir = File("$basePath/$testName")
if (!testDir.exists()) {
if (!testDir.mkdir()) {
throw RuntimeException("can't create sub directory for $testName")
}
}
return testDir.absolutePath
}
fun writeTestResultToDisk(testPath: String, testResult: Bitmap) {
val filePath = "$testPath/actual.png"
try {
FileOutputStream(filePath).use { out ->
testResult.compress(
Bitmap.CompressFormat.PNG,
100,
out
)
}
} catch (exception: IOException) {
Timber.e(exception)
}
}
}
companion object {
private const val TEST_BASE_PATH = "integration"
private const val RENDER_TEST_BASE_PATH = TEST_BASE_PATH + "/render-tests"
// We additionally read out excluded tests from `/platform/node/test/ignore.json`
private val EXCLUDED_TESTS: ArrayList<String?> = object : ArrayList<String?>() {
init {
add("overlay,background-opacity")
add("collision-lines-pitched,debug")
add("1024-circle,extent")
add("empty,empty")
add("rotation-alignment-map,icon-pitch-scaling")
add("rotation-alignment-viewport,icon-pitch-scaling")
add("pitch15,line-pitch")
add("pitch30,line-pitch")
add("line-placement-true-pitched,text-keep-upright")
add("180,raster-rotation")
add("45,raster-rotation")
add("90,raster-rotation")
add("overlapping,raster-masking")
add("missing,raster-loading")
add("pitchAndBearing,line-pitch")
add("overdraw,sparse-tileset")
}
}
private fun loadIgnoreList(assets: AssetManager): List<String> {
val ignores: MutableList<String> = ArrayList()
try {
assets.open(String.format("%s/ignores.json", TEST_BASE_PATH)).use { input ->
val source = input.source().buffer()
val styleJson = source.readByteString().string(Charset.forName("utf-8"))
val `object` = Gson().fromJson(styleJson, JsonObject::class.java)
for ((key) in `object`.entrySet()) {
val parts = key.split("/").toTypedArray()
ignores.add(String.format("%s,%s", parts[2], parts[1]))
}
}
} catch (exception: IOException) {
Timber.e(exception)
}
return ignores
}
private fun loadStyleJson(assets: AssetManager, category: String?, test: String): String? {
var styleJson: String? = null
try {
assets.open(
String.format(
"%s/%s/%s/style.json",
RENDER_TEST_BASE_PATH,
category,
test
)
).use { input ->
val source = input.source().buffer()
styleJson = source.readByteString().string(Charset.forName("utf-8"))
}
} catch (exception: IOException) {
Timber.e(exception)
}
return styleJson
}
}
}

View File

@@ -0,0 +1,74 @@
package org.maplibre.android.testapp.activity.render
import org.maplibre.android.maps.Style
import org.maplibre.android.snapshotter.MapSnapshotter
class RenderTestDefinition internal constructor( // eg. background-color
val category: String?, // eg. colorSpace-hcl
val name: String,
val styleJson: String?,
private val definition: RenderTestStyleDefinition
) {
val width: Int
get() {
val test = test
if (test != null) {
val testWidth = test.width
if (testWidth != null && testWidth > 0) {
return testWidth
}
}
return DEFAULT_WIDTH
}
val height: Int
get() {
val test = test
if (test != null) {
val testHeight = test.height
if (testHeight != null && testHeight > 0) {
return testHeight
}
}
return DEFAULT_HEIGHT
}
val pixelRatio: Float
get() {
val test = test
if (test != null) {
val pixelRatio = test.pixelRatio
if (pixelRatio != null && pixelRatio > 0) {
return pixelRatio
}
}
return 1F
}
fun hasOperations(): Boolean {
return test?.operations != null
}
val test: RenderTestStyleDefinition.Test?
get() = definition.metadata?.test
fun toOptions(): MapSnapshotter.Options {
return MapSnapshotter.Options(width, height)
.withStyleBuilder(Style.Builder().fromJson(styleJson!!))
.withPixelRatio(pixelRatio)
.withLogo(false)
}
override fun toString(): String {
return (
"RenderTestDefinition{" +
"category='" + category + '\'' +
", name='" + name + '\'' +
", styleJson='" + styleJson + '\'' +
'}'
)
}
companion object {
private const val DEFAULT_WIDTH = 512
private const val DEFAULT_HEIGHT = 512
}
}

View File

@@ -0,0 +1,12 @@
package org.maplibre.android.testapp.activity.render
import android.content.Context
import org.maplibre.android.snapshotter.MapSnapshot
import org.maplibre.android.snapshotter.MapSnapshotter
class RenderTestSnapshotter internal constructor(context: Context, options: Options) :
MapSnapshotter(context, options) {
override fun addOverlay(mapSnapshot: MapSnapshot) {
// don't add an overlay
}
}

View File

@@ -0,0 +1,46 @@
package org.maplibre.android.testapp.activity.render
import java.util.HashMap
class RenderTestStyleDefinition {
var version: Int? = null
var metadata: Metadata? = null
private val additionalProperties: MutableMap<String, Any> = HashMap()
fun getAdditionalProperties(): Map<String, Any> {
return additionalProperties
}
fun setAdditionalProperty(name: String, value: Any) {
additionalProperties[name] = value
}
inner class Metadata {
var test: Test? = null
private val additionalProperties: MutableMap<String, Any> = HashMap()
fun getAdditionalProperties(): Map<String, Any> {
return this.additionalProperties
}
fun setAdditionalProperty(name: String, value: Any) {
this.additionalProperties[name] = value
}
}
inner class Test {
var width: Int? = null
var height: Int? = null
val pixelRatio: Float? = null
var center: List<Int>? = null
var zoom: Int? = null
var diff: Double? = null
var operations: List<List<String>>? = null
private val additionalProperties: MutableMap<String, Any> = HashMap()
fun getAdditionalProperties(): Map<String, Any> {
return this.additionalProperties
}
fun setAdditionalProperty(name: String, value: Any) {
this.additionalProperties[name] = value
}
}
}

View File

@@ -0,0 +1,262 @@
package org.maplibre.android.testapp.activity.snapshot
import android.graphics.Color
import android.os.Bundle
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.GridLayout
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import com.mapbox.geojson.Feature
import com.mapbox.geojson.FeatureCollection
import com.mapbox.geojson.Point
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.constants.MapLibreConstants
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.geometry.LatLngBounds
import org.maplibre.android.maps.Style
import org.maplibre.android.snapshotter.MapSnapshot
import org.maplibre.android.snapshotter.MapSnapshotter
import org.maplibre.android.style.expressions.Expression
import org.maplibre.android.style.layers.Property
import org.maplibre.android.style.layers.PropertyFactory
import org.maplibre.android.style.layers.RasterLayer
import org.maplibre.android.style.layers.SymbolLayer
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.style.sources.RasterSource
import org.maplibre.android.style.sources.Source
import org.maplibre.android.testapp.R
import org.maplibre.android.utils.BitmapUtils
import timber.log.Timber
import java.util.Objects
import java.util.Random
/**
* Test activity showing how to use a the [com.mapbox.mapboxsdk.snapshotter.MapSnapshotter]
*/
class MapSnapshotterActivity : AppCompatActivity() {
lateinit var grid: GridLayout
private val snapshotters: MutableList<MapSnapshotter> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_snapshotter)
// Find the grid view and start snapshotting as soon
// as the view is measured
grid = findViewById(R.id.snapshot_grid)
grid.getViewTreeObserver()
.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
override fun onGlobalLayout() {
grid.getViewTreeObserver().removeGlobalOnLayoutListener(this)
addSnapshots()
}
})
}
private fun addSnapshots() {
Timber.i("Creating snapshotters")
for (row in 0 until grid.rowCount) {
for (column in 0 until grid.columnCount) {
startSnapShot(row, column)
}
}
}
private fun startSnapShot(row: Int, column: Int) {
// Optionally the style
val builder = Style.Builder()
.fromUri(
Style.getPredefinedStyle(
if ((column + row) % 2 == 0) {
"Streets"
} else {
"Pastel"
}
)
)
// Define the dimensions
val options = MapSnapshotter.Options(
grid.measuredWidth / grid.columnCount,
grid.measuredHeight / grid.rowCount
) // Optionally the pixel ratio
.withPixelRatio(1f)
.withLocalIdeographFontFamily(MapLibreConstants.DEFAULT_FONT)
// Optionally the visible region
if (row % 2 == 0) {
options.withRegion(
LatLngBounds.Builder()
.include(
LatLng(
randomInRange(-80f, 80f).toDouble(),
randomInRange(-160f, 160f)
.toDouble()
)
)
.include(
LatLng(
randomInRange(-80f, 80f).toDouble(),
randomInRange(-160f, 160f)
.toDouble()
)
)
.build()
)
}
// Optionally the camera options
if (column % 2 == 0) {
options.withCameraPosition(
CameraPosition.Builder()
.target(
if (options.region != null) {
options.region!!.center
} else {
LatLng(
randomInRange(-80f, 80f).toDouble(),
randomInRange(-160f, 160f)
.toDouble()
)
}
)
.bearing(randomInRange(0f, 360f).toDouble())
.tilt(randomInRange(0f, 60f).toDouble())
.zoom(randomInRange(0f, 10f).toDouble())
.padding(1.0, 1.0, 1.0, 1.0)
.build()
)
}
if (row == 0 && column == 0) {
// Add a source
val source: Source =
RasterSource("my-raster-source", "maptiler://sources/satellite", 512)
builder.withLayerAbove(
RasterLayer("satellite-layer", "my-raster-source"),
"country_1"
)
builder.withSource(source)
} else if (row == 0 && column == 2) {
val carBitmap = BitmapUtils.getBitmapFromDrawable(
ResourcesCompat.getDrawable(resources, R.drawable.ic_directions_car_black, null)
)
// marker source
val markerCollection = FeatureCollection.fromFeatures(
arrayOf(
Feature.fromGeometry(
Point.fromLngLat(4.91638, 52.35673),
featureProperties("1", "Android")
),
Feature.fromGeometry(
Point.fromLngLat(4.91638, 12.34673),
featureProperties("2", "Car")
)
)
)
val markerSource: Source = GeoJsonSource(MARKER_SOURCE, markerCollection)
// marker layer
val markerSymbolLayer = SymbolLayer(MARKER_LAYER, MARKER_SOURCE)
.withProperties(
PropertyFactory.iconImage(Expression.get(TITLE_FEATURE_PROPERTY)),
PropertyFactory.iconIgnorePlacement(true),
PropertyFactory.iconAllowOverlap(true),
PropertyFactory.iconSize(
Expression.switchCase(
Expression.toBool(
Expression.get(
SELECTED_FEATURE_PROPERTY
)
),
Expression.literal(1.5f),
Expression.literal(1.0f)
)
),
PropertyFactory.iconAnchor(Property.ICON_ANCHOR_BOTTOM),
PropertyFactory.iconColor(Color.BLUE)
)
builder.withImage("Car", Objects.requireNonNull(carBitmap!!), false)
.withSources(markerSource)
.withLayers(markerSymbolLayer)
options
.withRegion(null)
.withCameraPosition(
CameraPosition.Builder()
.target(
LatLng(
5.537109374999999,
52.07950600379697
)
)
.zoom(1.0)
.padding(1.0, 1.0, 1.0, 1.0)
.build()
)
}
options.withStyleBuilder(builder)
val snapshotter = MapSnapshotter(this@MapSnapshotterActivity, options)
snapshotter.setObserver(object : MapSnapshotter.Observer {
override fun onDidFinishLoadingStyle() {
Timber.i("onDidFinishLoadingStyle")
}
override fun onStyleImageMissing(imageName: String) {
val androidIcon =
BitmapUtils.getBitmapFromDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_android_2, null))
snapshotter.addImage(imageName, androidIcon!!, false)
}
})
snapshotter.start(
object : MapSnapshotter.SnapshotReadyCallback {
override fun onSnapshotReady(snapshot: MapSnapshot) {
Timber.i("Got the snapshot")
val imageView = ImageView(this@MapSnapshotterActivity)
imageView.setImageBitmap(snapshot.bitmap)
grid.addView(
imageView,
GridLayout.LayoutParams(GridLayout.spec(row), GridLayout.spec(column))
)
}
}
)
snapshotters.add(snapshotter)
}
public override fun onPause() {
super.onPause()
// Make sure to stop the snapshotters on pause
for (snapshotter in snapshotters) {
snapshotter.cancel()
}
snapshotters.clear()
}
private fun featureProperties(id: String, title: String): JsonObject {
val `object` = JsonObject()
`object`.add(ID_FEATURE_PROPERTY, JsonPrimitive(id))
`object`.add(TITLE_FEATURE_PROPERTY, JsonPrimitive(title))
`object`.add(SELECTED_FEATURE_PROPERTY, JsonPrimitive(false))
return `object`
}
companion object {
private const val ID_FEATURE_PROPERTY = "id"
private const val SELECTED_FEATURE_PROPERTY = "selected"
private const val TITLE_FEATURE_PROPERTY = "title"
// layer & source constants
private const val MARKER_SOURCE = "marker-source"
private const val MARKER_LAYER = "marker-layer"
private val random = Random()
fun randomInRange(min: Float, max: Float): Float {
return random.nextFloat() * (max - min) + min
}
}
}

View File

@@ -0,0 +1,100 @@
package org.maplibre.android.testapp.activity.snapshot
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.PointF
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.ImageView
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.Style
import org.maplibre.android.snapshotter.MapSnapshot
import org.maplibre.android.snapshotter.MapSnapshotter
import org.maplibre.android.testapp.R
import timber.log.Timber
/**
* Test activity showing how to use a the [MapSnapshotter] and overlay
* [android.graphics.Bitmap]s on top.
*/
class MapSnapshotterBitMapOverlayActivity :
AppCompatActivity(),
MapSnapshotter.SnapshotReadyCallback {
private var mapSnapshotter: MapSnapshotter? = null
@get:VisibleForTesting
var mapSnapshot: MapSnapshot? = null
private set
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_snapshotter_marker)
val container = findViewById<View>(R.id.container)
container.viewTreeObserver
.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
override fun onGlobalLayout() {
container.viewTreeObserver.removeGlobalOnLayoutListener(this)
Timber.i("Starting snapshot")
mapSnapshotter = MapSnapshotter(
applicationContext,
MapSnapshotter.Options(
Math.min(container.measuredWidth, 1024),
Math.min(container.measuredHeight, 1024)
)
.withStyleBuilder(
Style.Builder().fromUri(Style.getPredefinedStyle("Outdoor"))
)
.withCameraPosition(
CameraPosition.Builder().target(LatLng(52.090737, 5.121420))
.zoom(15.0).build()
)
)
mapSnapshotter!!.start(this@MapSnapshotterBitMapOverlayActivity)
}
})
}
override fun onStop() {
super.onStop()
mapSnapshotter!!.cancel()
}
@SuppressLint("ClickableViewAccessibility")
override fun onSnapshotReady(snapshot: MapSnapshot) {
mapSnapshot = snapshot
Timber.i("Snapshot ready")
val imageView = findViewById<View>(R.id.snapshot_image) as ImageView
val image = addMarker(snapshot)
imageView.setImageBitmap(image)
imageView.setOnTouchListener { v: View?, event: MotionEvent ->
if (event.action == MotionEvent.ACTION_DOWN) {
val latLng = snapshot.latLngForPixel(PointF(event.x, event.y))
Timber.e("Clicked LatLng is %s", latLng)
return@setOnTouchListener true
}
false
}
}
private fun addMarker(snapshot: MapSnapshot): Bitmap {
val canvas = Canvas(snapshot.bitmap)
val marker =
BitmapFactory.decodeResource(resources, R.drawable.maplibre_marker_icon_default, null)
// Dom toren
val markerLocation = snapshot.pixelForLatLng(LatLng(52.090649433011315, 5.121310651302338))
canvas.drawBitmap(
marker, /* Subtract half of the width so we center the bitmap correctly */
markerLocation.x - marker.width / 2, /* Subtract half of the height so we align the bitmap bottom correctly */
markerLocation.y - marker.height / 2,
null
)
return snapshot.bitmap
}
}

View File

@@ -0,0 +1,152 @@
package org.maplibre.android.testapp.activity.snapshot
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.Style
import org.maplibre.android.snapshotter.MapSnapshot
import org.maplibre.android.snapshotter.MapSnapshotter
import org.maplibre.android.style.expressions.Expression
import org.maplibre.android.style.layers.HeatmapLayer
import org.maplibre.android.style.layers.PropertyFactory
import org.maplibre.android.style.sources.GeoJsonSource
import org.maplibre.android.style.sources.Source
import org.maplibre.android.testapp.R
import timber.log.Timber
import java.net.URI
import java.net.URISyntaxException
/**
* Test activity showing how to use a the [MapSnapshotter] and heatmap layer on it.
*/
class MapSnapshotterHeatMapActivity : AppCompatActivity(), MapSnapshotter.SnapshotReadyCallback {
private var mapSnapshotter: MapSnapshotter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_snapshotter_marker)
val container = findViewById<View>(R.id.container)
container.viewTreeObserver
.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
override fun onGlobalLayout() {
container.viewTreeObserver.removeGlobalOnLayoutListener(this)
Timber.i("Starting snapshot")
val builder = Style.Builder().fromUri(Style.getPredefinedStyle("Outdoor"))
.withSource(earthquakeSource!!)
.withLayerAbove(heatmapLayer, "water_intermittent")
mapSnapshotter = MapSnapshotter(
applicationContext,
MapSnapshotter.Options(container.measuredWidth, container.measuredHeight)
.withStyleBuilder(builder)
.withCameraPosition(
CameraPosition.Builder()
.target(LatLng(15.0, (-94).toDouble()))
.zoom(5.0)
.padding(1.0, 1.0, 1.0, 1.0)
.build()
)
)
mapSnapshotter!!.start(this@MapSnapshotterHeatMapActivity)
}
})
}
// Color ramp for heatmap. Domain is 0 (low) to 1 (high).
// Begin color ramp at 0-stop with a 0-transparency color
// to create a blur-like effect.
// Increase the heatmap weight based on frequency and property magnitude
// Increase the heatmap color weight weight by zoom level
// heatmap-intensity is a multiplier on top of heatmap-weight
// Adjust the heatmap radius by zoom level
// Transition from heatmap to circle layer by zoom level
private val heatmapLayer: HeatmapLayer
private get() {
val layer = HeatmapLayer(HEATMAP_LAYER_ID, EARTHQUAKE_SOURCE_ID)
layer.maxZoom = 9f
layer.sourceLayer = HEATMAP_LAYER_SOURCE
layer.setProperties( // Color ramp for heatmap. Domain is 0 (low) to 1 (high).
// Begin color ramp at 0-stop with a 0-transparency color
// to create a blur-like effect.
PropertyFactory.heatmapColor(
Expression.interpolate(
Expression.linear(), Expression.heatmapDensity(),
Expression.literal(0), Expression.rgba(33, 102, 172, 0),
Expression.literal(0.2), Expression.rgb(103, 169, 207),
Expression.literal(0.4), Expression.rgb(209, 229, 240),
Expression.literal(0.6), Expression.rgb(253, 219, 199),
Expression.literal(0.8), Expression.rgb(239, 138, 98),
Expression.literal(1), Expression.rgb(178, 24, 43)
)
), // Increase the heatmap weight based on frequency and property magnitude
PropertyFactory.heatmapWeight(
Expression.interpolate(
Expression.linear(),
Expression.get("mag"),
Expression.stop(0, 0),
Expression.stop(6, 1)
)
), // Increase the heatmap color weight weight by zoom level
// heatmap-intensity is a multiplier on top of heatmap-weight
PropertyFactory.heatmapIntensity(
Expression.interpolate(
Expression.linear(),
Expression.zoom(),
Expression.stop(0, 1),
Expression.stop(9, 3)
)
), // Adjust the heatmap radius by zoom level
PropertyFactory.heatmapRadius(
Expression.interpolate(
Expression.linear(),
Expression.zoom(),
Expression.stop(0, 2),
Expression.stop(9, 20)
)
), // Transition from heatmap to circle layer by zoom level
PropertyFactory.heatmapOpacity(
Expression.interpolate(
Expression.linear(),
Expression.zoom(),
Expression.stop(7, 1),
Expression.stop(9, 0)
)
)
)
return layer
}
override fun onStop() {
super.onStop()
mapSnapshotter!!.cancel()
}
@SuppressLint("ClickableViewAccessibility")
override fun onSnapshotReady(snapshot: MapSnapshot) {
Timber.i("Snapshot ready")
val imageView = findViewById<ImageView>(R.id.snapshot_image)
imageView.setImageBitmap(snapshot.bitmap)
}
private val earthquakeSource: Source?
private get() {
var source: Source? = null
try {
source = GeoJsonSource(EARTHQUAKE_SOURCE_ID, URI(EARTHQUAKE_SOURCE_URL))
} catch (uriSyntaxException: URISyntaxException) {
Timber.e(uriSyntaxException, "That's not an url... ")
}
return source
}
companion object {
private const val EARTHQUAKE_SOURCE_URL =
"https://www.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson"
private const val EARTHQUAKE_SOURCE_ID = "earthquakes"
private const val HEATMAP_LAYER_ID = "earthquakes-heat"
private const val HEATMAP_LAYER_SOURCE = "earthquakes"
}
}

View File

@@ -0,0 +1,76 @@
package org.maplibre.android.testapp.activity.snapshot
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.Style
import org.maplibre.android.snapshotter.MapSnapshot
import org.maplibre.android.snapshotter.MapSnapshotter
import org.maplibre.android.testapp.R
import org.maplibre.android.testapp.utils.ResourceUtils
import timber.log.Timber
import java.io.IOException
import java.lang.RuntimeException
/**
* Test activity showing how to use a the MapSnapshotter with a local style
*/
class MapSnapshotterLocalStyleActivity : AppCompatActivity(), MapSnapshotter.SnapshotReadyCallback {
private var mapSnapshotter: MapSnapshotter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_snapshotter_marker)
val container = findViewById<View>(R.id.container)
container.viewTreeObserver
.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
override fun onGlobalLayout() {
container.viewTreeObserver.removeGlobalOnLayoutListener(this)
val styleJson: String
styleJson = try {
ResourceUtils.readRawResource(
this@MapSnapshotterLocalStyleActivity,
R.raw.sat_style
)
} catch (exception: IOException) {
throw RuntimeException(exception)
}
Timber.i("Starting snapshot")
mapSnapshotter = MapSnapshotter(
applicationContext,
MapSnapshotter.Options(
Math.min(container.measuredWidth, 1024),
Math.min(container.measuredHeight, 1024)
)
.withStyleBuilder(Style.Builder().fromJson(styleJson))
.withCameraPosition(
CameraPosition.Builder().target(LatLng(52.090737, 5.121420))
.zoom(18.0).build()
)
)
mapSnapshotter!!.start(
this@MapSnapshotterLocalStyleActivity,
object : MapSnapshotter.ErrorHandler {
override fun onError(error: String) {
Timber.e(error)
}
}
)
}
})
}
override fun onStop() {
super.onStop()
mapSnapshotter!!.cancel()
}
override fun onSnapshotReady(snapshot: MapSnapshot) {
Timber.i("Snapshot ready")
val imageView = findViewById<View>(R.id.snapshot_image) as ImageView
imageView.setImageBitmap(snapshot.bitmap)
}
}

Some files were not shown because too many files have changed in this diff Show More