Utils.kt 10.2 KB
package cn.feewee.amap3d

import android.content.Context
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Point
import android.location.Location
import android.view.View
import android.widget.Toast
import com.amap.api.maps.model.*
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.common.ResizeOptions
import com.facebook.imagepipeline.request.BasePostprocessor
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.WritableMap
import com.facebook.react.views.imagehelper.ImageSource
import kotlin.math.asin
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt

fun Float.toPx(): Int {
    return (this * Resources.getSystem().displayMetrics.density).toInt()
}

fun Int.toPx(): Int {
    return (this * Resources.getSystem().displayMetrics.density).toInt()
}

fun ReadableMap.toPoint(): Point {
    return Point(getDouble("x").toFloat().toPx(), getDouble("y").toFloat().toPx())
}

fun ReadableMap.toLatLng(): LatLng {
    return LatLng(getDouble("latitude"), getDouble("longitude"))
}

fun ReadableMap.toLatLonPoint(): LatLonPoint {
    return LatLonPoint(getDouble("latitude"), getDouble("longitude"))
}

fun ReadableArray.toLatLngList(): List<LatLng> {
    return (0 until size()).map {
        getMap(it)!!.toLatLng()
    }
}

fun LatLng.toJson(): WritableMap {
    return Arguments.createMap().apply {
        putDouble("latitude", latitude)
        putDouble("longitude", longitude)
    }
}

fun Poi.toJson(): WritableMap {
    return Arguments.createMap().apply {
        putMap("position", coordinate.toJson())
        putString("id", poiId)
        putString("name", name)
    }
}

fun CameraPosition.toJson(): WritableMap {
    return Arguments.createMap().apply {
        putMap("target", target.toJson())
        putDouble("zoom", zoom.toDouble())
        putDouble("tilt", tilt.toDouble())
        putDouble("bearing", bearing.toDouble())
    }
}

fun Location.toJson(): WritableMap {
    return Arguments.createMap().apply {
        putDouble("timestamp", time.toDouble())
        putMap("coords", Arguments.createMap().apply {
            putDouble("latitude", latitude)
            putDouble("longitude", longitude)
            putDouble("latitude", latitude)
            putDouble("accuracy", accuracy.toDouble())
            putDouble("heading", bearing.toDouble())
            putDouble("speed", speed.toDouble())
        })
    }
}

fun LatLngBounds.toJson(): WritableMap {
    return Arguments.createMap().apply {
        putMap("southwest", southwest.toJson())
        putMap("northeast", northeast.toJson())
    }
}

fun ReadableMap.getFloat(key: String): Float? {
    if (hasKey(key)) return getDouble(key).toFloat()
    return null
}

fun getEventTypeConstants(vararg list: String): Map<String, Any> {
    return list.associateWith { mapOf("phasedRegistrationNames" to mapOf("bubbled" to it)) }
}

fun View.fetchImage(source: ReadableMap, callback: (BitmapDescriptor) -> Unit) {
    val uri = ImageSource(context, source.getString("uri")).uri
    val request = ImageRequestBuilder.newBuilderWithSource(uri).let {
        it.postprocessor = object : BasePostprocessor() {
            override fun process(bitmap: Bitmap) {
                callback(BitmapDescriptorFactory.fromBitmap(bitmap))
            }
        }
        if (source.hasKey("width") && source.hasKey("height")) {
            it.resizeOptions = ResizeOptions.forDimensions(
                source.getInt("width").toPx(),
                source.getInt("height").toPx()
            )
        }
        it.build()
    }
    Fresco.getImagePipeline().fetchDecodedImage(request, this)
}

/**
 * 把LatLonPoint对象转化为LatLon对象
 */
fun LatLonPoint.convertToLatLng(): LatLng {
    return LatLng(latitude, longitude)
}

/**
 * 把LatLng对象转化为LatLonPoint对象
 */
fun LatLng.convertToLatLonPoint(): LatLonPoint {
    return LatLonPoint(latitude, longitude)
}

/**
 * 计算两点之间的距离
 */
fun calculateDistance(start: LatLng, end: LatLng): Int {
    var x1 = start.longitude
    var y1 = start.latitude
    var x2 = end.longitude
    var y2 = end.latitude
    val NF_pi = 0.01745329251994329 // 弧度 PI/180
    x1 *= NF_pi
    y1 *= NF_pi
    x2 *= NF_pi
    y2 *= NF_pi
    val sinx1 = sin(x1)
    val siny1 = sin(y1)
    val cosx1 = cos(x1)
    val cosy1 = cos(y1)
    val sinx2 = sin(x2)
    val siny2 = sin(y2)
    val cosx2 = cos(x2)
    val cosy2 = cos(y2)
    val v1 = DoubleArray(3)
    v1[0] = cosy1 * cosx1 - cosy2 * cosx2
    v1[1] = cosy1 * sinx1 - cosy2 * sinx2
    v1[2] = siny1 - siny2
    val dist = sqrt(v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2])
    return (asin(dist / 2) * 12742001.5798544).toInt()
}

fun show(context: Context, info: String) {
    Toast.makeText(context.applicationContext, info, Toast.LENGTH_LONG).show()
}

fun show(context: Context, info: Int) {
    Toast.makeText(context.applicationContext, info, Toast.LENGTH_LONG).show()
}

fun showerror(context: Context, rCode: Int) {
    fun logError(info: String, errorCode: Int) {
        val sb = StringBuilder()
        for (i in 0 until 80) {
            sb.append("=")
        }
        print(sb.toString())
        print("                                   错误信息                                     ")
        print(sb.toString())
        print(info)
        print("错误码: $errorCode")
        print("                                                                               ")
        print("如果需要更多信息,请根据错误码到以下地址进行查询")
        print("  http://lbs.amap.com/api/android-sdk/guide/map-tools/error-code/")
        print("如若仍无法解决问题,请将全部log信息提交到工单系统,多谢合作")
        print(sb.toString())
    }

    try {
        when (rCode) {
            1001 -> throw AMapException(AMapException.AMAP_SIGNATURE_ERROR)
            1002 -> throw AMapException(AMapException.AMAP_INVALID_USER_KEY)
            1003 -> throw AMapException(AMapException.AMAP_SERVICE_NOT_AVAILBALE)
            1004 -> throw AMapException(AMapException.AMAP_DAILY_QUERY_OVER_LIMIT)
            1005 -> throw AMapException(AMapException.AMAP_ACCESS_TOO_FREQUENT)
            1006 -> throw AMapException(AMapException.AMAP_INVALID_USER_IP)
            1007 -> throw AMapException(AMapException.AMAP_INVALID_USER_DOMAIN)
            1008 -> throw AMapException(AMapException.AMAP_INVALID_USER_SCODE)
            1009 -> throw AMapException(AMapException.AMAP_USERKEY_PLAT_NOMATCH)
            1010 -> throw AMapException(AMapException.AMAP_IP_QUERY_OVER_LIMIT)
            1011 -> throw AMapException(AMapException.AMAP_NOT_SUPPORT_HTTPS)
            1012 -> throw AMapException(AMapException.AMAP_INSUFFICIENT_PRIVILEGES)
            1013 -> throw AMapException(AMapException.AMAP_USER_KEY_RECYCLED)
            1100 -> throw AMapException(AMapException.AMAP_ENGINE_RESPONSE_ERROR)
            1101 -> throw AMapException(AMapException.AMAP_ENGINE_RESPONSE_DATA_ERROR)
            1102 -> throw AMapException(AMapException.AMAP_ENGINE_CONNECT_TIMEOUT)
            1103 -> throw AMapException(AMapException.AMAP_ENGINE_RETURN_TIMEOUT)
            1200 -> throw AMapException(AMapException.AMAP_SERVICE_INVALID_PARAMS)
            1201 -> throw AMapException(AMapException.AMAP_SERVICE_MISSING_REQUIRED_PARAMS)
            1202 -> throw AMapException(AMapException.AMAP_SERVICE_ILLEGAL_REQUEST)
            1203 -> throw AMapException(AMapException.AMAP_SERVICE_UNKNOWN_ERROR)
            1800 -> throw AMapException(AMapException.AMAP_CLIENT_ERRORCODE_MISSSING)
            1801 -> throw AMapException(AMapException.AMAP_CLIENT_ERROR_PROTOCOL)
            1802 -> throw AMapException(AMapException.AMAP_CLIENT_SOCKET_TIMEOUT_EXCEPTION)
            1803 -> throw AMapException(AMapException.AMAP_CLIENT_URL_EXCEPTION)
            1804 -> throw AMapException(AMapException.AMAP_CLIENT_UNKNOWHOST_EXCEPTION)
            1806 -> throw AMapException(AMapException.AMAP_CLIENT_NETWORK_EXCEPTION)
            1900 -> throw AMapException(AMapException.AMAP_CLIENT_UNKNOWN_ERROR)
            1901 -> throw AMapException(AMapException.AMAP_CLIENT_INVALID_PARAMETER)
            1902 -> throw AMapException(AMapException.AMAP_CLIENT_IO_EXCEPTION)
            1903 -> throw AMapException(AMapException.AMAP_CLIENT_NULLPOINT_EXCEPTION)
            2000 -> throw AMapException(AMapException.AMAP_SERVICE_TABLEID_NOT_EXIST)
            2001 -> throw AMapException(AMapException.AMAP_ID_NOT_EXIST)
            2002 -> throw AMapException(AMapException.AMAP_SERVICE_MAINTENANCE)
            2003 -> throw AMapException(AMapException.AMAP_ENGINE_TABLEID_NOT_EXIST)
            2100 -> throw AMapException(AMapException.AMAP_NEARBY_INVALID_USERID)
            2101 -> throw AMapException(AMapException.AMAP_NEARBY_KEY_NOT_BIND)
            2200 -> throw AMapException(AMapException.AMAP_CLIENT_UPLOADAUTO_STARTED_ERROR)
            2201 -> throw AMapException(AMapException.AMAP_CLIENT_USERID_ILLEGAL)
            2202 -> throw AMapException(AMapException.AMAP_CLIENT_NEARBY_NULL_RESULT)
            2203 -> throw AMapException(AMapException.AMAP_CLIENT_UPLOAD_TOO_FREQUENT)
            2204 -> throw AMapException(AMapException.AMAP_CLIENT_UPLOAD_LOCATION_ERROR)
            3000 -> throw AMapException(AMapException.AMAP_ROUTE_OUT_OF_SERVICE)
            3001 -> throw AMapException(AMapException.AMAP_ROUTE_NO_ROADS_NEARBY)
            3002 -> throw AMapException(AMapException.AMAP_ROUTE_FAIL)
            3003 -> throw AMapException(AMapException.AMAP_OVER_DIRECTION_RANGE)
            4000 -> throw AMapException(AMapException.AMAP_SHARE_LICENSE_IS_EXPIRED)
            4001 -> throw AMapException(AMapException.AMAP_SHARE_FAILURE)
            else -> {
                Toast.makeText(context, "查询失败:$rCode", Toast.LENGTH_LONG).show()
                logError("查询失败", rCode)
            }
        }
    } catch (e: Exception) {
        Toast.makeText(context.applicationContext, e.message, Toast.LENGTH_LONG).show()
        e.message?.let { logError(it, rCode) }
    }
}