diff --git a/README.md b/README.md index c4870c94..50d683f3 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,10 @@ Vue({ * [`removeCircles(...)`](#removecircles) * [`addPolylines(...)`](#addpolylines) * [`removePolylines(...)`](#removepolylines) +* [`addFeatures(...)`](#addfeatures) +* [`getFeatureBounds(...)`](#getfeaturebounds) +* [`removeFeature(...)`](#removefeature) +* [`removeFeatures(...)`](#removefeatures) * [`destroy()`](#destroy) * [`setCamera(...)`](#setcamera) * [`getMapType()`](#getmaptype) @@ -391,6 +395,7 @@ Vue({ * [`setOnClusterInfoWindowClickListener(...)`](#setonclusterinfowindowclicklistener) * [`setOnInfoWindowClickListener(...)`](#setoninfowindowclicklistener) * [`setOnMapClickListener(...)`](#setonmapclicklistener) +* [`setOnFeatureClickListener(...)`](#setonfeatureclicklistener) * [`setOnMarkerClickListener(...)`](#setonmarkerclicklistener) * [`setOnPolygonClickListener(...)`](#setonpolygonclicklistener) * [`setOnCircleClickListener(...)`](#setoncircleclicklistener) @@ -633,6 +638,67 @@ removePolylines(ids: string[]) => Promise -------------------- +### addFeatures(...) + +```typescript +addFeatures(type: FeatureType, data: any, idPropertyName?: string | undefined, styles?: FeatureStyles | undefined) => Promise +``` + +| Param | Type | +| -------------------- | ------------------------------------------------------- | +| **`type`** | FeatureType | +| **`data`** | any | +| **`idPropertyName`** | string | +| **`styles`** | FeatureStyles | + +**Returns:** Promise<string[]> + +-------------------- + + +### getFeatureBounds(...) + +```typescript +getFeatureBounds(featureId: string) => Promise +``` + +| Param | Type | +| --------------- | ------------------- | +| **`featureId`** | string | + +**Returns:** Promise<LatLngBounds> + +-------------------- + + +### removeFeature(...) + +```typescript +removeFeature(featureId: string) => Promise +``` + +| Param | Type | +| --------------- | ------------------- | +| **`featureId`** | string | + +-------------------- + + +### removeFeatures(...) + +```typescript +removeFeatures(featureIds: string[]) => Promise +``` + +Remove multiple GeoJSON features in a single plugin call. Feature IDs that are not found are ignored. + +| Param | Type | +| ---------------- | --------------------- | +| **`featureIds`** | string[] | + +-------------------- + + ### destroy() ```typescript @@ -866,6 +932,19 @@ setOnMapClickListener(callback?: MapListenerCallback | und -------------------- +### setOnFeatureClickListener(...) + +```typescript +setOnFeatureClickListener(callback?: MapListenerCallback | undefined) => Promise +``` + +| Param | Type | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| **`callback`** | MapListenerCallback<FeatureClickCallbackData> | + +-------------------- + + ### setOnMarkerClickListener(...) ```typescript @@ -1158,6 +1237,11 @@ Describes the style for some region of a polyline. | **`segments`** | number | The length of this span in number of segments. | +#### FeatureStyles + +Feature styles, identified by the feature id + + #### CameraConfig Configuration properties for a Google Map Camera @@ -1243,6 +1327,17 @@ Controls for setting padding on the 'visible' region of the view. | **`longitude`** | number | +#### FeatureClickCallbackData + +| Prop | Type | +| ---------------- | ------------------------------------------------------------ | +| **`mapId`** | string | +| **`featureId`** | string | +| **`latitude`** | number | +| **`longitude`** | number | +| **`properties`** | Record | + + #### PolygonClickCallbackData | Prop | Type | @@ -1296,6 +1391,14 @@ Supports markers of either "legacy" or "advanced" types. ### Enums +#### FeatureType + +| Members | Value | Description | +| ------------- | ---------------------- | ----------- | +| **`Default`** | 'Default' | Default | +| **`GeoJSON`** | 'GeoJSON' | GeoJSON | + + #### MapType | Members | Value | Description | diff --git a/plugin/README.md b/plugin/README.md index c4870c94..50d683f3 100644 --- a/plugin/README.md +++ b/plugin/README.md @@ -373,6 +373,10 @@ Vue({ * [`removeCircles(...)`](#removecircles) * [`addPolylines(...)`](#addpolylines) * [`removePolylines(...)`](#removepolylines) +* [`addFeatures(...)`](#addfeatures) +* [`getFeatureBounds(...)`](#getfeaturebounds) +* [`removeFeature(...)`](#removefeature) +* [`removeFeatures(...)`](#removefeatures) * [`destroy()`](#destroy) * [`setCamera(...)`](#setcamera) * [`getMapType()`](#getmaptype) @@ -391,6 +395,7 @@ Vue({ * [`setOnClusterInfoWindowClickListener(...)`](#setonclusterinfowindowclicklistener) * [`setOnInfoWindowClickListener(...)`](#setoninfowindowclicklistener) * [`setOnMapClickListener(...)`](#setonmapclicklistener) +* [`setOnFeatureClickListener(...)`](#setonfeatureclicklistener) * [`setOnMarkerClickListener(...)`](#setonmarkerclicklistener) * [`setOnPolygonClickListener(...)`](#setonpolygonclicklistener) * [`setOnCircleClickListener(...)`](#setoncircleclicklistener) @@ -633,6 +638,67 @@ removePolylines(ids: string[]) => Promise -------------------- +### addFeatures(...) + +```typescript +addFeatures(type: FeatureType, data: any, idPropertyName?: string | undefined, styles?: FeatureStyles | undefined) => Promise +``` + +| Param | Type | +| -------------------- | ------------------------------------------------------- | +| **`type`** | FeatureType | +| **`data`** | any | +| **`idPropertyName`** | string | +| **`styles`** | FeatureStyles | + +**Returns:** Promise<string[]> + +-------------------- + + +### getFeatureBounds(...) + +```typescript +getFeatureBounds(featureId: string) => Promise +``` + +| Param | Type | +| --------------- | ------------------- | +| **`featureId`** | string | + +**Returns:** Promise<LatLngBounds> + +-------------------- + + +### removeFeature(...) + +```typescript +removeFeature(featureId: string) => Promise +``` + +| Param | Type | +| --------------- | ------------------- | +| **`featureId`** | string | + +-------------------- + + +### removeFeatures(...) + +```typescript +removeFeatures(featureIds: string[]) => Promise +``` + +Remove multiple GeoJSON features in a single plugin call. Feature IDs that are not found are ignored. + +| Param | Type | +| ---------------- | --------------------- | +| **`featureIds`** | string[] | + +-------------------- + + ### destroy() ```typescript @@ -866,6 +932,19 @@ setOnMapClickListener(callback?: MapListenerCallback | und -------------------- +### setOnFeatureClickListener(...) + +```typescript +setOnFeatureClickListener(callback?: MapListenerCallback | undefined) => Promise +``` + +| Param | Type | +| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| **`callback`** | MapListenerCallback<FeatureClickCallbackData> | + +-------------------- + + ### setOnMarkerClickListener(...) ```typescript @@ -1158,6 +1237,11 @@ Describes the style for some region of a polyline. | **`segments`** | number | The length of this span in number of segments. | +#### FeatureStyles + +Feature styles, identified by the feature id + + #### CameraConfig Configuration properties for a Google Map Camera @@ -1243,6 +1327,17 @@ Controls for setting padding on the 'visible' region of the view. | **`longitude`** | number | +#### FeatureClickCallbackData + +| Prop | Type | +| ---------------- | ------------------------------------------------------------ | +| **`mapId`** | string | +| **`featureId`** | string | +| **`latitude`** | number | +| **`longitude`** | number | +| **`properties`** | Record | + + #### PolygonClickCallbackData | Prop | Type | @@ -1296,6 +1391,14 @@ Supports markers of either "legacy" or "advanced" types. ### Enums +#### FeatureType + +| Members | Value | Description | +| ------------- | ---------------------- | ----------- | +| **`Default`** | 'Default' | Default | +| **`GeoJSON`** | 'GeoJSON' | GeoJSON | + + #### MapType | Members | Value | Description | diff --git a/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMap.kt b/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMap.kt index c0bc416b..ac862ed4 100644 --- a/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMap.kt +++ b/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMap.kt @@ -3,6 +3,8 @@ package com.capacitorjs.plugins.googlemaps import android.annotation.SuppressLint import android.graphics.* import android.location.Location +import android.os.Handler +import android.os.Looper import android.util.Log import android.view.MotionEvent import android.view.View @@ -16,8 +18,19 @@ import com.google.android.gms.maps.GoogleMap.* import com.google.android.gms.maps.model.* import com.google.maps.android.clustering.Cluster import com.google.maps.android.clustering.ClusterManager +import com.google.maps.android.data.Feature +import com.google.maps.android.data.geojson.GeoJsonFeature +import com.google.maps.android.data.geojson.GeoJsonGeometryCollection +import com.google.maps.android.data.geojson.GeoJsonLayer +import com.google.maps.android.data.geojson.GeoJsonLineString +import com.google.maps.android.data.geojson.GeoJsonMultiLineString +import com.google.maps.android.data.geojson.GeoJsonMultiPoint +import com.google.maps.android.data.geojson.GeoJsonMultiPolygon +import com.google.maps.android.data.geojson.GeoJsonPoint +import com.google.maps.android.data.geojson.GeoJsonPolygon import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel +import org.json.JSONObject import java.io.InputStream import java.net.URL @@ -45,12 +58,16 @@ class CapacitorGoogleMap( private val tileOverlays = HashMap() private val polygons = HashMap() private val circles = HashMap() - private val polylines = HashMap() + private val polylines = HashMap() + private val featureLayers = HashMap() + private var geoJsonLayer: GeoJsonLayer? = null + private val featureProperties = HashMap() private val markerIcons = HashMap() private var clusterManager: ClusterManager? = null private val isReadyChannel = Channel() private var debounceJob: Job? = null + private var lastTapCoordinate: LatLng? = null init { val bridge = delegate.bridge @@ -172,6 +189,14 @@ class CapacitorGoogleMap( val relativeLeft = offsetViewBounds.left event.setLocation(event.x - relativeLeft, event.y - relativeTop) + if (event.actionMasked == MotionEvent.ACTION_DOWN) { + lastTapCoordinate = null + } + if (event.actionMasked == MotionEvent.ACTION_UP) { + lastTapCoordinate = googleMap?.projection?.fromScreenLocation( + Point(event.x.toInt(), event.y.toInt()) + ) + } mapView.dispatchTouchEvent(event) } } @@ -415,6 +440,107 @@ class CapacitorGoogleMap( } } + fun addFeatures(type: String, data: JSONObject, idPropertyName: String?, styles: JSONObject?, callback: (ids: Result>) -> Unit) { + try { + googleMap ?: throw GoogleMapNotAvailable() + val featureIds: MutableList = mutableListOf() + + CoroutineScope(Dispatchers.Main).launch { + if (type == "GeoJSON") { + try { + val normalizedData = JSONObject(data.toString()) + val inputs = if (normalizedData.optString("type") == "FeatureCollection") { + val entries = normalizedData.getJSONArray("features") + (0 until entries.length()).map { entries.getJSONObject(it) } + } else { + listOf(normalizedData) + } + val propertiesById = HashMap() + inputs.forEach { input -> + val properties = input.optJSONObject("properties") ?: JSONObject() + val propertyId = idPropertyName?.let { properties.opt(it) } + val identifier = propertyId?.takeUnless { it == JSONObject.NULL } + ?: input.opt("id")?.takeUnless { it == JSONObject.NULL } + ?: java.util.UUID.randomUUID().toString() + input.put("id", identifier.toString()) + propertiesById[identifier.toString()] = properties + } + val tempLayer = GeoJsonLayer(null, normalizedData) + val layer = geoJsonLayer ?: GeoJsonLayer(googleMap, JSONObject()).also { + geoJsonLayer = it + it.addLayerToMap() + Handler(Looper.getMainLooper()).post { restoreFeatureMapListeners() } + } + tempLayer.features.forEach { + val featureLayer = CapacitorGoogleMapsFeatureLayer(layer, it, idPropertyName, styles) + val featureId = featureLayer.id + featureLayers.remove(featureId)?.renderedFeatures?.forEach { previous -> + layer.removeFeature(previous) + } + featureIds.add(featureId) + featureLayers[featureId] = featureLayer + featureProperties[featureId] = propertiesById[featureId] ?: JSONObject() + } + callback(Result.success(featureIds)) + } catch (e: Exception) { + callback(Result.failure(e)) + } + } else { + callback(Result.failure(InvalidArgumentsError("addFeatures: not supported for this feature type"))) + } + } + } catch (e: GoogleMapsError) { + callback(Result.failure(e)) + } + } + + fun getFeatureBounds(featureId: String, callback: (bounds: Result) -> Unit) { + try { + CoroutineScope(Dispatchers.Main).launch { + val featurelayer = featureLayers[featureId] + val feature = featurelayer?.originalFeature + if (feature != null) { + try { + (feature as GeoJsonFeature).let { + callback(Result.success(it.boundingBoxFromGeometry())) + } + } catch (e: Exception) { + callback(Result.failure(InvalidArgumentsError("getFeatureBounds: not supported for this feature type"))) + } + } else { + callback(Result.failure(InvalidArgumentsError("Could not find feature for feature id $featureId"))) + } + } + } catch(e: Exception) { + callback(Result.failure(InvalidArgumentsError("Could not find feature layer"))) + } + } + + fun removeFeature(featureId: String, callback: (error: GoogleMapsError?) -> Unit) { + CoroutineScope(Dispatchers.Main).launch { + val featurelayer = featureLayers[featureId] + if (featurelayer != null) { + featurelayer.renderedFeatures.forEach { geoJsonLayer?.removeFeature(it) } + featureLayers.remove(featureId) + featureProperties.remove(featureId) + callback(null) + } else { + callback(InvalidArgumentsError("Could not find feature for feature id $featureId")) + } + } + } + + fun removeFeatures(featureIds: List, callback: (error: GoogleMapsError?) -> Unit) { + CoroutineScope(Dispatchers.Main).launch { + featureIds.forEach { featureId -> + val featureLayer = featureLayers.remove(featureId) ?: return@forEach + featureLayer.renderedFeatures.forEach { geoJsonLayer?.removeFeature(it) } + featureProperties.remove(featureId) + } + callback(null) + } + } + private fun setClusterManagerRenderer(minClusterSize: Int?) { clusterManager?.renderer = CapacitorClusterManagerRenderer( delegate.bridge.context, @@ -441,6 +567,9 @@ class CapacitorGoogleMap( setClusterManagerRenderer(minClusterSize) setClusterListeners() + if (geoJsonLayer != null) { + Handler(Looper.getMainLooper()).post { restoreFeatureMapListeners() } + } // add existing markers to the cluster if (markers.isNotEmpty()) { @@ -1032,6 +1161,52 @@ class CapacitorGoogleMap( return data } + private fun GeoJsonFeature.boundingBoxFromGeometry(): LatLngBounds? { + val coordinates: MutableList = ArrayList() + + if (this.hasGeometry()) { + when (geometry.geometryType) { + "Point" -> coordinates.add((geometry as GeoJsonPoint).coordinates) + "MultiPoint" -> { + val points = (geometry as GeoJsonMultiPoint).points + for (point in points) { + coordinates.add(point.coordinates) + } + } + + "LineString" -> coordinates.addAll((geometry as GeoJsonLineString).coordinates) + "MultiLineString" -> { + val lines = (geometry as GeoJsonMultiLineString).lineStrings + for (line in lines) { + coordinates.addAll(line.coordinates) + } + } + + "Polygon" -> { + val lists = (geometry as GeoJsonPolygon).coordinates + for (list in lists) { + coordinates.addAll(list) + } + } + + "MultiPolygon" -> { + val polygons = (geometry as GeoJsonMultiPolygon).polygons + for (polygon in polygons) { + for (list in polygon.coordinates) { + coordinates.addAll(list) + } + } + } + } + } + + val builder = LatLngBounds.builder() + for (latLng in coordinates) { + builder.include(latLng) + } + return builder.build() + } + override fun onMapClick(point: LatLng) { val data = JSObject() data.put("mapId", this@CapacitorGoogleMap.id) @@ -1040,7 +1215,38 @@ class CapacitorGoogleMap( delegate.notify("onMapClick", data) } + private fun notifyFeatureClick(mapObject: Any): Boolean { + val feature = geoJsonLayer?.getFeature(mapObject) ?: return false + val featureId = feature.id ?: return false + val data = JSObject() + data.put("mapId", id) + data.put("featureId", featureId) + lastTapCoordinate?.let { coordinate -> + data.put("latitude", coordinate.latitude) + data.put("longitude", coordinate.longitude) + } + lastTapCoordinate = null + data.put("properties", featureProperties[featureId] ?: JSONObject()) + delegate.notify("onFeatureClick", data) + return true + } + + private fun restoreFeatureMapListeners() { + googleMap?.setOnMarkerClickListener { marker -> + if (notifyFeatureClick(marker)) false + else clusterManager?.onMarkerClick(marker) ?: onMarkerClick(marker) + } + googleMap?.setOnPolygonClickListener(this) + googleMap?.setOnPolylineClickListener(this) + googleMap?.setOnMarkerDragListener(this) + googleMap?.setOnInfoWindowClickListener { marker -> + if (clusterManager != null) clusterManager?.onInfoWindowClick(marker) + else onInfoWindowClick(marker) + } + } + override fun onMarkerClick(marker: Marker): Boolean { + if (notifyFeatureClick(marker)) return false val data = JSObject() data.put("mapId", this@CapacitorGoogleMap.id) data.put("markerId", marker.id) @@ -1053,6 +1259,7 @@ class CapacitorGoogleMap( } override fun onPolylineClick(polyline: Polyline) { + if (notifyFeatureClick(polyline)) return val data = JSObject() data.put("mapId", this@CapacitorGoogleMap.id) data.put("polylineId", polyline.id) @@ -1148,6 +1355,7 @@ class CapacitorGoogleMap( } override fun onPolygonClick(polygon: Polygon) { + if (notifyFeatureClick(polygon)) return val data = JSObject() data.put("mapId", this@CapacitorGoogleMap.id) data.put("polygonId", polygon.id) diff --git a/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMapsFeatureLayer.kt b/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMapsFeatureLayer.kt new file mode 100644 index 00000000..dc403215 --- /dev/null +++ b/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMapsFeatureLayer.kt @@ -0,0 +1,110 @@ +package com.capacitorjs.plugins.googlemaps + +import android.graphics.Color +import com.google.maps.android.data.Feature +import com.google.maps.android.data.Layer +import com.google.maps.android.data.Geometry +import com.google.maps.android.data.geojson.GeoJsonFeature +import com.google.maps.android.data.geojson.GeoJsonLayer +import com.google.maps.android.data.geojson.GeoJsonGeometryCollection +import com.google.maps.android.data.geojson.GeoJsonMultiPoint +import com.google.maps.android.data.geojson.GeoJsonMultiLineString +import com.google.maps.android.data.geojson.GeoJsonMultiPolygon +import com.google.maps.android.data.geojson.GeoJsonPolygonStyle +import com.google.maps.android.data.geojson.GeoJsonLineStringStyle +import org.json.JSONObject +import java.lang.Exception +import java.util.UUID + +class CapacitorGoogleMapsFeatureLayer( + layer: Layer, + feature: Feature, + idPropertyName: String?, + styles: JSONObject? +) { + var id: String = idPropertyName?.let { feature.getProperty(it) } ?: feature.id ?: UUID.randomUUID().toString() + var layer: Layer? = null + val renderedFeatures = mutableListOf() + val originalFeature = feature as GeoJsonFeature + + init { + (feature as? GeoJsonFeature)?.let { + val properties: HashMap = hashMapOf() + for (propertyKey in feature.propertyKeys) { + properties[propertyKey] = feature.getProperty(propertyKey) + } + val newFeature = + GeoJsonFeature( + feature.geometry, + id, + properties, + null + ) + this.layer = layer + + val featureLayer = (layer as GeoJsonLayer) + val polygonStyle = GeoJsonPolygonStyle() + val lineStyle = GeoJsonLineStringStyle() + polygonStyle.isClickable = true + lineStyle.isClickable = true + + if (styles != null) { + try { + val styleId = id ?: feature.id + val featureStyle = styleId?.let { styles.optJSONObject(it) } + if (featureStyle != null) { + polygonStyle.strokeColor = + processColor( + featureStyle.getString("strokeColor"), + featureStyle.getDouble("strokeOpacity") + ) + polygonStyle.strokeWidth = + featureStyle.getDouble("strokeWeight").toFloat() + polygonStyle.fillColor = + processColor( + featureStyle.getString("fillColor"), + featureStyle.getDouble("fillOpacity") + ) + polygonStyle.isGeodesic = + featureStyle.getBoolean("geodesic") + lineStyle.color = polygonStyle.strokeColor + lineStyle.width = polygonStyle.strokeWidth + lineStyle.isGeodesic = polygonStyle.isGeodesic + } + } catch (e: Exception) { + throw InvalidArgumentsError("Styles object contains invalid values") + } + } + + fun addGeometry(geometry: Geometry<*>?) { + when (geometry) { + is GeoJsonGeometryCollection -> geometry.geometries.forEach { addGeometry(it) } + is GeoJsonMultiPoint -> geometry.points.forEach { addGeometry(it) } + is GeoJsonMultiLineString -> geometry.lineStrings.forEach { addGeometry(it) } + is GeoJsonMultiPolygon -> geometry.polygons.forEach { addGeometry(it) } + else -> { + val part = GeoJsonFeature(geometry, id, properties, null) + part.polygonStyle = polygonStyle + part.lineStringStyle = lineStyle + renderedFeatures.add(part) + featureLayer.addFeature(part) + } + } + } + addGeometry(newFeature.geometry) + } + } + + private fun processColor(hex: String, opacity: Double): Int { + val colorInt = Color.parseColor(hex) + + val alpha = (opacity * 255.0).toInt() + val red = Color.red(colorInt) + val green = Color.green(colorInt) + val blue = Color.blue(colorInt) + + return Color.argb(alpha, red, green, blue) + } + + private fun JSONObject.getStyle(key: String) = this.getJSONObject(id).get(key) as T +} diff --git a/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMapsPlugin.kt b/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMapsPlugin.kt index 06ecab29..a1429d49 100644 --- a/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMapsPlugin.kt +++ b/plugin/android/src/main/java/com/capacitorjs/plugins/googlemaps/CapacitorGoogleMapsPlugin.kt @@ -683,6 +683,165 @@ class CapacitorGoogleMapsPlugin : Plugin(), OnMapsSdkInitializedCallback { } } + @PluginMethod + fun addFeatures(call: PluginCall) { + try { + val id = call.getString("id") + id ?: throw InvalidMapIdError() + + val map = maps[id] + map ?: throw MapNotFoundError() + + val type = + call.getString("type") + ?: throw InvalidArgumentsError("feature type is missing") + + val data = + call.getObject("data") + ?: throw InvalidArgumentsError("feature data is missing") + + val idPropertyName = call.getString("idPropertyName") ?: null + + val styles = call.getObject("styles") ?: null + + map.addFeatures( + type, + data, + idPropertyName, + styles + ) { result -> + try { + val ids = result.getOrThrow() + + val jsonIDs = JSONArray() + ids.forEach { jsonIDs.put(it) } + + val res = JSObject() + res.put("ids", jsonIDs) + call.resolve(res) + } catch (e: GoogleMapsError) { + handleError(call, e) + } catch (e: Exception) { + handleError(call, e) + } + } + } catch (e: GoogleMapsError) { + handleError(call, e) + } catch (e: Exception) { + handleError(call, e) + } + } + + @PluginMethod + fun getFeatureBounds(call: PluginCall) { + try { + val id = call.getString("id") + id ?: throw InvalidMapIdError() + + val map = maps[id] + map ?: throw MapNotFoundError() + + val featureId = + call.getString("featureId") + ?: throw InvalidArgumentsError("feature id is missing") + + map.getFeatureBounds(featureId) { result -> + try { + val featureBounds = result.getOrThrow() + + val southwest = JSObject() + southwest.put("lat", featureBounds?.southwest?.latitude) + southwest.put("lng", featureBounds?.southwest?.longitude) + + val center = JSObject() + center.put("lat", featureBounds?.center?.latitude) + center.put("lng", featureBounds?.center?.longitude) + + val northeast = JSObject() + northeast.put("lat", featureBounds?.northeast?.latitude) + northeast.put("lng", featureBounds?.northeast?.longitude) + + val bounds = JSObject() + bounds.put("southwest", southwest) + bounds.put("center", center) + bounds.put("northeast", northeast) + + val res = JSObject() + res.put("bounds", bounds) + call.resolve(res) + } catch (e: GoogleMapsError) { + handleError(call, e) + } catch (e: Exception) { + handleError(call, e) + } + } + } catch (e: GoogleMapsError) { + handleError(call, e) + } catch (e: Exception) { + handleError(call, e) + } + } + + @PluginMethod + fun removeFeature(call: PluginCall) { + try { + val id = call.getString("id") + id ?: throw InvalidMapIdError() + + val map = maps[id] + map ?: throw MapNotFoundError() + + val featureId = + call.getString("featureId") + ?: throw InvalidArgumentsError("feature id is missing") + + map.removeFeature(featureId) { + try { + call.resolve() + } catch (e: GoogleMapsError) { + handleError(call, e) + } catch (e: Exception) { + handleError(call, e) + } + } + } catch (e: GoogleMapsError) { + handleError(call, e) + } catch (e: Exception) { + handleError(call, e) + } + } + + @PluginMethod + fun removeFeatures(call: PluginCall) { + try { + val id = call.getString("id") + id ?: throw InvalidMapIdError() + + val featureIdsArray = call.getArray("featureIds") + ?: throw InvalidArgumentsError("featureIds are invalid or missing") + + val map = maps[id] + map ?: throw MapNotFoundError() + + val featureIds = mutableListOf() + for (i in 0 until featureIdsArray.length()) { + featureIds.add(featureIdsArray.getString(i)) + } + + map.removeFeatures(featureIds) { err -> + if (err != null) { + handleError(call, err) + } else { + call.resolve() + } + } + } catch (e: GoogleMapsError) { + handleError(call, e) + } catch (e: Exception) { + handleError(call, e) + } + } + @PluginMethod fun setCamera(call: PluginCall) { try { diff --git a/plugin/ios/Sources/CapacitorGoogleMapsPlugin/CapacitorGoogleMapsPlugin.swift b/plugin/ios/Sources/CapacitorGoogleMapsPlugin/CapacitorGoogleMapsPlugin.swift index 55a830ed..31b7f152 100644 --- a/plugin/ios/Sources/CapacitorGoogleMapsPlugin/CapacitorGoogleMapsPlugin.swift +++ b/plugin/ios/Sources/CapacitorGoogleMapsPlugin/CapacitorGoogleMapsPlugin.swift @@ -83,6 +83,10 @@ public class CapacitorGoogleMapsPlugin: CAPPlugin, GMSMapViewDelegate, CAPBridge CAPPluginMethod(name: "removeCircles", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "removePolygons", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "removePolylines", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "addFeatures", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "getFeatureBounds", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "removeFeature", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "removeFeatures", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "enableClustering", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "disableClustering", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "destroy", returnType: CAPPluginReturnPromise), @@ -599,6 +603,120 @@ public class CapacitorGoogleMapsPlugin: CAPPlugin, GMSMapViewDelegate, CAPBridge } } + @objc func addFeatures(_ call: CAPPluginCall) { + do { + guard let id = call.getString("id") else { + throw GoogleMapErrors.invalidMapId + } + + guard let map = self.maps[id] else { + throw GoogleMapErrors.mapNotFound + } + + guard let type = call.getString("type") else { + throw GoogleMapErrors.invalidArguments("feature type is missing") + } + + guard let data = call.getObject("data") else { + throw GoogleMapErrors.invalidArguments("feature data is missing") + } + + let idPropertyName = call.getString("idPropertyName") + + let styles = call.getObject("styles") + + let ids = try map.addFeatures(type: type, data: data, idPropertyName: idPropertyName, styles: styles) + + call.resolve(["ids": ids.map({ id in + return String(id) + })]) + } catch { + handleError(call, error: error) + } + } + + @objc func getFeatureBounds(_ call: CAPPluginCall) { + do { + guard let id = call.getString("id") else { + throw GoogleMapErrors.invalidMapId + } + + guard let map = self.maps[id] else { + throw GoogleMapErrors.mapNotFound + } + + guard let featureId = call.getString("featureId") else { + throw GoogleMapErrors.invalidArguments("feature id is missing") + } + + let bounds = try map.getFeatureBounds(featureId: featureId) + let center = GMSGeometryInterpolate(bounds.southWest, bounds.northEast, 0.5) + + call.resolve([ + "bounds": [ + "southwest": [ + "lat": bounds.southWest.latitude, + "lng": bounds.southWest.longitude + ], + "center": [ + "lat": center.latitude, + "lng": center.longitude + ], + "northeast": [ + "lat": bounds.northEast.latitude, + "lng": bounds.northEast.longitude + ] + ] + ]) + } catch { + handleError(call, error: error) + } + } + + @objc func removeFeature(_ call: CAPPluginCall) { + do { + guard let id = call.getString("id") else { + throw GoogleMapErrors.invalidMapId + } + + guard let map = self.maps[id] else { + throw GoogleMapErrors.mapNotFound + } + + guard let featureId = call.getString("featureId") else { + throw GoogleMapErrors.invalidArguments("feature id is missing") + } + + try map.removeFeature(featureId: featureId) + + call.resolve() + } catch { + handleError(call, error: error) + } + } + + @objc func removeFeatures(_ call: CAPPluginCall) { + do { + guard let id = call.getString("id") else { + throw GoogleMapErrors.invalidMapId + } + + guard let map = self.maps[id] else { + throw GoogleMapErrors.mapNotFound + } + + guard let featureIds = call.getArray("featureIds") as? [String] else { + throw GoogleMapErrors.invalidArguments("featureIds are invalid or missing") + } + + map.removeFeatures(featureIds: featureIds) { + call.resolve() + } + } catch { + handleError(call, error: error) + } + } + @objc func setCamera(_ call: CAPPluginCall) { do { guard let id = call.getString("id") else { @@ -1090,8 +1208,11 @@ public class CapacitorGoogleMapsPlugin: CAPPlugin, GMSMapViewDelegate, CAPBridge ]) } - // onPolygonClick, onPolylineClick, onCircleClick + // onFeatureClick (GeoJSON overlays), onPolygonClick, onPolylineClick, onCircleClick public func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) { + if notifyFeatureClick(mapView, overlay: overlay) { + return + } if let polygon = overlay as? GMSPolygon { self.notifyListeners("onPolygonClick", data: [ "mapId": self.findMapIdByMapView(mapView), @@ -1120,8 +1241,11 @@ public class CapacitorGoogleMapsPlugin: CAPPlugin, GMSMapViewDelegate, CAPBridge } } - // onClusterClick, onMarkerClick + // onFeatureClick (GeoJSON points), onClusterClick, onMarkerClick public func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { + if notifyFeatureClick(mapView, overlay: marker) { + return false + } if let cluster = marker.userData as? GMUCluster { var items: [[String: Any?]] = [] @@ -1155,6 +1279,25 @@ public class CapacitorGoogleMapsPlugin: CAPPlugin, GMSMapViewDelegate, CAPBridge return false } + private func notifyFeatureClick(_ mapView: GMSMapView, overlay: GMSOverlay) -> Bool { + guard let feature = overlay.userData as? GMUFeature, + let identifier = feature.identifier else { + return false + } + let mapId = self.findMapIdByMapView(mapView) + var eventData: [String: Any] = [ + "mapId": mapId, + "featureId": String(describing: identifier), + "properties": feature.properties ?? [:] + ] + if let coordinate = self.maps[mapId]?.consumeLastTapCoordinate() { + eventData["latitude"] = coordinate.latitude + eventData["longitude"] = coordinate.longitude + } + self.notifyListeners("onFeatureClick", data: eventData) + return true + } + // onMarkerDragStart public func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker) { self.notifyListeners("onMarkerDragStart", data: [ diff --git a/plugin/ios/Sources/CapacitorGoogleMapsPlugin/Map.swift b/plugin/ios/Sources/CapacitorGoogleMapsPlugin/Map.swift index 85a8953d..909848db 100644 --- a/plugin/ios/Sources/CapacitorGoogleMapsPlugin/Map.swift +++ b/plugin/ios/Sources/CapacitorGoogleMapsPlugin/Map.swift @@ -8,6 +8,29 @@ public struct LatLng: Codable { let lng: Double } +private final class MapTapCoordinateRecognizer: UITapGestureRecognizer, UIGestureRecognizerDelegate { + var onTouchBegan: ((CGPoint) -> Void)? + + init() { + super.init(target: nil, action: nil) + delegate = self + } + + override func touchesBegan(_ touches: Set, with event: UIEvent) { + if let touch = touches.first, let view { + onTouchBegan?(touch.location(in: view)) + } + super.touchesBegan(touches, with: event) + } + + func gestureRecognizer( + _ gestureRecognizer: UIGestureRecognizer, + shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer + ) -> Bool { + true + } +} + class GMViewController: UIViewController { var mapViewBounds: [String: Double]! var GMapView: GMSMapView! @@ -81,7 +104,10 @@ public class Map { var polygons = [Int: GMSPolygon]() var circles = [Int: GMSCircle]() var polylines = [Int: GMSPolyline]() + var features = [String: GMUGeometryRenderer]() var markerIcons = [String: UIImage]() + private var mapTapCoordinateRecognizer: MapTapCoordinateRecognizer? + private var lastTapCoordinate: CLLocationCoordinate2D? // swiftlint:disable identifier_name public static let MAP_TAG = 99999 @@ -130,7 +156,21 @@ public class Map { func finishMapConfiguration() { DispatchQueue.main.async { - self.mapViewController.GMapView.delegate = self.delegate + let mapView = self.mapViewController.GMapView! + mapView.delegate = self.delegate + + let tapRecognizer = MapTapCoordinateRecognizer() + tapRecognizer.cancelsTouchesInView = false + tapRecognizer.delaysTouchesBegan = false + tapRecognizer.delaysTouchesEnded = false + tapRecognizer.onTouchBegan = { [weak self, weak mapView] point in + guard let self, let mapView else { + return + } + self.lastTapCoordinate = mapView.projection.coordinate(for: point) + } + mapView.addGestureRecognizer(tapRecognizer) + self.mapTapCoordinateRecognizer = tapRecognizer if let styles = self.config.styles { do { @@ -476,6 +516,126 @@ public class Map { } } + func addFeatures(type: String, data: JSObject, idPropertyName: String?, styles: JSObject?) throws -> [String] { + guard type == "GeoJSON" else { + throw GoogleMapErrors.invalidArguments("addFeatures: not supported for this feature type") + } + let jsonData = try JSONSerialization.data(withJSONObject: data, options: []) + var featureIds: [String] = [] + + DispatchQueue.main.sync { + let geoJSONParser = GMUGeoJSONParser(data: jsonData) + geoJSONParser.parse() + + for container in geoJSONParser.features { + if let tempFeature = container as? GMUFeature { + let properties = tempFeature.properties ?? [:] + var featureId: String? = nil + if let propertyName = idPropertyName, let propertyId = properties[propertyName], !(propertyId is NSNull) { + featureId = String(describing: propertyId) + } + + if featureId == nil, let identifier = tempFeature.identifier, !(identifier is NSNull) { + featureId = String(describing: identifier) + } + featureId = featureId ?? UUID().uuidString + + if (featureId != nil) { + if let renderer = self.features[featureId!] { + renderer.clear() + self.features.removeValue(forKey: featureId!) + } + } + + let feature = GMUFeature(geometry: tempFeature.geometry, identifier: featureId, properties: properties, boundingBox: nil) + + if (featureId != nil) { + featureIds.append(featureId!) + } + + if (featureId != nil && styles != nil) { + if let stylesData = (styles! as [String: Any])[featureId!] as? [String: Any] { + if let strokeColor = stylesData["strokeColor"] as? String, + let strokeOpacity = stylesData["strokeOpacity"] as? Double, + let stroke = UIColor.init(hex: strokeColor)?.withAlphaComponent(strokeOpacity), + let fillColor = stylesData["fillColor"] as? String, + let fillOpacity = stylesData["fillOpacity"] as? Double, + let fill = UIColor.init(hex: fillColor)?.withAlphaComponent(fillOpacity) + { + let style = GMUStyle(styleID: "styleId", stroke: stroke, fill: fill, width: stylesData["strokeWeight"] as? Double ?? 1, scale: 2, heading: 0, anchor: CGPoint(x: 0, y: 0), iconUrl: nil, title: nil, hasFill: true, hasStroke: true) + feature.style = style + } + } + } + + func flattenGeometry(_ geometry: GMUGeometry) -> [GMUFeature] { + if let collection = geometry as? GMUGeometryCollection { + return collection.geometries.flatMap { flattenGeometry($0) } + } + let part = GMUFeature(geometry: geometry, identifier: featureId, properties: properties, boundingBox: nil) + part.style = feature.style + return [part] + } + let renderer = GMUGeometryRenderer(map: self.mapViewController.GMapView, geometries: flattenGeometry(feature.geometry)) + renderer.render() + for overlay in renderer.mapOverlays() { + overlay.userData = feature + overlay.isTappable = true + } + + if (featureId != nil) { + self.features[featureId!] = renderer + } + } + } + } + + return featureIds + } + + func getFeatureBounds(featureId: String) throws -> GMSCoordinateBounds { + if let renderer = self.features[featureId] { + var bounds: GMSCoordinateBounds! + + DispatchQueue.main.sync { + bounds = renderer.getBounds() + } + + return bounds + } else { + throw GoogleMapErrors.unhandledError("feature not found") + } + } + + func removeFeature(featureId: String) throws { + if let renderer = self.features[featureId] { + DispatchQueue.main.async { + renderer.clear() + self.features.removeValue(forKey: featureId) + } + } else { + throw GoogleMapErrors.unhandledError("feature not found") + } + } + + func removeFeatures(featureIds: [String], completion: @escaping () -> Void) { + DispatchQueue.main.async { + featureIds.forEach { featureId in + guard let renderer = self.features.removeValue(forKey: featureId) else { + return + } + + renderer.clear() + } + completion() + } + } + + func consumeLastTapCoordinate() -> CLLocationCoordinate2D? { + defer { lastTapCoordinate = nil } + return lastTapCoordinate + } + func setCamera(config: GoogleMapCameraConfig) throws { let currentCamera = self.mapViewController.GMapView.camera @@ -805,3 +965,39 @@ extension UIImage { return resizedImage } } + +extension GMUGeometryRenderer { + func getBounds() -> GMSCoordinateBounds { + var bounds = GMSCoordinateBounds.init() + + for overlay in self.mapOverlays() { + if let circle = overlay as? GMSCircle { + bounds = bounds.includingBounds(circle.getBounds()) + } + if let groundOverlay = overlay as? GMSGroundOverlay, let groundOverlayBounds = groundOverlay.bounds { + bounds = bounds.includingBounds(groundOverlayBounds) + } + if let marker = overlay as? GMSMarker { + bounds = bounds.includingCoordinate(marker.position) + } + if let polygon = overlay as? GMSPolygon, let polygonPath = polygon.path { + bounds = bounds.includingPath(polygonPath) + } + if let polyline = overlay as? GMSPolyline, let polylinePath = polyline.path { + bounds = bounds.includingPath(polylinePath) + } + } + + return bounds + } +} + +extension GMSCircle { + func getBounds() -> GMSCoordinateBounds { + var bounds = GMSCoordinateBounds.init( + coordinate: GMSGeometryOffset(self.position, self.radius * sqrt(2.0), 225), + coordinate: GMSGeometryOffset(self.position, self.radius * sqrt(2.0), 45) + ) + return bounds + } +} \ No newline at end of file diff --git a/plugin/src/definitions.ts b/plugin/src/definitions.ts index 5d0a716e..776c6138 100644 --- a/plugin/src/definitions.ts +++ b/plugin/src/definitions.ts @@ -130,6 +130,34 @@ export interface Polyline extends google.maps.PolylineOptions { styleSpans?: StyleSpan[]; } +/** + * Feature types + */ +export enum FeatureType { + /** + * Default + */ + Default = 'Default', + /** + * GeoJSON + */ + GeoJSON = 'GeoJSON', +} + +/** + * Feature styles, identified by the feature id + */ +export interface FeatureStyles { + [key: string]: { + strokeColor: string; + strokeOpacity: number; + strokeWeight: number; + fillColor: string; + fillOpacity: number; + geodesic: boolean; + }; +} + /** * Describes the style for some region of a polyline. */ @@ -517,6 +545,14 @@ export interface MarkerClickCallbackData extends MarkerCallbackData { mapId: string; } +export interface FeatureClickCallbackData { + mapId: string; + featureId: string; + latitude: number; + longitude: number; + properties: Record; +} + export interface PolygonClickCallbackData { mapId: string; polygonId: string; diff --git a/plugin/src/implementation.ts b/plugin/src/implementation.ts index 357f0d10..10f8f6fb 100644 --- a/plugin/src/implementation.ts +++ b/plugin/src/implementation.ts @@ -13,6 +13,8 @@ import type { Polygon, Polyline, TileOverlay, + FeatureType, + FeatureStyles, } from './definitions'; /** @@ -93,6 +95,7 @@ export interface RemoveCirclesArgs { id: string; circleIds: string[]; } + export interface AddPolylinesArgs { id: string; polylines: Polyline[]; @@ -103,6 +106,29 @@ export interface RemovePolylinesArgs { polylineIds: string[]; } +export interface AddFeatureArgs { + id: string; + type: FeatureType; + data: any; + idPropertyName?: string; + styles?: FeatureStyles; +} + +export interface GetFeatureBoundsArgs { + id: string; + featureId: string; +} + +export interface RemoveFeatureArgs { + id: string; + featureId: string; +} + +export interface RemoveFeaturesArgs { + id: string; + featureIds: string[]; +} + export interface CameraArgs { id: string; config: CameraConfig; @@ -195,6 +221,10 @@ export interface CapacitorGoogleMapsPlugin extends Plugin { addCircles(args: AddCirclesArgs): Promise<{ ids: string[] }>; removeCircles(args: RemoveCirclesArgs): Promise; addPolylines(args: AddPolylinesArgs): Promise<{ ids: string[] }>; + addFeatures(args: AddFeatureArgs): Promise<{ ids: string[] }>; + getFeatureBounds(args: GetFeatureBoundsArgs): Promise<{ bounds: LatLngBounds }>; + removeFeature(args: RemoveFeatureArgs): Promise; + removeFeatures(args: RemoveFeaturesArgs): Promise; removePolylines(args: RemovePolylinesArgs): Promise; enableClustering(args: EnableClusteringArgs): Promise; disableClustering(args: { id: string }): Promise; diff --git a/plugin/src/index.ts b/plugin/src/index.ts index 1900cdad..0e216832 100644 --- a/plugin/src/index.ts +++ b/plugin/src/index.ts @@ -1,8 +1,18 @@ /* eslint-disable @typescript-eslint/no-namespace */ -import { LatLngBounds, MapType, Marker, Polygon, Circle, Polyline, StyleSpan } from './definitions'; +import { + LatLngBounds, + MapType, + Marker, + Polygon, + Circle, + Polyline, + StyleSpan, + FeatureType, + FeatureStyles, +} from './definitions'; import { GoogleMap } from './map'; -export { GoogleMap, LatLngBounds, MapType, Marker, Polygon, Circle, Polyline, StyleSpan }; +export { GoogleMap, LatLngBounds, MapType, Marker, Polygon, Circle, Polyline, StyleSpan, FeatureType, FeatureStyles }; declare global { export namespace JSX { diff --git a/plugin/src/map.ts b/plugin/src/map.ts index 73f064b4..61322763 100644 --- a/plugin/src/map.ts +++ b/plugin/src/map.ts @@ -11,6 +11,7 @@ import type { CameraMoveStartedCallbackData, ClusterClickCallbackData, MapClickCallbackData, + FeatureClickCallbackData, MarkerClickCallbackData, MyLocationButtonClickCallbackData, Polygon, @@ -20,6 +21,8 @@ import type { Polyline, PolylineCallbackData, TileOverlay, + FeatureType, + FeatureStyles, } from './definitions'; import { LatLngBounds, MapType } from './definitions'; import type { CreateMapArgs } from './implementation'; @@ -48,6 +51,13 @@ export interface GoogleMapInterface { removeCircles(ids: string[]): Promise; addPolylines(polylines: Polyline[]): Promise; removePolylines(ids: string[]): Promise; + addFeatures(type: FeatureType, data: any, idPropertyName?: string, styles?: FeatureStyles): Promise; + getFeatureBounds(featureId: string): Promise; + removeFeature(featureId: string): Promise; + /** + * Remove multiple GeoJSON features in a single plugin call. Feature IDs that are not found are ignored. + */ + removeFeatures(featureIds: string[]): Promise; destroy(): Promise; setCamera(config: CameraConfig): Promise; /** @@ -79,6 +89,7 @@ export interface GoogleMapInterface { setOnClusterInfoWindowClickListener(callback?: MapListenerCallback): Promise; setOnInfoWindowClickListener(callback?: MapListenerCallback): Promise; setOnMapClickListener(callback?: MapListenerCallback): Promise; + setOnFeatureClickListener(callback?: MapListenerCallback): Promise; setOnMarkerClickListener(callback?: MapListenerCallback): Promise; setOnPolygonClickListener(callback?: MapListenerCallback): Promise; setOnCircleClickListener(callback?: MapListenerCallback): Promise; @@ -124,6 +135,7 @@ export class GoogleMap { private onClusterInfoWindowClickListener?: PluginListenerHandle; private onInfoWindowClickListener?: PluginListenerHandle; private onMapClickListener?: PluginListenerHandle; + private onFeatureClickListener?: PluginListenerHandle; private onPolylineClickListener?: PluginListenerHandle; private onMarkerClickListener?: PluginListenerHandle; private onPolygonClickListener?: PluginListenerHandle; @@ -468,6 +480,41 @@ export class GoogleMap { }); } + async addFeatures(type: FeatureType, data: any, idPropertyName?: string, styles?: FeatureStyles): Promise { + const res = await CapacitorGoogleMaps.addFeatures({ + id: this.id, + type, + data, + idPropertyName, + styles, + }); + + return res.ids; + } + + async getFeatureBounds(id: string): Promise { + const res = await CapacitorGoogleMaps.getFeatureBounds({ + id: this.id, + featureId: id, + }); + + return new LatLngBounds(res.bounds); + } + + async removeFeature(id: string): Promise { + return CapacitorGoogleMaps.removeFeature({ + id: this.id, + featureId: id, + }); + } + + async removeFeatures(featureIds: string[]): Promise { + return CapacitorGoogleMaps.removeFeatures({ + id: this.id, + featureIds, + }); + } + /** * Destroy the current instance of the map */ @@ -823,6 +870,20 @@ export class GoogleMap { } } + /** + * Set the event listener for clicks on features added with addFeatures. + * The featureId matches the ID returned by addFeatures. Calling without a callback removes the listener. + * + * @param callback + * @returns + */ + async setOnFeatureClickListener(callback?: MapListenerCallback): Promise { + await this.onFeatureClickListener?.remove(); + this.onFeatureClickListener = callback + ? await CapacitorGoogleMaps.addListener('onFeatureClick', this.generateCallback(callback)) + : undefined; + } + /** * Set the event listener on the map for 'onPolygonClick' events. * @@ -1051,6 +1112,11 @@ export class GoogleMap { this.onMapClickListener = undefined; } + if (this.onFeatureClickListener) { + await this.onFeatureClickListener.remove(); + this.onFeatureClickListener = undefined; + } + if (this.onPolylineClickListener) { this.onPolylineClickListener.remove(); this.onPolylineClickListener = undefined; diff --git a/plugin/src/web.ts b/plugin/src/web.ts index 3c409eb7..2664240a 100644 --- a/plugin/src/web.ts +++ b/plugin/src/web.ts @@ -2,8 +2,8 @@ import { WebPlugin } from '@capacitor/core'; import type { Cluster, onClusterClickHandler } from '@googlemaps/markerclusterer'; import { MarkerClusterer, SuperClusterAlgorithm } from '@googlemaps/markerclusterer'; -import type { Marker, TileOverlay } from './definitions'; -import { MapType, LatLngBounds } from './definitions'; +import type { LatLngBoundsInterface, LatLng, Marker, TileOverlay } from './definitions'; +import { FeatureType, MapType, LatLngBounds } from './definitions'; import type { AddTileOverlayArgs, AddMarkerArgs, @@ -29,6 +29,10 @@ import type { AddPolylinesArgs, RemovePolylinesArgs, RemoveTileOverlayArgs, + AddFeatureArgs, + GetFeatureBoundsArgs, + RemoveFeatureArgs, + RemoveFeaturesArgs, } from './implementation'; export class CapacitorGoogleMapsWeb extends WebPlugin implements CapacitorGoogleMapsPlugin { @@ -440,6 +444,99 @@ export class CapacitorGoogleMapsWeb extends WebPlugin implements CapacitorGoogle } } + async addFeatures(args: AddFeatureArgs): Promise<{ ids: string[] }> { + const featureIds: string[] = []; + const map = this.maps[args.id]; + + const features = + args.type === FeatureType.GeoJSON + ? map.map.data.addGeoJson(args.data, args.idPropertyName ? { idPropertyName: args.idPropertyName } : null) + : [map.map.data.add(args.data)]; + + for (const feature of features) { + let featureId = feature.getId(); + if (featureId === undefined) { + featureId = window.crypto.randomUUID(); + const properties: Record = {}; + feature.forEachProperty((value, name) => { + properties[name] = value; + }); + map.map.data.remove(feature); + map.map.data.add( + new google.maps.Data.Feature({ + id: featureId, + geometry: feature.getGeometry(), + properties, + }), + ); + } + featureIds.push(featureId.toString()); + } + + if (args.styles) { + map.map.data.setStyle((feature) => { + const featureId = feature.getId(); + return featureId !== undefined ? (args.styles?.[featureId] as any) : null; + }); + } + + return { + ids: featureIds, + }; + } + + async getFeatureBounds(args: GetFeatureBoundsArgs): Promise<{ bounds: LatLngBounds }> { + if (!args.featureId) { + throw new Error('Feature id not set.'); + } + + const map = this.maps[args.id]; + const feature = map.map.data.getFeatureById(args.featureId); + + if (!feature) { + throw new Error(`Feature '${args.featureId}' could not be found.`); + } + + const bounds = new google.maps.LatLngBounds(); + + feature?.getGeometry()?.forEachLatLng((latLng) => { + bounds.extend(latLng); + }); + + return { + bounds: new LatLngBounds({ + southwest: bounds.getSouthWest().toJSON() as LatLng, + center: bounds.getCenter().toJSON() as LatLng, + northeast: bounds.getNorthEast().toJSON() as LatLng, + } as LatLngBoundsInterface), + }; + } + + async removeFeature(args: RemoveFeatureArgs): Promise { + if (!args.featureId) { + throw new Error('Feature id not set.'); + } + + const map = this.maps[args.id]; + + const feature = map.map.data.getFeatureById(args.featureId); + if (!feature) { + throw new Error(`Feature '${args.featureId}' could not be found.`); + } + + map.map.data.remove(feature); + } + + async removeFeatures(args: RemoveFeaturesArgs): Promise { + const map = this.maps[args.id]; + for (const featureId of args.featureIds) { + const feature = map.map.data.getFeatureById(featureId); + if (feature) { + map.map.data.remove(feature); + } + } + } + async enableClustering(_args: EnableClusteringArgs): Promise { const markers: google.maps.marker.AdvancedMarkerElement[] = []; @@ -677,6 +774,24 @@ export class CapacitorGoogleMapsWeb extends WebPlugin implements CapacitorGoogle }); }); + map.data.addListener('click', (event: google.maps.Data.MouseEvent) => { + if (!event.latLng) { + return; + } + + const properties: Record = {}; + event.feature.forEachProperty((value, name) => { + properties[name] = value; + }); + this.notifyListeners('onFeatureClick', { + mapId, + featureId: event.feature.getId()?.toString(), + latitude: event.latLng.lat(), + longitude: event.latLng.lng(), + properties, + }); + }); + this.notifyListeners('onMapReady', { mapId: mapId, });