npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@nfdoom/capacitor-google-maps

v4.5.14

Published

Google maps on Capacitor

Downloads

5

Readme

@capacitor/google-maps

Google maps on Capacitor

Install

npm install @capacitor/google-maps
npx cap sync

API Keys

To use the Google Maps SDK on any platform, API keys associated with an account with billing enabled are required. These can be obtained from the Google Cloud Console. This is required for all three platforms, Android, iOS, and Javascript. Additional information about obtaining these API keys can be found in the Google Maps documentation for each platform.

iOS

The Google Maps SDK supports the use of showing the users current location via enableCurrentLocation(bool). To use this, Apple requires privacy descriptions to be specified in Info.plist:

  • NSLocationAlwaysUsageDescription (Privacy - Location Always Usage Description)
  • NSLocationWhenInUseUsageDescription (Privacy - Location When In Use Usage Description)

Read about Configuring Info.plist in the iOS Guide for more information on setting iOS permissions in Xcode.

The Google Maps SDK currently does not support running on simulators using the new M1-based Macbooks. This is a known and acknowledged issue and requires a fix from Google. If you are developing on a M1 Macbook, building and running on physical devices is still supported and is the recommended approach.

Android

The Google Maps SDK for Android requires you to add your API key to the AndroidManifest.xml file in your project.

<meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_API_KEY_HERE"/>

To use certain location features, the SDK requires the following permissions to also be added to your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Variables

This plugin will use the following project variables (defined in your app's variables.gradle file):

  • $googleMapsPlayServicesVersion: version of com.google.android.gms:play-services-maps (default: 18.0.2)
  • $googleMapsUtilsVersion: version of com.google.maps.android:android-maps-utils (default: 2.3.0)
  • $googleMapsKtxVersion: version of com.google.maps.android:maps-ktx (default: 3.4.0)
  • $googleMapsUtilsKtxVersion: version of com.google.maps.android:maps-utils-ktx (default: 3.4.0)
  • $kotlinxCoroutinesVersion: version of org.jetbrains.kotlinx:kotlinx-coroutines-android and org.jetbrains.kotlinx:kotlinx-coroutines-core (default: 1.6.3)
  • $androidxCoreKTXVersion: version of androidx.core:core-ktx (default: 1.8.0)
  • $kotlin_version: version of org.jetbrains.kotlin:kotlin-stdlib-jdk7 (default: 1.7.0)

Usage

The Google Maps Capacitor plugin ships with a web component that must be used to render the map in your application as it enables us to embed the native view more effectively on iOS. The plugin will automatically register this web component for use in your application.

For Angular users, you will get an error warning that this web component is unknown to the Angular compiler. This is resolved by modifying the module that declares your component to allow for custom web components.

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

Include this component in your HTML and assign it an ID so that you can easily query for that element reference later.

<capacitor-google-map id="map"></capacitor-google-map>

On Android, the map is rendered beneath the entire webview, and uses this component to manage its positioning during scrolling events. This means that as the developer, you must ensure that the webview is transparent all the way through the layers to the very bottom. In a typically Ionic application, that means setting transparency on elements such as IonContent and the root HTML tag to ensure that it can be seen. If you can't see your map on Android, this should be the first thing you check.

On iOS, we render the map directly into the webview and so the same transparency effects are not required. We are investigating alternate methods for Android still and hope to resolve this better in a future update.

The Google Map element itself comes unstyled, so you should style it to fit within the layout of your page structure. Because we're rendering a view into this slot, by itself the element has no width or height, so be sure to set those explicitly.

capacitor-google-map {
  display: inline-block;
  width: 275px;
  height: 400px;
}

Next, we should create the map reference. This is done by importing the GoogleMap class from the Capacitor plugin and calling the create method, and passing in the required parameters.

import { GoogleMap } from '@capacitor/google-maps';

const apiKey = 'YOUR_API_KEY_HERE';

const mapRef = document.getElementById('map');

const newMap = await GoogleMap.create({
  id: 'my-map', // Unique identifier for this map instance
  element: mapRef, // reference to the capacitor-google-map element
  apiKey: apiKey, // Your Google Maps API Key
  config: {
    center: {
      // The initial position to be rendered by the map
      lat: 33.6,
      lng: -117.9,
    },
    zoom: 8, // The initial zoom level to be rendered by the map
  },
});

At this point, your map should be created within your application. Using the returned reference to the map, you can easily interact with your map in a number of way, a few of which are shown here.

const newMap = await GoogleMap.create({...});

// Add a marker to the map
const markerId = await newMap.addMarker({
  coordinate: {
    lat: 33.6,
    lng: -117.9
  }
});

// Move the map programmatically
await newMap.setCamera({
  coordinate: {
    lat: 33.6,
    lng: -117.9
  }
});

// Enable marker clustering
await newMap.enableClustering();

// Handle marker click
await newMap.setOnMarkerClickListener((event) => {...});

// Clean up map reference
await newMap.destroy();

Full Examples

Angular

import { GoogleMap } from '@capacitor/google-maps';

@Component({
  template: `
    <capacitor-google-map #map></capacitor-google-map>
    <button (click)="createMap()">Create Map</button>
  `,
  styles: [
    `
      capacitor-google-map {
        display: inline-block;
        width: 275px;
        height: 400px;
      }
    `,
  ],
})
export class MyMap {
  @ViewChild('map')
  mapRef: ElementRef<HTMLElement>;
  newMap: GoogleMap;

  async createMap() {
    this.newMap = await GoogleMap.create({
      id: 'my-cool-map',
      element: this.mapRef.nativeElement,
      apiKey: environment.apiKey,
      config: {
        center: {
          lat: 33.6,
          lng: -117.9,
        },
        zoom: 8,
      },
    });
  }
}

React

import { GoogleMap } from '@capacitor/google-maps';
import { useRef } from 'react';

const MyMap: React.FC = () => {
  const mapRef = useRef<HTMLElement>();
  let newMap: GoogleMap;

  async function createMap() {
    if (!mapRef.current) return;

    newMap = await GoogleMap.create({
      id: 'my-cool-map',
      element: mapRef.current,
      apiKey: process.env.REACT_APP_YOUR_API_KEY_HERE,
      config: {
        center: {
          lat: 33.6,
          lng: -117.9
        },
        zoom: 8
      }
    })
  }

  return (
    <div className="component-wrapper">
      <capacitor-google-map ref={mapRef} style={{
        display: 'inline-block',
        width: 275,
        height: 400
      }}></capacitor-google-map>

      <button onClick={createMap}>Create Map</button>
    </div>
  )
}

export default MyMap;

Javascript

<capacitor-google-map id="map"></capacitor-google-map>
<button onclick="createMap()">Create Map</button>

<style>
  capacitor-google-map {
    display: inline-block;
    width: 275px;
    height: 400px;
  }
</style>

<script>
  import { GoogleMap } from '@capacitor/google-maps';

  const createMap = async () => {
    const mapRef = document.getElementById('map');

    const newMap = await GoogleMap.create({
      id: 'my-map', // Unique identifier for this map instance
      element: mapRef, // reference to the capacitor-google-map element
      apiKey: 'YOUR_API_KEY_HERE', // Your Google Maps API Key
      config: {
        center: {
          // The initial position to be rendered by the map
          lat: 33.6,
          lng: -117.9,
        },
        zoom: 8, // The initial zoom level to be rendered by the map
      },
    });
  };
</script>

API

create(...)

create(options: CreateMapArgs, callback?: MapListenerCallback<MapReadyCallbackData> | undefined) => Promise<GoogleMap>

| Param | Type | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | options | CreateMapArgs | | callback | MapListenerCallback<MapReadyCallbackData> |

Returns: Promise<GoogleMap>


enableClustering(...)

enableClustering(minClusterSize?: number | undefined) => Promise<void>

| Param | Type | Description | | -------------------- | ------------------- | --------------------------------------------------------------------------------------- | | minClusterSize | number | The minimum number of markers that can be clustered together. The default is 4 markers. |


disableClustering()

disableClustering() => Promise<void>

addMarker(...)

addMarker(marker: Marker) => Promise<string>

| Param | Type | | ------------ | ----------------------------------------- | | marker | Marker |

Returns: Promise<string>


addMarkers(...)

addMarkers(markers: Marker[]) => Promise<string[]>

| Param | Type | | ------------- | --------------------- | | markers | Marker[] |

Returns: Promise<string[]>


removeMarker(...)

removeMarker(id: string) => Promise<void>

| Param | Type | | -------- | ------------------- | | id | string |


removeMarkers(...)

removeMarkers(ids: string[]) => Promise<void>

| Param | Type | | --------- | --------------------- | | ids | string[] |


destroy()

destroy() => Promise<void>

setCamera(...)

setCamera(config: CameraConfig) => Promise<void>

| Param | Type | | ------------ | ----------------------------------------------------- | | config | CameraConfig |


getMapType()

getMapType() => Promise<MapType>

Get current map type

Returns: Promise<MapType>


setMapType(...)

setMapType(mapType: MapType) => Promise<void>

| Param | Type | | ------------- | ------------------------------------------- | | mapType | MapType |


enableIndoorMaps(...)

enableIndoorMaps(enabled: boolean) => Promise<void>

| Param | Type | | ------------- | -------------------- | | enabled | boolean |


enableTrafficLayer(...)

enableTrafficLayer(enabled: boolean) => Promise<void>

| Param | Type | | ------------- | -------------------- | | enabled | boolean |


enableAccessibilityElements(...)

enableAccessibilityElements(enabled: boolean) => Promise<void>

| Param | Type | | ------------- | -------------------- | | enabled | boolean |


enableCurrentLocation(...)

enableCurrentLocation(enabled: boolean) => Promise<void>

| Param | Type | | ------------- | -------------------- | | enabled | boolean |


setPadding(...)

setPadding(padding: MapPadding) => Promise<void>

| Param | Type | | ------------- | ------------------------------------------------- | | padding | MapPadding |


setOnBoundsChangedListener(...)

setOnBoundsChangedListener(callback?: MapListenerCallback<CameraIdleCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<CameraIdleCallbackData> |


setOnCameraIdleListener(...)

setOnCameraIdleListener(callback?: MapListenerCallback<CameraIdleCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<CameraIdleCallbackData> |


setOnCameraMoveStartedListener(...)

setOnCameraMoveStartedListener(callback?: MapListenerCallback<CameraMoveStartedCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<CameraMoveStartedCallbackData> |


setOnClusterClickListener(...)

setOnClusterClickListener(callback?: MapListenerCallback<ClusterClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<ClusterClickCallbackData> |


setOnClusterInfoWindowClickListener(...)

setOnClusterInfoWindowClickListener(callback?: MapListenerCallback<ClusterClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<ClusterClickCallbackData> |


setOnInfoWindowClickListener(...)

setOnInfoWindowClickListener(callback?: MapListenerCallback<MarkerClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<MarkerClickCallbackData> |


setOnMapClickListener(...)

setOnMapClickListener(callback?: MapListenerCallback<MapClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<MapClickCallbackData> |


setOnMarkerClickListener(...)

setOnMarkerClickListener(callback?: MapListenerCallback<MarkerClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<MarkerClickCallbackData> |


setOnMarkerDragStartListener(...)

setOnMarkerDragStartListener(callback?: MapListenerCallback<MarkerClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<MarkerClickCallbackData> |


setOnMarkerDragListener(...)

setOnMarkerDragListener(callback?: MapListenerCallback<MarkerClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<MarkerClickCallbackData> |


setOnMarkerDragEndListener(...)

setOnMarkerDragEndListener(callback?: MapListenerCallback<MarkerClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<MarkerClickCallbackData> |


setOnMyLocationButtonClickListener(...)

setOnMyLocationButtonClickListener(callback?: MapListenerCallback<MyLocationButtonClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<MyLocationButtonClickCallbackData> |


setOnMyLocationClickListener(...)

setOnMyLocationClickListener(callback?: MapListenerCallback<MapClickCallbackData> | undefined) => Promise<void>

| Param | Type | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | callback | MapListenerCallback<MapClickCallbackData> |


Interfaces

CreateMapArgs

An interface containing the options used when creating a map.

| Prop | Type | Description | Default | | ----------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ------------------ | | id | string | A unique identifier for the map instance. | | | apiKey | string | The Google Maps SDK API Key. | | | config | GoogleMapConfig | The initial configuration settings for the map. | | | element | HTMLElement | The DOM element that the Google Map View will be mounted on which determines size and positioning. | | | forceCreate | boolean | Destroy and re-create the map instance if a map with the supplied id already exists | false |

GoogleMapConfig

For web, all the javascript Google Maps options are available as GoogleMapConfig extends google.maps.MapOptions. For iOS and Android only the config options declared on GoogleMapConfig are available.

| Prop | Type | Description | Default | Since | | ---------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ----- | | width | number | Override width for native map. | | | | height | number | Override height for native map. | | | | x | number | Override absolute x coordinate position for native map. | | | | y | number | Override absolute y coordinate position for native map. | | | | center | LatLng | Default location on the Earth towards which the camera points. | | | | zoom | number | Sets the zoom of the map. | | | | androidLiteMode | boolean | Enables image-based lite mode on Android. | false | | | devicePixelRatio | number | Override pixel ratio for native map. | | | | styles | MapTypeStyle[] | null | Styles to apply to each of the default map types. Note that for satellite, hybrid and terrain modes, these styles will only apply to labels and geometry. | | 4.3.0 |

LatLng

An interface representing a pair of latitude and longitude coordinates.

| Prop | Type | Description | | --------- | ------------------- | ------------------------------------------------------------------------- | | lat | number | Coordinate latitude, in degrees. This value is in the range [-90, 90]. | | lng | number | Coordinate longitude, in degrees. This value is in the range [-180, 180]. |

MapReadyCallbackData

| Prop | Type | | ----------- | ------------------- | | mapId | string |

Marker

A marker is an icon placed at a particular point on the map's surface.

| Prop | Type | Description | Default | Since | | ---------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ----- | | coordinate | LatLng | Marker position | | | | opacity | number | Sets the opacity of the marker, between 0 (completely transparent) and 1 inclusive. | 1 | | | title | string | Title, a short description of the overlay. | | | | snippet | string | Snippet text, shown beneath the title in the info window when selected. | | | | isFlat | boolean | Controls whether this marker should be flat against the Earth's surface or a billboard facing the camera. | false | | | iconUrl | string | Path to a marker icon to render. It can be relative to the web app public directory, or a https url of a remote marker icon. SVGs are not supported on native platforms. | | 4.2.0 | | iconSize | Size | Controls the scaled size of the marker image set in iconUrl. | | 4.2.0 | | iconOrigin | Point | The position of the image within a sprite, if any. By default, the origin is located at the top left corner of the image . | | 4.2.0 | | iconAnchor | Point | The position at which to anchor an image in correspondence to the location of the marker on the map. By default, the anchor is located along the center point of the bottom of the image. | | 4.2.0 | | tintColor | { r: number; g: number; b: number; a: number; } | Customizes the color of the default marker image. Each value must be between 0 and 255. Only for iOS and Android. | | 4.2.0 | | draggable | boolean | Controls whether this marker can be dragged interactively | false | |

Size

| Prop | Type | | ------------ | ------------------- | | width | number | | height | number |

Point

Point geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.2

| Prop | Type | Description | | ----------------- | --------------------------------------------- | ------------------------------------- | | type | 'Point' | Specifies the type of GeoJSON object. | | coordinates | Position | |

CameraConfig

Configuration properties for a Google Map Camera

| Prop | Type | Description | Default | | ----------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------ | | coordinate | LatLng | Location on the Earth towards which the camera points. | | | zoom | number | Sets the zoom of the map. | | | bearing | number | Bearing of the camera, in degrees clockwise from true north. | 0 | | angle | number | The angle, in degrees, of the camera from the nadir (directly facing the Earth). The only allowed values are 0 and 45. | 0 | | animate | boolean | Animate the transition to the new Camera properties. | false | | animationDuration | number | This configuration option is not being used. | |

MapPadding

Controls for setting padding on the 'visible' region of the view.

| Prop | Type | | ------------ | ------------------- | | top | number | | left | number | | right | number | | bottom | number |

CameraIdleCallbackData

| Prop | Type | | --------------- | ------------------------- | | mapId | string | | bounds | LatLngBounds | | bearing | number | | latitude | number | | longitude | number | | tilt | number | | zoom | number |

CameraMoveStartedCallbackData

| Prop | Type | | --------------- | -------------------- | | mapId | string | | isGesture | boolean |

ClusterClickCallbackData

| Prop | Type | | --------------- | --------------------------------- | | mapId | string | | latitude | number | | longitude | number | | size | number | | items | MarkerCallbackData[] |

MarkerCallbackData

| Prop | Type | | --------------- | ------------------- | | markerId | string | | latitude | number | | longitude | number | | title | string | | snippet | string |

MarkerClickCallbackData

| Prop | Type | | ----------- | ------------------- | | mapId | string |

MapClickCallbackData

| Prop | Type | | --------------- | ------------------- | | mapId | string | | latitude | number | | longitude | number |

MyLocationButtonClickCallbackData

| Prop | Type | | ----------- | ------------------- | | mapId | string |

Type Aliases

MapListenerCallback

The callback function to be called when map events are emitted.

(data: T): void

Position

A Position is an array of coordinates. https://tools.ietf.org/html/rfc7946#section-3.1.1 Array should contain between two and three elements. The previous GeoJSON specification allowed more elements (e.g., which could be used to represent M values), but the current specification only allows X, Y, and (optionally) Z to be defined.

number[]

Enums

MapType

| Members | Value | Description | | --------------- | ------------------------ | ---------------------------------------- | | Normal | 'Normal' | Basic map. | | Hybrid | 'Hybrid' | Satellite imagery with roads and labels. | | Satellite | 'Satellite' | Satellite imagery with no labels. | | Terrain | 'Terrain' | Topographic data. | | None | 'None' | No base map tiles. |