init
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
package org.pupes.mhdrunpathfinder
|
||||
|
||||
import android.app.Activity
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.widget.Toast
|
||||
import kotlinx.serialization.json.Json
|
||||
import okhttp3.OkHttpClient
|
||||
import ovh.plrapps.mapcompose.api.moveMarker
|
||||
import java.net.URL
|
||||
|
||||
// OkHttpClient for making HTTP requests
|
||||
val httpClient = OkHttpClient.Builder()
|
||||
.build()
|
||||
|
||||
private val HaukMainHandler = Handler(Looper.getMainLooper())
|
||||
private var HaukTrackingThread: Thread? = null
|
||||
private var HaukIsTracking = false
|
||||
|
||||
private fun fetchHaukPosition(haukUrl: String, callee: Activity) {
|
||||
try {
|
||||
val url = URL(haukUrl)
|
||||
val targetId = url.toString().substringAfter("?")
|
||||
|
||||
val request = okhttp3.Request.Builder()
|
||||
.url("${url.protocol}://${url.host}/api/fetch.php?id=$targetId")
|
||||
.header("User-Agent", "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME} (Android)")
|
||||
.build()
|
||||
|
||||
httpClient.newCall(request).execute().use { response ->
|
||||
var message = if (response.isSuccessful) {
|
||||
response.body?.string() ?: "Empty response"
|
||||
} else {
|
||||
"Error: ${response.code} ${response.message}"
|
||||
}
|
||||
|
||||
message = "{" + message.substringAfter("{");
|
||||
val hauk_response = Json.decodeFromString<HaukResponse>(message)
|
||||
|
||||
HaukMainHandler.post {
|
||||
mapState.moveMarker("target_position", x = longitudeToXNormalized(hauk_response.points.last()[1]), y = latitudeToYNormalized(hauk_response.points.last()[0]))
|
||||
}
|
||||
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Post UI update to main thread
|
||||
HaukMainHandler.post {
|
||||
Toast.makeText(callee, e.message ?: "Unknown error", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Start the timer with a URL:
|
||||
fun startHaukTracking(url: String, callee: Activity) {
|
||||
if (HaukIsTracking) return
|
||||
|
||||
HaukIsTracking = true
|
||||
HaukTrackingThread = Thread {
|
||||
while (HaukIsTracking) {
|
||||
fetchHaukPosition(url, callee)
|
||||
try {
|
||||
Thread.sleep(1000) // Wait 1 second between requests
|
||||
} catch (e: InterruptedException) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}.apply { start() }
|
||||
}
|
||||
|
||||
fun stopHaukTracking() {
|
||||
HaukIsTracking = false
|
||||
HaukTrackingThread?.interrupt()
|
||||
HaukTrackingThread = null
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.pupes.mhdrunpathfinder
|
||||
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.tan
|
||||
|
||||
fun longitudeToXNormalized(longitude: Double): Double {
|
||||
return (longitude + 180.0) / 360.0
|
||||
}
|
||||
|
||||
|
||||
fun latitudeToYNormalized(latitude: Double): Double {
|
||||
// Clamp latitude to Web Mercator bounds
|
||||
val lat = latitude.coerceIn(-85.05112878, 85.05112878)
|
||||
|
||||
// Convert to radians
|
||||
val latRad = lat * PI / 180.0
|
||||
|
||||
// Web Mercator projection formula
|
||||
val mercatorY = ln(tan(PI / 4.0 + latRad / 2.0))
|
||||
|
||||
// Normalize to 0.0 - 1.0 range
|
||||
// The mercator Y range is approximately -PI to PI
|
||||
return 0.5 - (mercatorY / (2.0 * PI))
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package org.pupes.mhdrunpathfinder
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.widget.Toast
|
||||
import androidx.core.app.ActivityCompat
|
||||
import ovh.plrapps.mapcompose.api.moveMarker
|
||||
|
||||
// Handler for main thread operations
|
||||
private val LocationMainHandler = Handler(Looper.getMainLooper())
|
||||
private var locationManager: LocationManager? = null
|
||||
private var locationListener: LocationListener? = null
|
||||
private var isLocationTracking = false
|
||||
|
||||
// Location update configuration
|
||||
private const val MIN_TIME_BETWEEN_UPDATES = 1000L // 1 second in milliseconds
|
||||
private const val MIN_DISTANCE_CHANGE = 0f // 0 meters - update on any movement
|
||||
|
||||
// LocationListener callback
|
||||
private val createLocationListener: (Activity) -> LocationListener = { callee ->
|
||||
LocationListener { location ->
|
||||
handleLocationUpdate(location, callee)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleLocationUpdate(location: Location, callee: Activity) {
|
||||
try {
|
||||
val normalizedX = longitudeToXNormalized(location.longitude)
|
||||
val normalizedY = latitudeToYNormalized(location.latitude)
|
||||
|
||||
// Update marker on main thread
|
||||
LocationMainHandler.post {
|
||||
try {
|
||||
mapState.moveMarker(
|
||||
"current_position",
|
||||
x = normalizedX,
|
||||
y = normalizedY
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
// Marker might not exist yet, silently ignore
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
LocationMainHandler.post {
|
||||
Toast.makeText(callee, "Location error: ${e.message}", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if location permissions are granted
|
||||
private fun hasLocationPermissions(context: Context): Boolean {
|
||||
return ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_FINE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED ||
|
||||
ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
// Start continuous location tracking
|
||||
fun startLocationTracking(callee: Activity) {
|
||||
if (isLocationTracking) {
|
||||
Toast.makeText(callee, "Location tracking already active", Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
|
||||
if (!hasLocationPermissions(callee)) {
|
||||
Toast.makeText(callee, "Location permissions not granted", Toast.LENGTH_LONG).show()
|
||||
// Request permissions
|
||||
ActivityCompat.requestPermissions(
|
||||
callee,
|
||||
arrayOf(
|
||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
),
|
||||
LOCATION_PERMISSION_REQUEST_CODE
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
locationManager = callee.getSystemService(Context.LOCATION_SERVICE) as LocationManager
|
||||
locationListener = createLocationListener(callee)
|
||||
|
||||
// Try GPS first, then network provider
|
||||
val providers = listOf(
|
||||
LocationManager.GPS_PROVIDER,
|
||||
LocationManager.NETWORK_PROVIDER
|
||||
)
|
||||
|
||||
var providerFound = false
|
||||
for (provider in providers) {
|
||||
if (locationManager?.isProviderEnabled(provider) == true) {
|
||||
try {
|
||||
locationManager?.requestLocationUpdates(
|
||||
provider,
|
||||
MIN_TIME_BETWEEN_UPDATES,
|
||||
MIN_DISTANCE_CHANGE,
|
||||
locationListener!!,
|
||||
Looper.getMainLooper()
|
||||
)
|
||||
providerFound = true
|
||||
|
||||
// Get last known location and update immediately
|
||||
locationManager?.getLastKnownLocation(provider)?.let { location ->
|
||||
handleLocationUpdate(location, callee)
|
||||
}
|
||||
|
||||
break
|
||||
} catch (e: SecurityException) {
|
||||
// Permission denied
|
||||
Toast.makeText(callee, "Location permission denied", Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!providerFound) {
|
||||
Toast.makeText(callee, "No location provider available. Please enable GPS or network location", Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
|
||||
isLocationTracking = true
|
||||
Toast.makeText(callee, "Location tracking started", Toast.LENGTH_SHORT).show()
|
||||
|
||||
} catch (e: Exception) {
|
||||
Toast.makeText(callee, "Failed to start location tracking: ${e.message}", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
|
||||
// Stop location tracking
|
||||
fun stopLocationTracking() {
|
||||
if (!isLocationTracking) return
|
||||
|
||||
try {
|
||||
locationListener?.let { listener ->
|
||||
locationManager?.removeUpdates(listener)
|
||||
}
|
||||
locationListener = null
|
||||
locationManager = null
|
||||
isLocationTracking = false
|
||||
} catch (e: Exception) {
|
||||
// Silently handle cleanup errors
|
||||
}
|
||||
}
|
||||
|
||||
// Get current tracking status
|
||||
fun isLocationTrackingActive(): Boolean {
|
||||
return isLocationTracking
|
||||
}
|
||||
|
||||
// Permission request code
|
||||
const val LOCATION_PERMISSION_REQUEST_CODE = 1001
|
||||
@@ -0,0 +1,153 @@
|
||||
package org.pupes.mhdrunpathfinder
|
||||
|
||||
import android.R.attr.onClick
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.serialization.Serializable
|
||||
import ovh.plrapps.mapcompose.api.addLayer
|
||||
import ovh.plrapps.mapcompose.api.addMarker
|
||||
import ovh.plrapps.mapcompose.api.scrollTo
|
||||
import ovh.plrapps.mapcompose.core.TileStreamProvider
|
||||
import ovh.plrapps.mapcompose.ui.MapUI
|
||||
import ovh.plrapps.mapcompose.ui.state.MapState
|
||||
import java.net.URL
|
||||
|
||||
@Serializable
|
||||
data class HaukResponse(
|
||||
val type: Int,
|
||||
val expire: Long,
|
||||
val serverTime: Double,
|
||||
val interval: Int,
|
||||
val points: List<List<Double>>,
|
||||
val encrypted: Boolean,
|
||||
val salt: String? = null
|
||||
)
|
||||
|
||||
// MapState configuration for OpenStreetMap
|
||||
// Max zoom level is 18, tile size is 256x256
|
||||
// At zoom level 18, there are 2^18 = 262144 tiles in each dimension
|
||||
// So fullWidth/Height = 256 * 262144
|
||||
val mapState = MapState(
|
||||
levelCount = 19, // zoom levels 0-18
|
||||
fullWidth = 67108864, // 256 * 2^18
|
||||
fullHeight = 67108864,
|
||||
tileSize = 256
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
|
||||
setContent {
|
||||
MaterialTheme {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = MaterialTheme.colorScheme.background
|
||||
) {
|
||||
OpenStreetMapScreen()
|
||||
AddButton()
|
||||
}
|
||||
}
|
||||
}
|
||||
startHaukTracking("https://hauk.limit6.eu/?M4SJ-SH7I",this)
|
||||
startLocationTracking(this)
|
||||
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
stopHaukTracking()
|
||||
stopLocationTracking()
|
||||
}
|
||||
}
|
||||
|
||||
@Preview
|
||||
@Composable
|
||||
// When a composable with parameters is used with @Preview,
|
||||
// a default value must be provided for the preview to render.
|
||||
fun AddButton(onClick: () -> Unit = {}) {
|
||||
OutlinedButton(onClick = { onClick() }) {
|
||||
Text("Outlined")
|
||||
}
|
||||
}
|
||||
|
||||
@Preview
|
||||
@Composable
|
||||
fun OpenStreetMapScreen() {
|
||||
// Create tile stream provider for OpenStreetMap with User-Agent
|
||||
val tileStreamProvider = TileStreamProvider { row, col, zoomLvl ->
|
||||
try {
|
||||
val url = URL("https://tile.openstreetmap.org/$zoomLvl/$col/$row.png")
|
||||
val connection = url.openConnection()
|
||||
// Set User-Agent header as required by OSM tile usage policy
|
||||
// Format: AppId/Version (Platform) (Contact: email)
|
||||
val userAgent = "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME} (Android) (Contact: poliecho@pupes.org)"
|
||||
connection.setRequestProperty("User-Agent", userAgent)
|
||||
connection.getInputStream()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/* Add a marker at the center of the map */
|
||||
mapState.addMarker("target_position", x = longitudeToXNormalized(14.4058031), y = latitudeToYNormalized(50.0756083)) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.target),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
tint = Color(0xFFFF0000)
|
||||
)
|
||||
}
|
||||
|
||||
/* Add a marker for current position */
|
||||
mapState.addMarker("current_position", x = longitudeToXNormalized(14.4378), y = latitudeToYNormalized(50.0755)) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.user_location),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
tint = Color(0xFF0000FF) // Blue color for current position
|
||||
)
|
||||
}
|
||||
|
||||
// Add the tile layer and set initial position
|
||||
LaunchedEffect(Unit) {
|
||||
mapState.addLayer(tileStreamProvider)
|
||||
|
||||
// Scroll to Prague, Czech Republic
|
||||
// Prague coordinates: latitude 50.0755, longitude 14.4378
|
||||
val normalizedX = longitudeToXNormalized(14.4378)
|
||||
val normalizedY = latitudeToYNormalized(50.0755)
|
||||
|
||||
// Use a higher scale to zoom in more (closer to 1.0 = more zoomed in)
|
||||
mapState.scrollTo(normalizedX, normalizedY, destScale = 0.8)
|
||||
}
|
||||
|
||||
// Display the map
|
||||
MapUI(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
state = mapState
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.pupes.mhdrunpathfinder.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
val Purple80 = Color(0xFFD0BCFF)
|
||||
val PurpleGrey80 = Color(0xFFCCC2DC)
|
||||
val Pink80 = Color(0xFFEFB8C8)
|
||||
|
||||
val Purple40 = Color(0xFF6650a4)
|
||||
val PurpleGrey40 = Color(0xFF625b71)
|
||||
val Pink40 = Color(0xFF7D5260)
|
||||
@@ -0,0 +1,58 @@
|
||||
package org.pupes.mhdrunpathfinder.ui.theme
|
||||
|
||||
import android.app.Activity
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
private val DarkColorScheme = darkColorScheme(
|
||||
primary = Purple80,
|
||||
secondary = PurpleGrey80,
|
||||
tertiary = Pink80
|
||||
)
|
||||
|
||||
private val LightColorScheme = lightColorScheme(
|
||||
primary = Purple40,
|
||||
secondary = PurpleGrey40,
|
||||
tertiary = Pink40
|
||||
|
||||
/* Other default colors to override
|
||||
background = Color(0xFFFFFBFE),
|
||||
surface = Color(0xFFFFFBFE),
|
||||
onPrimary = Color.White,
|
||||
onSecondary = Color.White,
|
||||
onTertiary = Color.White,
|
||||
onBackground = Color(0xFF1C1B1F),
|
||||
onSurface = Color(0xFF1C1B1F),
|
||||
*/
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun MHDRunPathfinderTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
// Dynamic color is available on Android 12+
|
||||
dynamicColor: Boolean = true,
|
||||
content: @Composable () -> Unit
|
||||
) {
|
||||
val colorScheme = when {
|
||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
val context = LocalContext.current
|
||||
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||
}
|
||||
|
||||
darkTheme -> DarkColorScheme
|
||||
else -> LightColorScheme
|
||||
}
|
||||
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = Typography,
|
||||
content = content
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.pupes.mhdrunpathfinder.ui.theme
|
||||
|
||||
import androidx.compose.material3.Typography
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
// Set of Material typography styles to start with
|
||||
val Typography = Typography(
|
||||
bodyLarge = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp,
|
||||
letterSpacing = 0.5.sp
|
||||
)
|
||||
/* Other default text styles to override
|
||||
titleLarge = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 22.sp,
|
||||
lineHeight = 28.sp,
|
||||
letterSpacing = 0.sp
|
||||
),
|
||||
labelSmall = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
letterSpacing = 0.5.sp
|
||||
)
|
||||
*/
|
||||
)
|
||||
Reference in New Issue
Block a user