We're excited to announce Preview 2.0 is entering Public Beta!
Read the Announcement

@nativescript/google-maps

NativeScript binding for the Google Maps Android & iOS API.

Table of Contents

Prerequisites

To use the Google Maps API, you must register your app in the Google API Console and obtain an API key.

Installation

ns plugin add @nativescript/google-maps

Config

Android

Modify the AndroidManifest to include the new meta tag along with your API key, the manifest is located in App_Resources/Android/AndroidManifest.xml

<application
  android:name="com.tns.NativeScriptApplication"
  android:allowBackup="true"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name"
  android:theme="@style/AppTheme"
  android:hardwareAccelerated="true"
>
  <meta-data android:name="com.google.android.geo.API_KEY" android:value="yourKey" />
</application>

iOS

Modify the Info.plist to include the new meta tag along with your API key, the manifest is located in App_Resources/iOS/Info.plist

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>TNSGoogleMapsAPIKey</key>
    <string>yourKey</string>
  </dict>
</plist>

Usage

Core

Important

Ensure you've included xmlns:map="@nativescript/google-maps" on the Page element

<map:MapView
  lat="{{lat}}"
  lng="{{lng}}"
  zoom="{{zoom}}"
  bearing="{{bearing}}"
  tilt="{{tilt}}"
  ready="{{onReady}}"
  mapTap="{{onTap}}"
  mapLongPress="{{onLongPress}}"
  markerTap="{{onMarkerTap}}"
/>

Angular

import { GoogleMapsModule } from '@nativescript/google-maps/angular';

@NgModule({
    imports: [
      GoogleMapsModule
    ],
    declarations: [
      AppComponent
    ],
    bootstrap: [AppComponent]
})
<MapView
  (ready)="onReady($event)"
  (mapTap)="onTap($event)"
  (mapLongPress)="onLongPress($event)"
  (markerTap)="onMarkerTap($event)"
>
</MapView>

Vue

import Vue from 'nativescript-vue'
import GoogleMaps from '@nativescript/google-maps/vue'

Vue.use(GoogleMaps)
<MapView
  @ready="onReady"
  @mapTap="onTap"
  @mapLongPress="onLongPress"
  @markerTap="onMarkerTap"
/>

MapView API

Properties

The following properties are available for adjusting the camera view on initialization:

PropertytypeDescription and Data Type
latnumberLatitude, in degrees
lngnumberLongitude, in degrees
zoomnumberZoom level (described here)
bearingnumberBearing, in degrees
tiltnumberTilt, in degrees

Events

The following events are available:

| Event | Description | | :-------------------- | :---------------------------------------------------------------------- | ------- | -------- | | ready | Fires when the MapView is ready for use see GoogleMap | | mapTap | Fires when a coordinate is tapped on the map | | mapLongPress | Fires when a coordinate is long-pressed on the map | | markerTap | Fires when a marker is tapped | | myLocationTap | Fires when 'My Location' is tapped | | myLocationButtonTap | Fires when the 'My Location' button is tapped | | markerDragStart | Fires when a marker begins dragging | | markerDragging | Fires while a marker is being dragged | | markerDragEnd | Fires when a marker ends dragging | | tileRenderingStart | Fires when tile rendering begins | | tileRenderingEnd | Fires when tile rendering ends | | cameraPosition | Fires when the map viewport state changes, camera states include idle | start | moving | | circle | Fires when a circle is tapped | | polygon | Fires when a polygon is tapped | | polyline | Fires when a polyline is tapped | | poi | Fires when a POI is tapped | | groundOverlay | Fires when a ground overlay is tapped | | infoWindowTap | Fires when a marker's info window is tapped | | infoWindowLongPress | Fires when a marker's info window is long-pressed | | infoWindowClose | Fires when a marker's info window is closed | | markerInfoContents | | markerInfoWindow | | activeBuilding | Fires when a building is focused on | | activeLevel | Fires when the level of the focused building changes |

Google Map

Instance

A GoogleMap instance is required from the map view to access many of the mapping features. The GoogleMaps instance is available from the MapViews ready event:

function onReady(event: MapReadyEvent) {
  const map: GoogleMap = event.map
}

API

Properties

PropertyTypeDescription
mapStyleStyle[]See Map Styles
mapTypeMapTypeSee Map Type
buildingsEnabledbooleanEnables Buildings
maxZoomLevelnumberMaximum level of zoom
minZoomLevelnumberMinimum level of zoom
myLocationEnabledbooleanEnables "My Location"
trafficEnabledbooleanEnables traffic
uiSettingsIUISettingsSee UI Settings
cameraPositionCameraPositionSee Camera Position
projectionProjectionSee Projection
nativeanySee Native Map Object

Functions

FuncDescription
addMarker(marker: MarkerOptions): MarkerAdds a marker to the map
removeMarker(marker: Marker)Removes a marker from the map
addTileOverlay(options: TileOverlayOptions): TileOverlayAdds a tile overlay to the map
removeTileOverlay(overlay: TileOverlay)Removes a tile overlay from the map
addCircle(circle: CircleOptions): CircleAdds a circle to the map
removeCircle(circle: Circle)Removes a circle from the map
addGroundOverlay(options: GroundOverlayOptions): GroundOverlayAdds a ground overlay to the map
removeGroundOverlay(groundOverlay: GroundOverlay)Removes a ground overlay from the map
addPolygon(options: PolygonOptions): PolygonAdds a polygon to the map
removePolygon(polygon: Polygon)Removes a polygon from the map
addPolyline(options: PolylineOptions): PolylineAdds a polyline to the map
removePolyline(polyline: Polyline#polyline)Removes a polyline from the map
animateCamera(update: CameraUpdate)Animates camera to a new position
snapshot(): Promise<ImageSource>Returns a platform specific image of the maps current viewport
clear()Clears all objects added to the map

Native Map Object

GoogleMap gives you access to the platforms native map objects native | android | ios

consult the appropriate SDK reference on how to use it: iOS | Android

Camera Position

The maps current camera position can be read from the GoogleMaps object cameraPosition.

PropertyTypeDescription
targetCoordinateThe camera target is the location of the center of the map, specified as lat and lng.
bearingnumberThe direction in which the camera points measured in degrees clockwise from north.
tiltnumberThe viewing angle of the camera measured in degrees
zoomnumberThe scale of the map

Controlling the camera

To programatically update the camera position you can call animateCamera from the GoogleMap object, like so:

import { CameraPosition } from '@nativescript/google-maps'

googleMap.animateCamera(
  CameraPosition.fromCoordinates(
    {
      lat: -32.1234,
      lng: 125.1234
    },
    googleMap.cameraPosition.zoom
  )
)

CameraPosition provides multiple methods to create a target CameraUpdate position.

MethodDescription
fromCoordinate(coordinate: Coordinate, zoom: number)Returns a CameraUpdate from a single coordinate
fromCoordinates(coordinates: Coordinate[], padding: number)Returns a CameraUpdate from multiple coordinates
fromCoordinates(coordinates: Coordinate[], width: number, height: number, padding: number)Returns a CameraUpdate from multiple coordinates with specified height, width and padding
fromCameraPosition(position: CameraPosition)Returns a CameraUpdate from a CameraPosition
zoomIn()Returns a CameraUpdate that has zoomed in
zoomOut()Returns a CameraUpdate that has zoomed out
zoomTo(value: number)Returns a CameraUpdate that has zoomed to a value
zoomBy(amount: number, point?: { x: number; y: number })Returns a CameraUpdate that has zoomed and panned
scrollBy(x: number, y: number)Returns a panned CameraUpdate

UI Settings

You can adjust the maps UI settings from the GoogleMap object by configuring the following properties of uiSettings:

PropertyTypeDescription
compassEnabledbooleanWhether the compass is enabled or not
indoorLevelPickerEnabledbooleanWhether the indoor level picker is enabled or not
mapToolbarEnabledbooleanWhether the map toolbar is enabled or not
myLocationButtonEnabledbooleanWhether the 'My Location' button is enabled or not
rotateGesturesEnabledbooleanWhether the compass is enabled or not
scrollGesturesEnabledbooleanWhether map scroll gestures are enabled or not
tiltGesturesEnabledbooleanWhether map tilt gestures are enabled or not
zoomGesturesEnabledbooleanWhether map zoom gestures are enabled or not
zoomControlsEnabledbooleanWhether map zoom controls are enabled or not
scrollGesturesEnabledDuringRotateOrZoombooleanWhether scroll gestures are enabled while rotating or zooming

Map Type

The Google Maps API offers five types of maps:

TypeDescription
NoneNo tiles. The map is rendered as an empty grid with no tiles loaded.
NormalTypical road map. Shows roads, some features built by humans, and important natural features such as rivers. Road and feature labels are also visible.
SatelliteSatellite photograph data. Road and feature labels are not visible.
TerrainTopographic data. The map includes colors, contour lines and labels, and perspective shading. Some roads and labels are also visible.
HybridSatellite photograph data with road maps added. Road and feature labels are also visible.

To set the type of a map, adjust the GoogleMap objects mapType. You can pass in one map type from the MapType Enum. For example:

import { GoogleMap, MapType } from '@nativescript/google-map';

...
map: GoogleMap;
map.mapType = MapType.Hybrid;

Map Styles

You can customize the presentation of the standard Google Map styles, changing the visual display of features like roads, parks, businesses, and other points of interest. This means that you can emphasize particular components of the map or make the map look good with your app.

Styling works only on the normal map type. Styling does not affect indoor maps.

To style your map, use a JSON file generated by the Google Maps APIs Styling Wizard. In addition to changing the appearance of features, you can also hide features completely.

[
  {
    "featureType": "all",
    "stylers": [{ "color": "#C0C0C0" }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "geometry",
    "stylers": [{ "color": "#CCFFFF" }]
  },
  {
    "featureType": "landscape",
    "elementType": "labels",
    "stylers": [{ "visibility": "off" }]
  }
]

To apply a custom style to your map you can set the mapStyle property on your GoogleMap object, like so:

import { GoogleMap } from '@nativescript/google-map';

...
map: GoogleMap;
map.mapStyle = [{
	"featureType": "landscape",
	"elementType": "labels",
	"stylers": [
		{ "visibility": "off" }
	]
}];

Markers

Adding Markers

You can create markers using the GoogleMaps object addMarker function by passing in the specified Marker Options.

function addMarker(map: GoogleMap, marker: MarkerOptions): Marker {
  return map.addMarker(marker)
}

Marker Options

PropertyTypeDescription
positionCoordinateThe position of the marker, specified as lat and lng
colorstring | ColorColor of the marker, shades are unavailable.
titlestringA string that's displayed in the info window when the user taps the marker
snippetstringAdditional text that's displayed below the title
iconImageA image that's displayed in place of the default marker image
draggablebooleanSet to true if you want to allow the user to move the marker. Defaults to false
flatbooleanBy default, markers are oriented against the screen, and will not rotate or tilt with the camera. Flat markers are oriented against the surface of the earth, and will rotate and tilt with the camera
rotationbooleanThe orientation of the marker, specified in degrees clockwise
anchorUnumberHorizontal icon offset from the marker position
anchorVnumberVertical icon offset from the marker position
userDataanyAdditional information assigned to the marker
zIndexnumberZ-index of the marker

Removing Markers

You can remove a marker using the GoogleMaps removeMarker function, like so:

function removeMarker(map: GoogleMap, marker: Marker) {
  map.removeMarker(marker)
}

Circle

Adding Circles

You can create Circles using the GoogleMaps object addCircle function by passing in the specified Circle Options.

function addCircle(map: GoogleMap, Circle: CircleOptions): Circle {
  return map.addCircle(Circle)
}

Circle Options

PropertyType
centerCoordinate
fillColorColor | string
radiusnumber
strokeColorColor | string
strokePatternPatternItem & Partial<NativeObject>[]
strokeWidthnumber
tappableboolean
visibleboolean
zIndexnumber
userData{ [key: string]: any }

Removing Circles

You can remove a Circle using the GoogleMaps removeCircle function, like so:

function removeCircle(map: GoogleMap, Circle: CircleOptions) {
  map.removeCircle(Circle)
}

Polygons

Adding Polygons

You can create polygons using the GoogleMaps object addPolygon function by passing in the specified Polygon Options.

function addPolygon(map: GoogleMap, Polygon: PolygonOptions): Polygon {
  return map.addPolygon(Polygon)
}

Polygon Options

PropertyType
pointsCoordinate[]
holesCoordinate[]
tappableboolean
strokeWidthnumber
strokeColorColor | string
fillColorColor | string
strokePatternPatternItem & Partial<NativeObject>[]
zIndexnumber
geodesicboolean
strokeJointTypeJointType
visibleboolean
userData{ [key: string]: any }

Removing Polygons

You can remove a Polygon using the GoogleMaps removePolygon function, like so:

function removePolygon(map: GoogleMap, Polygon: PolygonOptions) {
  map.removePolygon(Polygon)
}

Polyline

Adding Polylines

You can create Polylines using the GoogleMaps object addPolyline function by passing in the specified Polyline Options.

function addPolyline(map: GoogleMap, Polyline: PolylineOptions): Polyline {
  return map.addPolyline(Polyline)
}

Polyline Options

PropertyType
widthnumber
pointsCoordinate[]
tappableboolean
geodesicboolean
visibleboolean
zIndexnumber
jointTypeJointType
patternPatternItem & Partial<NativeObject>[]
colorColor | string
startCapCap & Partial<NativeObject>
endCapCap & Partial<NativeObject>
userData{ [key: string]: any }

Removing Polylines

You can remove a Polyline using the GoogleMaps removePolyline function, like so:

function removePolyline(map: GoogleMap, Polyline: PolylineOptions) {
  map.removePolyline(Polyline)
}

Ground Overlays

Adding Ground Overlays

You can create Ground Overlays using the GoogleMaps object addGroundOverlay function by passing in the specified GroundOverlay Options.

function addGroundOverlay(
  map: GoogleMap,
  GroundOverlay: GroundOverlayOptions
): GroundOverlay {
  return map.addGroundOverlay(GroundOverlay)
}

GroundOverlay Options

PropertyType
zIndexnumber
visibleboolean
transparencynumber
positionCoordinate
boundsCoordinateBounds
tappableboolean
bearingnumber
imageImageSource
userDataany
widthnumber
heightnumber
anchorUnumber
anchorVnumber

Removing Ground Overlays

You can remove a GroundOverlay using the GoogleMaps removeGroundOverlay function, like so:

function removeGroundOverlay(map: GoogleMap, GroundOverlay: GroundOverlayOptions) {
  map.removeGroundOverlay(GroundOverlay)
}

Tile Overlays

Adding Tile Overlays

You can create Tile Overlays using the GoogleMaps object addTileOverlay function by passing in the specified TileOverlay Options.

function addTileOverlay(map: GoogleMap, TileOverlay: TileOverlayOptions): TileOverlay {
  return map.addTileOverlay(TileOverlay)
}

TileOverlay Options

PropertyType
fadeInboolean
transparencynumber
visibleboolean
tileProviderTileProvider & Partial<NativeObject>
zIndexnumber

Removing Tile Overlays

You can remove a TileOverlay using the GoogleMaps removeTileOverlay function, like so:

function removeTileOverlay(map: GoogleMap, TileOverlay: TileOverlayOptions) {
  map.removeTileOverlay(TileOverlay)
}

License

Apache License Version 2.0