Skip to content

Commit

Permalink
refactor(android): refactor MapView commands
Browse files Browse the repository at this point in the history
  • Loading branch information
mfazekas committed Sep 3, 2023
1 parent 2ef75ff commit bf1b185
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 84 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -895,52 +895,52 @@ open class RCTMGLMapView(private val mContext: Context, var mManager: RCTMGLMapV

// region Callbacks

fun getCenter(callbackID: String?) {
fun getCenter(response: CommandResponse) {
var center = mMap!!.cameraState!!.center

sendResponse(callbackID, {
response.success {
val array: WritableArray = WritableNativeArray()
array.pushDouble(center.longitude())
array.pushDouble(center.latitude())
it.putArray("center", array)
})
}
}

fun getZoom(callbackID: String?) {
fun getZoom(response: CommandResponse) {
var zoom = mMap!!.cameraState!!.zoom

sendResponse(callbackID, {
response.success {
it.putDouble("zoom", zoom)
})
}
}

private fun getDisplayDensity(): Float {
return mContext.resources.displayMetrics.density
}

fun getCoordinateFromView(callbackID: String?, pixel: ScreenCoordinate) {
fun getCoordinateFromView(pixel: ScreenCoordinate, response: CommandResponse) {
val density: Float = getDisplayDensity()
val screenCoordinate = ScreenCoordinate(pixel.x * density, pixel.y * density)

val coordinate = mMap!!.coordinateForPixel(screenCoordinate)

sendResponse(callbackID, {
response.success {
it.putArray("coordinateFromView", coordinate.toReadableArray())
})
}
}

fun getPointInView(callbackID: String?, coordinate: Point) {
fun getPointInView(coordinate: Point, response: CommandResponse) {
val point = mMap!!.pixelForCoordinate(coordinate)

sendResponse(callbackID, {
response.success {
val array: WritableArray = WritableNativeArray()
array.pushDouble(point.x)
array.pushDouble(point.y)
it.putArray("pointInView", array)
})
}
}

fun queryRenderedFeaturesAtPoint(callbackID: String?, point: PointF, filter: Expression?, layerIDs: List<String>?) {
fun queryRenderedFeaturesAtPoint(point: PointF, filter: Expression?, layerIDs: List<String>?, response: CommandResponse) {
if (mMap == null) {
Logger.e("queryRenderedFeaturesAtPoint", "mapbox map is null")
return
Expand All @@ -955,16 +955,16 @@ open class RCTMGLMapView(private val mContext: Context, var mManager: RCTMGLMapV
for (i in features.value!!) {
featuresList.add(i.feature)
}
sendResponse(callbackID) {
response.success {
it.putString("data", FeatureCollection.fromFeatures(featuresList).toJson())
}
} else {
Logger.e("queryRenderedFeaturesAtPoint", features.error ?: "n/a")
response.error(features.error ?: "n/a")
}
}
}

fun queryRenderedFeaturesInRect(callbackID: String?, rect: RectF, filter: Expression?, layerIDs: List<String>?) {
fun queryRenderedFeaturesInRect(rect: RectF, filter: Expression?, layerIDs: List<String>?, response: CommandResponse) {
val size = mMap!!.getMapOptions().size
val screenBox = if (rect.isEmpty()) ScreenBox(ScreenCoordinate(0.0, 0.0), ScreenCoordinate(size?.width!!.toDouble(), size?.height!!.toDouble())) else ScreenBox(
ScreenCoordinate(rect.right.toDouble(), rect.bottom.toDouble() ),
Expand All @@ -980,18 +980,16 @@ open class RCTMGLMapView(private val mContext: Context, var mManager: RCTMGLMapV
featuresList.add(i.feature)
}

val payload: WritableMap = WritableNativeMap()
payload.putString("data", FeatureCollection.fromFeatures(featuresList).toJson())

var event = AndroidCallbackEvent(this, callbackID, payload)
mManager.handleEvent(event)
response.success {
it.putString("data", FeatureCollection.fromFeatures(featuresList).toJson())
}
} else {
Logger.e("queryRenderedFeaturesInRect", features.error ?: "n/a")
response.error(features.error ?: "n/a")
}
}
}

fun querySourceFeatures(callbackID: String?, sourceId: String, filter: Expression?, sourceLayerIDs: List<String>?) {
fun querySourceFeatures(sourceId: String, filter: Expression?, sourceLayerIDs: List<String>?, response: CommandResponse) {
mMap?.querySourceFeatures(
sourceId,
SourceQueryOptions(sourceLayerIDs, (filter ?: Value.nullValue()) as Value),
Expand All @@ -1002,80 +1000,59 @@ open class RCTMGLMapView(private val mContext: Context, var mManager: RCTMGLMapV
featuresList.add(i.feature)
}

val payload: WritableMap = WritableNativeMap()
payload.putString("data", FeatureCollection.fromFeatures(featuresList).toJson())

var event = AndroidCallbackEvent(this, callbackID, payload)
mManager.handleEvent(event)
response.success {
payload.putString("data", FeatureCollection.fromFeatures(featuresList).toJson())
}
} else {
Logger.e("querySourceFeatures", features.error ?: "n/a")
response.error(features.error ?: "n/a")
}
}
}

fun sendResponse(callbackID: String?, buildPayload: (map: WritableMap) -> Unit) {
val payload: WritableMap = WritableNativeMap()
buildPayload(payload)
var event = AndroidCallbackEvent(this, callbackID, payload)
mManager.handleEvent(event)
}

fun getVisibleBounds(callbackID: String?) {
fun getVisibleBounds(response: CommandResponse) {
val bounds = mMap!!.coordinateBoundsForCamera(mMap!!.cameraState.toCameraOptions())

sendResponse(callbackID, {
response.success {
it.putArray("visibleBounds", bounds.toReadableArray())
})
}
}

fun takeSnap(callbackID: String?, writeToDisk: Boolean) {
fun takeSnap(writeToDisk: Boolean, response: CommandResponse) {
mapView.snapshot { snapshot ->
if (snapshot == null) {
Logger.e("takeSnap", "snapshot failed")

sendResponse(callbackID, {
it.putNull("data")
it.putString("error", "no snapshot")
})
response.error("snapshot failed")
} else {
val uri: String = if (writeToDisk) BitmapUtils.createTempFile(
mContext,
snapshot
) else BitmapUtils.createBase64(snapshot)

sendResponse(callbackID, {
response.success {
it.putString("uri", uri)
})
}
}
}
}

fun queryTerrainElevation(callbackID: String?, longitude: Double, latitude: Double) {
fun queryTerrainElevation(longitude: Double, latitude: Double, response: CommandResponse) {
val result = mMap?.getElevation(Point.fromLngLat(longitude, latitude))

sendResponse(callbackID, {response ->
if (result != null) {
response.putDouble("data", result)
} else {
Logger.e("queryTerrainElevation", "no elevation data")

response.putNull("data")
response.putString("error", "no elevation")
if (result != null) {
response.success {
it.putDouble("data", result)
}
})
} else {
response.error("no elevation data")
}
}

fun clearData(callbackID: String?) {
fun clearData(response: CommandResponse) {
mapView.getMapboxMap().clearData { expected ->
sendResponse(callbackID) { response ->
if (expected.isError()) {
response.putNull("data")
response.putString("error", expected.error!!.toString())
} else {
response.putBoolean("data", true)
}
if (expected.isError()) {
response.error(expected.error!!.toString())
} else {
response.success { it.putBoolean("data", true) }
}

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ import com.mapbox.rctmgl.events.constants.EventKeys
import com.facebook.react.common.MapBuilder
import com.mapbox.maps.extension.style.layers.properties.generated.ProjectionName
import com.mapbox.maps.plugin.gestures.gestures
<<<<<<< HEAD
=======
import com.mapbox.maps.plugin.logo.logo
import com.mapbox.rctmgl.events.AndroidCallbackEvent
>>>>>>> ee35502d (refactor(android): refactor MapView commands)
import com.mapbox.rctmgl.utils.ConvertUtils
import com.mapbox.rctmgl.utils.ExpressionParser
import com.mapbox.rctmgl.utils.Logger
Expand All @@ -34,6 +39,11 @@ fun ReadableArray.asArrayString(): Array<String> {
return result
}

interface CommandResponse {
fun success(builder: (WritableMap) -> Unit)
fun error(message: String)
}

open class RCTMGLMapViewManager(context: ReactApplicationContext) :
AbstractEventEmitter<RCTMGLMapView>(context) {
private val mViews: MutableMap<Int, RCTMGLMapView>
Expand Down Expand Up @@ -253,31 +263,52 @@ open class RCTMGLMapViewManager(context: ReactApplicationContext) :
);
}

fun sendResponse(mapView: RCTMGLMapView, callbackId: String, responseBuilder: (WritableMap) -> Unit) {
val payload: WritableMap = WritableNativeMap()
responseBuilder(payload)
var event = AndroidCallbackEvent(mapView, callbackId, payload)
handleEvent(event)
}

override fun receiveCommand(mapView: RCTMGLMapView, command: String, args: ReadableArray?) {
val callbackId = args!!.getString(0);
// allows method calls to work with componentDidMount
val mapboxMap = mapView.getMapboxMap()
?: // mapView.enqueuePreRenderMapMethod(commandID, args);
return
val response = object : CommandResponse {
override fun success(builder: (WritableMap) -> Unit) {
sendResponse(mapView, callbackId, builder)
}

override fun error(message: String) {
Logger.e(REACT_CLASS, "Command: ${command} failed with: ${message}")
sendResponse(mapView, callbackId) {
it.putNull("data")
it.putString("error", message)
}
}
}
when (command) {
"queryTerrainElevation" -> {
val coords = args!!.getArray(1)
mapView.queryTerrainElevation(
args.getString(0),
coords.getDouble(0),
coords.getDouble(1)
coords.getDouble(1),
response
)
}
"getZoom" -> {
mapView.getZoom(args!!.getString(0));
mapView.getZoom(response)
}
"getCenter" -> {
mapView.getCenter(args!!.getString(0));
mapView.getCenter(response)
}
"getPointInView" -> {
mapView.getPointInView(args!!.getString(0), args.getArray(1).toCoordinate())
mapView.getPointInView(args.getArray(1).toCoordinate(), response)
}
"getCoordinateFromView" -> {
mapView.getCoordinateFromView(args!!.getString(0), args.getArray(1).toScreenCoordinate());
mapView.getCoordinateFromView(args.getArray(1).toScreenCoordinate(), response)
}
"setSourceVisibility" -> {
mapView!!.setSourceVisibility(
Expand All @@ -288,43 +319,43 @@ open class RCTMGLMapViewManager(context: ReactApplicationContext) :
}
"queryRenderedFeaturesAtPoint" -> {
mapView.queryRenderedFeaturesAtPoint(
args!!.getString(0),
ConvertUtils.toPointF(args!!.getArray(1)),
ExpressionParser.from(args!!.getArray(2)),
ConvertUtils.toStringList(args!!.getArray(3))
);
ConvertUtils.toStringList(args!!.getArray(3)),
response
)
}
"queryRenderedFeaturesInRect" -> {
val layerIds = ConvertUtils.toStringList(args!!.getArray(3))
mapView.queryRenderedFeaturesInRect(
args!!.getString(0),
ConvertUtils.toRectF(args.getArray(1)),
ExpressionParser.from(args!!.getArray(2)),
if (layerIds.size == 0) null else layerIds
);
if (layerIds.size == 0) null else layerIds,
response
)
}
"querySourceFeatures" -> {
val sourceLayerIds = ConvertUtils.toStringList(args!!.getArray(3))
mapView.querySourceFeatures(
args!!.getString(0),
args!!.getString(1),
ExpressionParser.from(args!!.getArray(2)),
if (sourceLayerIds.size == 0) null else sourceLayerIds
if (sourceLayerIds.size == 0) null else sourceLayerIds,
response
);
}
"getVisibleBounds" -> {
mapView.getVisibleBounds(args!!.getString(0));
mapView.getVisibleBounds(response)
}
"takeSnap" -> {
mapView.takeSnap(args!!.getString(0), args!!.getBoolean(1))
mapView.takeSnap(args!!.getBoolean(1), response)
}
"setHandledMapChangedEvents" -> {
args?.let {
mapView.setHandledMapChangedEvents(it.getArray(1).asArrayString());
}
}
"clearData" -> {
mapView.clearData(args!!.getString(0))
mapView.clearData(response)
}
else -> {
Logger.w("RCTMGLMapView.receiveCommand", "unexpected command: ${command}")
Expand Down

0 comments on commit bf1b185

Please sign in to comment.