Code Monkey home page Code Monkey logo

mapboxu's Introduction

Imagen Promocional

API Download Download API

README LANGUAGES

  • Español
  • English (Soon)

mapboxu's People

Contributors

jeluchu avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

zack1191

mapboxu's Issues

Offline Mapbox

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 = [email protected]
    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
    }
}

`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.