Skip to content

Instantly share code, notes, and snippets.

@jeluchu
Last active March 4, 2019 11:52
Show Gist options
  • Save jeluchu/b902cc5316b847b5fe69c4880e30762f to your computer and use it in GitHub Desktop.
Save jeluchu/b902cc5316b847b5fe69c4880e30762f to your computer and use it in GitHub Desktop.
Developing new map options for "MapboxU"
/* -------------------------------- DOWNLOAD BUTTON ---------------------------------------- */
private fun downloadRegionDialog() {
val builder = AlertDialog.Builder(this@MainActivity)
val regionNameEdit = EditText(this@MainActivity)
regionNameEdit.hint = "Introduce un nombre"
regionNameEdit.gravity = Gravity.CENTER_HORIZONTAL
regionNameEdit.ellipsize
// CREAR EL DIALOGO
builder.setTitle("Registrar lugar")
.setView(regionNameEdit)
.setMessage("Descarga la zona del mapa que estás viendo actualmente.\n")
.setPositiveButton("Descargar") { _, _ ->
val regionName = regionNameEdit.text.toString()
if (regionName.isEmpty()) {
Toast.makeText(this@MainActivity, "El campo no puede estar vacío", Toast.LENGTH_SHORT).show()
} else {
// EMPEZAR DESCARGA
downloadRegion(regionName)
}
}
.setNegativeButton("Cancelar") { dialog, _ -> dialog.cancel() }
// MOSTRAR
builder.show()
}
@SuppressLint("LogNotTimber")
private fun downloadRegion(regionName: String) {
// INICIO PROGRESS BAR
startProgress()
val styleUrl = map.styleUrl.toString()
val bounds = map.projection.visibleRegion.latLngBounds
val minZoom = map.cameraPosition.zoom
val maxZoom = map.maxZoomLevel
val pixelRatio = this@MainActivity.resources.displayMetrics.density
val definition = OfflineTilePyramidRegionDefinition(
styleUrl, bounds, minZoom, maxZoom, pixelRatio)
val metadata: ByteArray? = try {
val jsonObject = JSONObject()
jsonObject.put(JSON_FIELD_REGION_NAME, regionName)
val json = jsonObject.toString()
json.toByteArray(Charset.defaultCharset())
} catch (exception: Exception) {
Log.d("ERROR", "Failed to encode metadata: " + exception.message)
null
}
// CREAR LA ZONA OFFLINE Y LANZAR LA DESCARGA
offlineManager?.createOfflineRegion(definition, metadata!!, object : OfflineManager.CreateOfflineRegionCallback {
override fun onCreate(offlineRegion: OfflineRegion) {
Log.d("INFO", "Offline region created: $regionName")
offlineRegionDownloaded = offlineRegion
launchDownload()
}
override fun onError(error: String) {
Log.e("ERROR", "Error: $error")
}
})
}
private fun startProgress() {
// INICIAR PROGRESS BAR
isEndNotified = false
progress_bar.isIndeterminate = true
progress_bar.visibility = View.INVISIBLE
}
private fun launchDownload() {
// NOTIFICAR AL USUARIO CUÁNDO SE COMPLETE LA DESCARGA
offlineRegionDownloaded?.setObserver(object : OfflineRegion.OfflineRegionObserver {
@SuppressLint("LogNotTimber")
override fun onStatusChanged(status: OfflineRegionStatus) {
// PORCENTAJE
val percentage = if (status.requiredResourceCount >= 0)
100.0 * status.completedResourceCount / status.requiredResourceCount
else
0.0
if (status.isComplete) {
// DESCARGA COMPLETA
endProgress("Zona descargada correctamente")
return
} else if (status.isRequiredResourceCountPrecise) {
setPercentage(Math.round(percentage).toInt())
}
Log.d("DOWNLOAD", String.format("%s/%s resources; %s bytes downloaded.",
status.completedResourceCount.toString(),
status.requiredResourceCount.toString(),
status.completedResourceSize.toString()))
}
override fun onError(error: OfflineRegionError) {
Timber.e("onError reason: %s", error.reason)
Timber.e("onError message: %s", error.message)
}
@SuppressLint("LogNotTimber")
override fun mapboxTileCountLimitExceeded(limit: Long) {
Log.e("DOWNLOAD", "Mapbox tile count limit exceeded: $limit")
}
})
// CAMBIAR EL ESTADO DE LA REGIÓN
offlineRegionDownloaded?.setDownloadState(OfflineRegion.STATE_ACTIVE)
}
private fun endProgress(message: String) {
// NO NOTIFICAR MÁS DE UNA VEZ
if (isEndNotified) {
return
}
// PARAR Y OCULTAR PROGRESS BAR
isEndNotified = true
progress_bar.isIndeterminate = false
progress_bar.visibility = View.GONE
Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
}
private fun setPercentage(percentage: Int) {
progress_bar.isIndeterminate = false
progress_bar.progress = percentage
}
/* ----------------------------- DOWNLOAD REGION BUTTON ---------------------------------------- */
private fun downloadRegionList() {
// RESET PLACE TO 0
regionSelected = 0
offlineManager?.listOfflineRegions(object : OfflineManager.ListOfflineRegionsCallback {
override fun onList(offlineRegions: Array<out OfflineRegion>?) {
if (offlineRegions == null || offlineRegions.isEmpty()) {
Toast.makeText(this@MainActivity, "Aún no tienes lugares", Toast.LENGTH_SHORT).show()
return
}
// TODOS LOS NOMBRES DE LUGARES EN LA LISTA
val offlineRegionsNames = ArrayList<String>()
for (offlineRegion in offlineRegions) {
offlineRegionsNames.add(getRegionName(offlineRegion))
}
val items = offlineRegionsNames.toTypedArray<CharSequence>()
// ALERT DIALOG
val dialog = AlertDialog.Builder(this@MainActivity)
.setTitle("Listado")
.setSingleChoiceItems(items, 0) { _, which ->
// VER CUÁL ES EL LUGAR SELECCIONADO
regionSelected = which
}
.setPositiveButton("Iniciar la navegación") { _, _ ->
Toast.makeText(this@MainActivity, items[regionSelected], Toast.LENGTH_LONG).show()
// RECOGER DATOS DEL LUGAR
val bounds = (offlineRegions[regionSelected].definition as OfflineTilePyramidRegionDefinition).bounds
val regionZoom = (offlineRegions[regionSelected].definition as OfflineTilePyramidRegionDefinition).minZoom
// CREAR UNA NUEVA POSICIÓN DE LA CÁMARA
val cameraPosition = CameraPosition.Builder()
.target(bounds.center)
.zoom(regionZoom)
.build()
// MOVER LA CÁMARA A DICHA POSICIÓN
map.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
.setNeutralButton("Eliminar") { _, _ ->
progress_bar.isIndeterminate = true
progress_bar.visibility = View.VISIBLE
// PROCESO DE ELIMINACIÓN
offlineRegions[regionSelected].delete(object : OfflineRegion.OfflineRegionDeleteCallback {
override fun onDelete() {
progress_bar.visibility = View.INVISIBLE
progress_bar.isIndeterminate = false
Toast.makeText(this@MainActivity, "Lugar eliminado", Toast.LENGTH_LONG).show()
}
override fun onError(error: String) {
progress_bar.visibility = View.INVISIBLE
progress_bar.isIndeterminate = false
Timber.e("¡Ha ocurrido un error!")
}
})
}
.setNegativeButton("Cancelar") { _, _ ->
// NO SE HACE NADA, SE CIERRA AUTOMÁTICAMENTE
}.create()
dialog.show()
}
@SuppressLint("LogNotTimber")
override fun onError(error: String) {
Log.e("ERROR", "Error: $error")
}
})
}
@SuppressLint("LogNotTimber")
private fun getRegionName(offlineRegion: OfflineRegion): String {
// OBTENCIÓN DEL NOMBRE MEDIANTE LOS METADATOS
return try {
val metadata = offlineRegion.metadata
val json = metadata.toString(Charset.defaultCharset())
val jsonObject = JSONObject(json)
jsonObject.getString(JSON_FIELD_REGION_NAME)
} catch (exception: Exception) {
Timber.e("Failed to decode metadata: %s", exception.message)
"Region " + offlineRegion.id
}
}
override fun onMapClick(point: LatLng) {
if (!map.markers.isEmpty()) {
map.clear()
}
map.addMarker(MarkerOptions().setTitle("¡Soy Marki! ʕ⊙ᴥ⊙ʔ").setSnippet("Un marcador y te llevaré hasta tu destino").position(point))
checkLocation()
originLocation?.run {
val startPoint = Point.fromLngLat(longitude, latitude)
val endPoint = Point.fromLngLat(point.longitude, point.latitude)
getRoute(startPoint, endPoint)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment