Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Offline Mapbox #1

Open
jeluchu opened this issue Apr 8, 2019 · 0 comments
Open

Offline Mapbox #1

jeluchu opened this issue Apr 8, 2019 · 0 comments
Assignees
Labels
help wanted Extra attention is needed

Comments

@jeluchu
Copy link
Owner

jeluchu commented Apr 8, 2019

I need help in the "Offline Maps" section, I have been trying to implement this function for a while and I have something done but it doesn't work, I know that @mapbox has its own plugin but I can not implement it in my application. This is my code from develop branch.

`

  private fun downloadRegionDialog() {
    val builder = AlertDialog.Builder(this@MainActivity)

    val regionNameEdit = EditText(this@MainActivity)
    regionNameEdit.hint = "Introduce un nombre"

    builder.setTitle("Nombre de la zona")
        .setView(regionNameEdit)
        .setMessage("Descarga la zona actual")
        .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 {
                downloadRegion(regionName)
            }
        }
        .setNegativeButton("Cancelar") { dialog, _ -> dialog.cancel() }

    builder.show()
}

private fun downloadRegion(regionName: String) {

    startProgress()

    val styleUrl = mapboxMap!!.style
    val bounds = mapboxMap!!.projection.visibleRegion.latLngBounds
    val minZoom = mapboxMap!!.cameraPosition.zoom
    val maxZoom = mapboxMap!!.maxZoomLevel
    val pixelRatio = this@MainActivity.resources.displayMetrics.density
    val definition = OfflineTilePyramidRegionDefinition(
        styleUrl.toString(), 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) {
        Timber.e("Failed to encode metadata: %s", exception.message)
        null
    }


    offlineManager?.createOfflineRegion(definition, metadata!!, object : OfflineManager.CreateOfflineRegionCallback {
        override fun onCreate(offlineRegion: OfflineRegion) {
            Timber.e("Offline region created: %s", regionName)
            offlineRegionDownloaded = offlineRegion
            launchDownload()
        }

        override fun onError(error: String) {
            Timber.e("Error: %s", error)
        }
    })
}

private fun launchDownload() {

    offlineRegionDownloaded?.setObserver(object : OfflineRegion.OfflineRegionObserver {
        override fun onStatusChanged(status: OfflineRegionStatus) {

            val percentage = if (status.requiredResourceCount >= 0)
                100.0 * status.completedResourceCount / status.requiredResourceCount
            else
                0.0

            if (status.isComplete) {

                endProgress("Region downloaded successfully.")
                return
            } else if (status.isRequiredResourceCountPrecise) {

                setPercentage(Math.round(percentage).toInt())
            }

            Timber.d(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)
        }

        override fun mapboxTileCountLimitExceeded(limit: Long) {
            Timber.e("Mapbox tile count limit exceeded: %s", limit)
        }
    })

    offlineRegionDownloaded?.setDownloadState(OfflineRegion.STATE_ACTIVE)
}

private fun startProgress() {

    isEndNotified = false
    progress_bar.isIndeterminate = true
    progress_bar.visibility = View.VISIBLE
}

private fun setPercentage(percentage: Int) {
    progress_bar.isIndeterminate = false
    progress_bar.progress = percentage
}

private fun endProgress(message: String) {

    if (isEndNotified) {
        return
    }

    isEndNotified = true
    progress_bar.isIndeterminate = false
    progress_bar.visibility = View.GONE

    Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show()
}

private fun downloadRegionList() {

    regionSelected = 0

    offlineManager?.listOfflineRegions(object : OfflineManager.ListOfflineRegionsCallback {
        override fun onList(offlineRegions: Array<out OfflineRegion>?) {

            if (offlineRegions == null || offlineRegions.isEmpty()) {
                Toast.makeText(this@MainActivity, "You have no regions yet.", Toast.LENGTH_SHORT).show()
                return
            }

            val offlineRegionsNames = ArrayList<String>()
            for (offlineRegion in offlineRegions) {
                offlineRegionsNames.add(getRegionName(offlineRegion))
            }
            val items = offlineRegionsNames.toTypedArray<CharSequence>()

            val dialog = AlertDialog.Builder(this@MainActivity)
                .setTitle("List")
                .setSingleChoiceItems(items, 0) { _, which ->
                    regionSelected = which
                }
                .setPositiveButton("Navigate to") { _, _ ->
                    Toast.makeText(this@MainActivity, items[regionSelected], Toast.LENGTH_LONG).show()

                    val bounds = (offlineRegions[regionSelected].definition as OfflineTilePyramidRegionDefinition).bounds
                    val regionZoom = (offlineRegions[regionSelected].definition as OfflineTilePyramidRegionDefinition).minZoom

                    val cameraPosition = CameraPosition.Builder()
                        .target(bounds.center)
                        .zoom(regionZoom)
                        .build()

                    mapboxMap!!.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
                }
                .setNeutralButton("Delete") { _, _ ->

                    progress_bar.isIndeterminate = true
                    progress_bar.visibility = View.VISIBLE

                    offlineRegions[regionSelected].delete(object : OfflineRegion.OfflineRegionDeleteCallback {
                        override fun onDelete() {

                            progress_bar.visibility = View.INVISIBLE
                            progress_bar.isIndeterminate = false
                            Toast.makeText(this@MainActivity, "Region deleted", Toast.LENGTH_LONG).show()
                        }

                        override fun onError(error: String) {
                            progress_bar.visibility = View.INVISIBLE
                            progress_bar.isIndeterminate = false
                            Timber.e("Error: $error")
                        }
                    })
                }
                .setNegativeButton("Cancel") { _, _ ->

                }.create()
            dialog.show()

        }

        override fun onError(error: String) {
            Timber.e("Error: $error")
        }

    })
}

private fun getRegionName(offlineRegion: OfflineRegion): String {

    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
    }
}

`

@jeluchu jeluchu added the help wanted Extra attention is needed label Apr 8, 2019
@jeluchu jeluchu self-assigned this Apr 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant