Skip to content

Commit

Permalink
feat(google-maps): add fitBounds to Map object
Browse files Browse the repository at this point in the history
* feat(google-maps): add fitBounds to Google Map

* Update build.gradle

* fmt
  • Loading branch information
ItsChaceD authored Jun 28, 2023
1 parent 6784a92 commit f4ae690
Show file tree
Hide file tree
Showing 11 changed files with 146 additions and 2 deletions.
17 changes: 17 additions & 0 deletions google-maps/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ export default MyMap;
* [`enableAccessibilityElements(...)`](#enableaccessibilityelements)
* [`enableCurrentLocation(...)`](#enablecurrentlocation)
* [`setPadding(...)`](#setpadding)
* [`fitBounds(...)`](#fitbounds)
* [`setOnBoundsChangedListener(...)`](#setonboundschangedlistener)
* [`setOnCameraIdleListener(...)`](#setoncameraidlelistener)
* [`setOnCameraMoveStartedListener(...)`](#setoncameramovestartedlistener)
Expand Down Expand Up @@ -613,6 +614,22 @@ setPadding(padding: MapPadding) => Promise<void>
--------------------


### fitBounds(...)

```typescript
fitBounds(bounds: LatLngBounds, padding?: number | undefined) => Promise<void>
```

Sets the map viewport to contain the given bounds.

| Param | Type | Description |
| ------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| **`bounds`** | <code>LatLngBounds</code> | The bounds to fit in the viewport. |
| **`padding`** | <code>number</code> | Optional padding to apply in pixels. The bounds will be fit in the part of the map that remains after padding is removed. |

--------------------


### setOnBoundsChangedListener(...)

```typescript
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,11 @@ class CapacitorGoogleMap(
return googleMap?.projection?.visibleRegion?.latLngBounds ?: throw BoundsNotFoundError()
}

fun fitBounds(bounds: LatLngBounds, padding: Int) {
val cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding)
googleMap?.animateCamera(cameraUpdate)
}

private fun getScaledPixels(bridge: Bridge, pixels: Int): Int {
// Get the screen's density scale
val scale = bridge.activity.resources.displayMetrics.density
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,32 @@ class CapacitorGoogleMapsPlugin : Plugin() {
}
}

@PluginMethod
fun fitBounds(call: PluginCall) {
try {
val id = call.getString("id")
id ?: throw InvalidMapIdError()

val map = maps[id]
map ?: throw MapNotFoundError()

val boundsObject =
call.getObject("bounds") ?: throw InvalidArgumentsError("bounds is missing")

val padding = call.getInt("padding", 0)!!

CoroutineScope(Dispatchers.Main).launch {
val bounds = createLatLngBounds(boundsObject)
map.fitBounds(bounds, padding)
call.resolve()
}
} catch (e: GoogleMapsError) {
handleError(call, e)
} catch (e: Exception) {
handleError(call, e)
}
}

@PluginMethod
fun mapBoundsExtend(call: PluginCall) {
try {
Expand Down
28 changes: 27 additions & 1 deletion google-maps/e2e-tests/src/pages/Map/Bounds.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { GoogleMap } from '@capacitor/google-maps';
import { GoogleMap, LatLngBounds } from '@capacitor/google-maps';
import {
IonButton,
IonCol,
Expand Down Expand Up @@ -68,6 +68,29 @@ const BoundsMapPage: React.FC = () => {
}
}

async function fitBounds() {
setCommandOutput('');
try {
const bounds = new LatLngBounds({
southwest: {
lat: lat - 1,
lng: lng - 1,
},
center: {
lat,
lng,
},
northeast: {
lat: lat + 1,
lng: lng + 1,
},
});
await map!.fitBounds(bounds, 50);
} catch (err: any) {
setCommandOutput(err.message);
}
}

async function boundsContainsPoint() {
setCommandOutput('');
try {
Expand Down Expand Up @@ -108,6 +131,9 @@ const BoundsMapPage: React.FC = () => {
<IonButton expand="block" id="getBoundsButton" onClick={getBounds}>
Get Bounds
</IonButton>
<IonButton expand="block" id="fitBoundsButton" onClick={fitBounds}>
Fit Bounds
</IonButton>
<IonRow>
<IonCol size="3">
<IonLabel id="latLabel">Lat</IonLabel>
Expand Down
1 change: 1 addition & 0 deletions google-maps/ios/Plugin/CapacitorGoogleMapsPlugin.m
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
CAP_PLUGIN_METHOD(setPadding, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(onScroll, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(getMapBounds, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(fitBounds, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(mapBoundsContains, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(mapBoundsExtend, CAPPluginReturnPromise);
)
24 changes: 24 additions & 0 deletions google-maps/ios/Plugin/CapacitorGoogleMapsPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,30 @@ public class CapacitorGoogleMapsPlugin: CAPPlugin, GMSMapViewDelegate {
}
}

@objc func fitBounds(_ 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 boundsObject = call.getObject("bounds") else {
throw GoogleMapErrors.invalidArguments("Invalid bounds provided")
}

let bounds = try getGMSCoordinateBounds(boundsObject)
let padding = CGFloat(call.getInt("padding", 0))

map.fitBounds(bounds: bounds, padding: padding)
call.resolve()
} catch {
handleError(call, error: error)
}
}

@objc func mapBoundsExtend(_ call: CAPPluginCall) {
do {
guard let boundsObject = call.getObject("bounds") else {
Expand Down
7 changes: 7 additions & 0 deletions google-maps/ios/Plugin/Map.swift
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,13 @@ public class Map {
return GMSCoordinateBounds(region: self.mapViewController.GMapView.projection.visibleRegion())
}

func fitBounds(bounds: GMSCoordinateBounds, padding: CGFloat) {
DispatchQueue.main.sync {
let cameraUpdate = GMSCameraUpdate.fit(bounds, withPadding: padding)
self.mapViewController.GMapView.animate(with: cameraUpdate)
}
}

private func getFrameOverflowBounds(frame: CGRect, mapBounds: CGRect) -> [CGRect] {
var intersections: [CGRect] = []

Expand Down
7 changes: 7 additions & 0 deletions google-maps/src/implementation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,12 @@ export interface EnableClusteringArgs {
minClusterSize?: number;
}

export interface FitBoundsArgs {
id: string;
bounds: LatLngBounds;
padding?: number;
}

export interface CapacitorGoogleMapsPlugin extends Plugin {
create(options: CreateMapArgs): Promise<void>;
addMarker(args: AddMarkerArgs): Promise<{ id: string }>;
Expand All @@ -189,6 +195,7 @@ export interface CapacitorGoogleMapsPlugin extends Plugin {
onScroll(args: OnScrollArgs): Promise<void>;
dispatchMapEvent(args: { id: string; focus: boolean }): Promise<void>;
getMapBounds(args: { id: string }): Promise<LatLngBounds>;
fitBounds(args: FitBoundsArgs): Promise<void>;
mapBoundsContains(
args: MapBoundsContainsArgs,
): Promise<{ contains: boolean }>;
Expand Down
12 changes: 11 additions & 1 deletion google-maps/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-namespace */
import {
LatLngBounds,
MapType,
Marker,
Polygon,
Expand All @@ -9,7 +10,16 @@ import {
} from './definitions';
import { GoogleMap } from './map';

export { GoogleMap, MapType, Marker, Polygon, Circle, Polyline, StyleSpan };
export {
GoogleMap,
LatLngBounds,
MapType,
Marker,
Polygon,
Circle,
Polyline,
StyleSpan,
};

declare global {
export namespace JSX {
Expand Down
14 changes: 14 additions & 0 deletions google-maps/src/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ export interface GoogleMapInterface {
enableAccessibilityElements(enabled: boolean): Promise<void>;
enableCurrentLocation(enabled: boolean): Promise<void>;
setPadding(padding: MapPadding): Promise<void>;
/**
* Sets the map viewport to contain the given bounds.
* @param bounds The bounds to fit in the viewport.
* @param padding Optional padding to apply in pixels. The bounds will be fit in the part of the map that remains after padding is removed.
*/
fitBounds(bounds: LatLngBounds, padding?: number): Promise<void>;
setOnBoundsChangedListener(
callback?: MapListenerCallback<CameraIdleCallbackData>,
): Promise<void>;
Expand Down Expand Up @@ -489,6 +495,14 @@ export class GoogleMap {
);
}

async fitBounds(bounds: LatLngBounds, padding?: number): Promise<void> {
return CapacitorGoogleMaps.fitBounds({
id: this.id,
bounds,
padding,
});
}

initScrolling(): void {
const ionContents = document.getElementsByTagName('ion-content');

Expand Down
7 changes: 7 additions & 0 deletions google-maps/src/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import type {
OnScrollArgs,
MapBoundsContainsArgs,
EnableClusteringArgs,
FitBoundsArgs,
MapBoundsExtendArgs,
AddPolygonsArgs,
RemovePolygonsArgs,
Expand Down Expand Up @@ -248,6 +249,12 @@ export class CapacitorGoogleMapsWeb
});
}

async fitBounds(_args: FitBoundsArgs): Promise<void> {
const map = this.maps[_args.id].map;
const bounds = this.getLatLngBounds(_args.bounds);
map.fitBounds(bounds, _args.padding);
}

async addMarkers(_args: AddMarkersArgs): Promise<{ ids: string[] }> {
const markerIds: string[] = [];
const map = this.maps[_args.id];
Expand Down

0 comments on commit f4ae690

Please sign in to comment.