Introduction
Styling your native google map can be useful, if you have a brand and you want your map to match the brand. It can also provide better ux depending on the use case of the app, also useful for theming your app. In this tutorial we will be building a map that changes style depending on the time of the day. It will have a normal map style during the day and a dark style during the night.
Setting up project
To generate a new ionic project, run the following command in the ionic cli:
ionic start googleStyleMap blank
navigate into the project:
cd googleStyleMap
If you check the folder you should see a src folder. Navigate into it, you should see pages, we will be using the home page inside the pages folder to display our map. Now let’s install the plugin Get the api key and add it to the following code
ionic cordova plugin add https://github.com/mapsplugin/cordova-plugin-googlemaps#multiple_maps --variable API_KEY_FOR_ANDROID="YOUR_ANDROID_API_KEY_IS_HERE" --variable API_KEY_FOR_IOS="YOUR_IOS_API_KEY_IS_HERE"
npm install --save @ionic-native/google-maps
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { GoogleMaps } from '@ionic-native/google-maps' @NgModule({ declarations: [ MyApp, HomePage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, GoogleMaps, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {}
Google Map Style
import { Component, ElementRef, ViewChild } from '@angular/core'; import { NavController } from 'ionic-angular'; import { GoogleMaps, GoogleMap, CameraPosition, LatLng, GoogleMapsEvent } from '@ionic-native/google-maps'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { @ViewChild('map') mapElement: ElementRef; map: GoogleMap; constructor(public navCtrl: NavController,private _googleMaps: GoogleMaps) { } ngAfterViewInit(){ this.initMap(); } initMap(){ let element = this.mapElement.nativeElement; let loc: LatLng = new LatLng(40.7128, -74.0059); this.map = this._googleMaps.create(element,{ styles: []}); this.map.one(GoogleMapsEvent.MAP_READY).then(() => { this.moveCamera(loc); }); } moveCamera(loc: LatLng){ let options: CameraPosition = { target: loc, zoom: 15, tilt: 10 } this.map.moveCamera(options); } }