I use Ionic 3 version and I try to add a page into my app, to display a map with markers.
I already use for my app a Google Map Id for Autocomplete (Google places...).
I went to Google APIs and I added Map Embed, Javascript etc... to my API Key.
But The page appears with "Google" in the bottom and the display button", but the map is empty.
See attached file...
Install the Cordova and Ionic Native plugins:
$ ionic cordova plugin add https://github.com/mapsplugin/cordova-plugin-googlemaps#multiple_maps --variable API_KEY_FOR_ANDROID="AIzaSyB6mEnxH4vC+++++++++9wnXXNNmK2co" --variable API_KEY_FOR_IOS="AIzaSyB6mEnxH4v++++++++++++++wnXXNNmK2co"
$ npm install --save #ionic-native/google-maps
Home.ts:
import { NavController } from 'ionic-angular';
import { Component, ViewChild, ElementRef } from '#angular/core';
import { GoogleMaps, CameraPosition, GoogleMapsEvent, GoogleMap, MarkerOptions, Marker } from "#ionic-native/google-maps";
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
#ViewChild('map') mapElement: ElementRef;
map: any;
constructor(public navCtrl: NavController, private googleMaps: GoogleMaps) {
}
ngAfterViewInit() {
this.loadMap();
}
loadMap() {
// make sure to create following structure in your view.html file
// and add a height (for example 100%) to it, else the map won't be visible
// <ion-content>
// <div #map id="map" style="height:100%;"></div>
// </ion-content>
// create a new map by passing HTMLElement
let element: HTMLElement = document.getElementById('map');
let map: GoogleMap = this.googleMaps.create(element);
// listen to MAP_READY event
// You must wait for this event to fire before adding something to the map or modifying it in anyway
map.one(GoogleMapsEvent.MAP_READY).then(
() => {
console.log('Map is ready!');
// Now you can add elements to the map like the marker
}
);
// create CameraPosition
let position: CameraPosition = {
target: {
lat: 43.0741904,
lng: -89.3809802
},
zoom: 18,
tilt: 30
};
// move the map's camera to position
}
}
Home.HTML
Home.html :
<ion-header>
<ion-navbar>
<ion-title>
Map
</ion-title>
<ion-buttons end>
<button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>Add Marker</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<div #map id="map" style="height:100%;"></div>
</ion-content>
Home.scss
page-home {
}
Do not use the ngAfterViewInit.
You must wait platform.ready()
// Wait the native plugin is ready.
platform.ready().then(() => {
this.loadMap();
});
Full code is https://github.com/mapsplugin/cordova-plugin-googlemaps-doc/blob/master/v2.0.0/ionic-native/README.md
Repo: https://github.com/mapsplugin/ionic-google-maps
The current official document page is wrong. I sent a pull request, but it's waiting now.
https://github.com/ionic-team/ionic-native/pull/1834
Please try below code and make sure you are using correct API key, write following code in your .ts file:
ionViewDidLoad() {
this.loadMap();
}
loadMap() {
let mapOptions: GoogleMapOptions = {
camera: {
target: {
lat: 43.0741904,
lng: -89.3809802
},
zoom: 18,
tilt: 30
}
};
this.map = this.googleMaps.create('map_canvas', mapOptions);
// Wait the MAP_READY before using any methods.
this.map.one(GoogleMapsEvent.MAP_READY)
.then(() => {
console.log('Map is ready!');
this.map.addMarker({
title: 'Ionic',
icon: 'blue',
animation: 'DROP',
position: {
lat: 43.0741904,
lng: -89.3809802
}
})
.then(marker => {
marker.on(GoogleMapsEvent.MARKER_CLICK)
.subscribe(() => {
alert('clicked');
});
});
});
}
In your .html file define map like below
<ion-content>
<div id="map_canvas" style="height: 100%;"></div>
</ion-content>
Related
Using IONIC 4 ion-slides, I am trying to get currently clicked silde index using getActiveIndex() as below which it is not working.
<ion-slides #testSlider (ionSlideTap)="getIndex()">
<ion-slide>....</ion-slide>
</ion-slides>
#ViewChild('testSlider') slider: ElementRef; // first way
getIndex() {
this.slider.nativeElement.getActiveIndex();
}
#ViewChild('testSlider') slider: Slider; //second way
getIndex() {
this.slider.getActiveIndex();
}
And the another way as below which is also not working:
<ion-slides #testSlider (ionSlideTap)="getIndex(testSlider)">
<ion-slide>....</ion-slide>
</ion-slides>
getIndex(testSlider) {
testSlider.getActiveIndex();
}
Can anyone please suggest me how can I get active index or currently clicked slide index in IONIC 4 ?
I had the same problem, but managed to solve it as follows:
export class SomePage implements OnInit {
...
currentIndex:Number = 0;
...
getSlideIndex(){
this.slides.getActiveIndex().then(
(index)=>{
this.currentIndex = index;
});
}
...
this.getSlideIndex();
console.log(this.currentIndex);
Note that although it seems to work, I suspect that because the value is changes inside promise, it will only return the correct value if it has not recently changed. I thus intend to update this with a wait implemented to counter this.
in template
<ion-slides pager="true" (ionSlideDidChange)="slideChanged($event)" #slides>
</ion-slides>
in component
import { IonSlides } from '#ionic/angular';
#ViewChild('slides', {static: true}) slides: IonSlides;
slideChanged(e: any) {
this.slides.getActiveIndex().then((index: number) => {
console.log(index);
});
}
According to the documentation, getActiveIndex() returns a Promise<number>.
So by using ionSlideTap:
<ion-slides (ionSlideTap)="onSlideTapped($event)">
...
</ion-slides>
I found two ways to do it:
As phunder suggests, you can use then() to retrieve its value. I also did it with async/await:
async onSlideTapped(event: any) {
const index: number = await event.target.getActiveIndex();
console.log(index);
}
Or you can use the swiper object:
onSlideTapped(event: any) {
console.log(event.target.swiper.clickedIndex);
}
Therefore, you don't have to listen for every changes or to import the IonSlides in your component.
UPDATED:
I think I made a few mistakes, here is working example (Ionic 3). Please make sure you are using $event.
Template file:
<ion-slides (ionSlideTap)="getIndex($event)">
<ion-slide>1</ion-slide>
</ion-slides>
Now in TS file:
getIndex(event) {
console.log(event.clickedIndex);
}
Try the above approach?
Here is working stackblitz: https://stackblitz.com/edit/ionic-ssvout
1)Assign id to the respective like #slides
<div>
<ion-slides #slide (ionSlideDidChange)="SlideChanges(slide)">
</ion-slides>
</div>
2) import IonSlides in your.ts page/component
import { IonSlides } from '#ionic/angular';
3). Use method
SlideChanges(slide: IonSlides) {
slide.getActiveIndex().then((index: number) => {
this.yourSlideIndex= index;
alert(this.yourSlideIndex)
});
}
for ionic 4
*.html
<ion-slides #slides (ionSlideDidChange)="slideChanged(slides)">
...
</ion-slides>
*. ts
...
#ViewChild('slides', { static: false }) slides: IonSlides;
...
slideChanged(slides: IonSlides) {
slides.getActiveIndex().then((index: number) => {
console.log(index);
this.currentIndex = index;
});
}
Yes, It's working...!
// Typescript
import { IonSlides } from '#ionic/angular';
// in Component Class
export class AppComponent implements OnInit {
#ViewChild('contentSlider') contentSlider: IonSlides;
constructor(){}
ngOnInit() {}
do_getActiveSlide(e: any) {
this.contentSlider.getActiveIndex().then((index: number) => {
console.log("Current active slide index", index);
});
}
}
div {
width: 100%;
height: 5em;
color: gold;
background-color: #333;
margin: 1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/#ionic/core/dist/ionic/ionic.esm.js"></script>
<script nomodule src="https://cdn.jsdelivr.net/npm/#ionic/core/dist/ionic/ionic.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#ionic/core/css/ionic.bundle.css"/>
<ion-slides pager="true" (ionSlideDidChange)="do_getActiveSlide($event)" #contentSlider>
<ion-slide>
<div>1</div>
</ion-slide>
<ion-slide>
<div>2</div>
</ion-slide>
<ion-slide>
<div>3</div>
</ion-slide>
</ion-slides>
I created a sidemenu app in Ionic 2 which contains a Main Tab and 3 sub tab pages.
It looks like this:
This is the code for Main tabs page:
<ion-header>
<ion-navbar #content color="black">
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title >Main Tab</ion-title>
</ion-navbar>
</ion-header>
<ion-tabs [selectedIndex]="mySelectedIndex" #myTabs>
<ion-tab [root]="tabARoot" tabTitle="Tab A" tabIcon="information-circle"></ion-tab>
<ion-tab [root]="tabBRoot" tabTitle="Tab B" tabIcon="information-circle"></ion-tab>
<ion-tab [root]="tabCRoot" tabTitle="Tab C" tabIcon="information-circle"></ion-tab>
</ion-tabs>
It contains 3 sub tab pages with some gibberish on it.
This is how my side menu looks like.
So when a user clicks on Tab B link from side menu, he should navigate to main tabs page with Tab B as selected. But now when I click, Tab A is selected by default.
Is it possible to change this behavior?
My app.component.ts file looks like this
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform, App, Tabs } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { MainPage } from '../pages/main/main';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = MainPage;
pages: Array<{title: string, component: any}>;
constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private app: App) {
this.initializeApp();
// used for an example of ngFor and navigation
this.pages = [
{ title: 'Tab A', component: MainPage },
{ title: 'Tab B', component: MainPage },
{ title: 'Tab C', component: MainPage },
];
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.nav.setRoot(page.component);
}
}
From somewhere I got a solution which didn't work, obviously.
in that solution, it was mentioned to do it like given below but it didn't work'
this.nav.setRoot(page.component, {tabIndex: 2});
There is a property called selectedIndex in ion-tabs component to set the default tab. Since you are passing tabIndex while clicking the main tab you can do something like this
In the controller
selectedTabIndex = navParams.get('tabIndex');
In the view
<ion-tabs [selectedIndex]="selectedTabIndex">
<ion-tab [root]="tabA"></ion-tab>
<ion-tab [root]="tabB"></ion-tab>
<ion-tab [root]="tabC"></ion-tab>
</ion-tabs>
Else if you want to select any tabs programatically from controller you can do this, first get the reference of your tabs and then you can use the select() function to set the selected tab you want by passing the index
#ViewChild('myTabs') tabRef: Tabs;
ionViewDidLoad() {
this.tabRef.select(1, { animate: false });
}
#john Doe
set root page = 'MenuPage' page
rootPage = 'MenuPage'
try below code:
`
src/pages/menu/menu.html :
<ion-menu [content]="content">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<button ion-item menuClose *ngFor="let p of pages" (click)="openPage(p)">
<ion-icon item-start [name]="p.icon" [color]="isActive(p)"></ion-icon>
{{ p.title }}
</button>
</ion-list>
</ion-content>
</ion-menu>
<!-- main navigation -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
src/pages/menu/menu.ts:
import { Tab2Page } from './../tab2/tab2';
import { Tab1Page } from './../tab1/tab1';
import { TabsPage } from './../tabs/tabs';
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, Nav } from 'ionic-angular';
export interface PageInterface {
title: string;
pageName: string;
tabComponent?: any;
index?: number;
icon: string;
}
#IonicPage()
#Component({
selector: 'page-menu',
templateUrl: 'menu.html',
})
export class MenuPage {
// Basic root for our content view
rootPage = 'TabsPage';
// Reference to the app's root nav
#ViewChild(Nav) nav: Nav;
pages: PageInterface[] = [
{ title: 'Tab 1', pageName: 'TabsPage', tabComponent: 'Tab1Page', index: 0, icon: 'home' },
{ title: 'Tab 2', pageName: 'TabsPage', tabComponent: 'Tab2Page', index: 1, icon: 'contacts' },
{ title: 'Special', pageName: 'SpecialPage', icon: 'shuffle' },
];
constructor(public navCtrl: NavController) { }
openPage(page: PageInterface) {
let params = {};
// The index is equal to the order of our tabs inside tabs.ts
if (page.index) {
params = { tabIndex: page.index };
}
// The active child nav is our Tabs Navigation
if (this.nav.getActiveChildNav() && page.index != undefined) {
this.nav.getActiveChildNav().select(page.index);
} else {
// Tabs are not active, so reset the root page
// In this case: moving to or from SpecialPage
this.nav.setRoot(page.pageName, params);
}
}
isActive(page: PageInterface) {
// Again the Tabs Navigation
let childNav = this.nav.getActiveChildNav();
if (childNav) {
if (childNav.getSelected() && childNav.getSelected().root === page.tabComponent) {
return 'primary';
}
return;
}
// Fallback needed when there is no active childnav (tabs not active)
if (this.nav.getActive() && this.nav.getActive().name === page.pageName) {
return 'primary';
}
return;
}
}
src/pages/tabs/tabs.html
<ion-tabs [selectedIndex]="myIndex">
<ion-tab [root]="tab1Root" tabTitle="Tab 1" tabIcon="home"></ion-tab>
<ion-tab [root]="tab2Root" tabTitle="Tab 2" tabIcon="contacts"></ion-tab>
</ion-tabs>
src/pages/tabs/tabs.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
#IonicPage()
#Component({
selector: 'page-tabs',
templateUrl: 'tabs.html',
})
export class TabsPage {
tab1Root: any = 'Tab1Page';
tab2Root: any = 'Tab2Page';
myIndex: number;
constructor(navParams: NavParams) {
// Set the active tab based on the passed index from menu.ts
this.myIndex = navParams.data.tabIndex || 0;
}
}
thanks
i am trying to open the photolibrary of android to select images using ionic 2.
here is the code of the home.ts in witch the camera plugin is used.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Camera} from '#ionic-native/camera';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
image640:any;
constructor(public navCtrl: NavController,public camera : Camera)
{
}
openGallery()
{
var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
this.camera.getPicture(
options
).then(
(imageData)=>
{
this.image640 = 'data:image/jpeg;base64,'+imageData;
},
(err) =>
{
console.log(err);
}
);
}
}
And the code of the home.html is below :
<ion-header>
<ion-navbar>
<ion-title align="center">
Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<img src="image640" *ngIf="image640"/>
<Button align="center" ion-button (click)="openGallery()">Open
Gallery</Button>
</ion-content>
but when i click on the opengallery button, the android library is opened but when i select an image, a blank screen appear during about 8 seconds, and after that, the it is the rootpage that is displayed. Then i cannot see the selected image in my page.
can somebody help ?
Set options
var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
Then select photos like this
this.camera.getPicture(options).then((imagePath) => {
// Special handling for Android library
if (this.platform.is('android') && sourceType ===
this.camera.PictureSourceType.PHOTOLIBRARY) { //when selecting from library
//your code goes here
} else { //when capturing by camera
//your code goes here
}
now i trying array data modeling using ionic2.
i created 'model.ts' in 'src/app/models' and declared in 'setting.ts' with array data.
next, i called it to 'setting.html'.
By the way...There is a some problem.
build and run were success. but any datas didn't show in screen..
not Error, i dont know where is wrong..
please find wrong point and fix that.
there is my code..
workoutlist-model.ts
export class WorkoutlistModel {
constructor(public Workoutlist: any[]) {
this.Workoutlist = [];
}
addItem(nm, gl) {
this.Workoutlist.push({
name: nm,
goal: gl
});
}
removeItem(nm, gl) {
for (var i = 0; i < this.Workoutlist.length; i++) {
if (this.Workoutlist[i].name == nm) {
if (this.Workoutlist[i].goal == gl) {
this.Workoutlist.splice(i);
}
}
}
}
}
setting.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { WorkoutlistModel } from '../../app/models/workoutlist-model';
#Component({
selector: 'page-setting',
templateUrl: 'setting.html'
})
export class Setting {
constructor(public navCtrl: NavController) {
new WorkoutlistModel([{ name: 'Push-Up', goal: 100 },
{ name: 'Squat', goal: 150 },
{ name: 'Sit-Up', goal: 45 }]);
}
}
setting.html - the part using this.
<ion-content style="height: 200px; outline: green">
<ion-card *ngFor="let WO of WorkoutlistModel;">
<button ion-item>
<div style="float: left;padding: 0px;">name : {{WO.name}}</div>
<div style="float: right;padding: 0px;">goal : {{WO.goal}}</div>
</button>
</ion-card>
</ion-content>
You havent declared or assigned WorkoutlistModel
Also WorklistModel is class and not an array to traverse with *ngFor
export class Setting {
workListModel:any;//declare
constructor(public navCtrl: NavController) {
this.workListModel = new WorkoutlistModel([{ name: 'Push-Up', goal: 100 },
{ name: 'Squat', goal: 150 },
{ name: 'Sit-Up', goal: 45 }]);//assign
}
}
In Html
<ion-card *ngFor="let WO of workListModel.getList();"><!-- get the list of items from class to traverse. may have to create this function -->
<button ion-item>
<div style="float: left;padding: 0px;">name : {{WO.name}}</div>
<div style="float: right;padding: 0px;">goal : {{WO.goal}}</div>
</button>
</ion-card>
You are not injecting the model. So change it to this.
constructor( Workoutlist: any[]) {
this.Workoutlist = Workoutlist;
}
I would like to raise an alert on Ionic2 when the device does not have a Camera.
When i launch : ionic serve
then i try to display the message as follow :
let alert = Alert.create({
title: 'Camera not found',
subTitle: 'It seems your camera is not working on your device',
buttons: ['Ok']
});
this.nav.present(alert);
i have a javascript error
Uncaught EXCEPTION: Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: rootNav.getActive is not a function
ORIGINAL STACKTRACE:
TypeError: rootNav.getActive is not a function
at Tab.NavController.present (http://localhost:8100/build/js/app.bundle.js:46996:36)
at SmartScan.takePicture (http://localhost:8100/build/js/app.bundle.js:60864:23)
at AbstractChangeDetector.ChangeDetector_SmartScan_0.handleEventInternal (eval at <anonymous> (http://localhost:8100/build/js/app.bundle.js:14578:17), <anonymous>:185:36)
at AbstractChangeDetector.handleEvent (http://localhost:8100/build/js/app.bundle.js:13892:25)
at AppView.dispatchEvent (http://localhost:8100/build/js/app.bundle.js:18772:46)
at AppView.dispatchRenderEvent (http://localhost:8100/build/js/app.bundle.js:18766:22)
at DefaultRenderView.dispatchRenderEvent (http://localhost:8100/build/js/app.bundle.js:33592:39)
at eventDispatcher (http://localhost:8100/build/js/app.bundle.js:33258:22)
at http://localhost:8100/build/js/app.bundle.js:33329:40
In alert.js:
import {Page, Alert, NavController} from 'ionic-angular';
#Page({
templateUrl: 'build/pages/alert/alert.html'
})
export class AlertPage {
static get parameters() {
return [[NavController]];
}
constructor(nav) {
this.nav = nav;
}
showAlert() {
let alert = Alert.create({
title: 'New Friend!',
subTitle: 'Your friend, Obi wan Kenobi, just accepted your friend request!',
buttons: ['Ok']
});
this.nav.present(alert);
}
}
In alert.html:
<button block dark (click)="showAlert()">test</button>
Try this:
with this structure of folder and files
In:
home.html
<ion-header>
<ion-navbar>
<ion-title>Ionic 2 Notifications</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button block dark (click)="showAlert()">Alert</button>
</ion-content>
In:
home.ts
import {Component} from "#angular/core";
import {NavController, AlertController} from 'ionic-angular';
#Component({
templateUrl: 'home.html'
})
export class HomePage {
constructor(public alertCtrl: AlertController) {
}
showAlert() {
let alert = this.alertCtrl.create({
title: 'New Friend!',
subTitle: 'Your friend, Obi wan Kenobi, just accepted your friend request!',
buttons: ['OK']
});
alert.present();
}
}
I got this information from the documentation site:
https://ionicframework.com/docs/v2/components/#action-sheets
I am also working on ionic2 and was in the need to implement "PopUp" window in my existing application.
I try many for that by does not get my task accomplished, finally i did something like this-
pop-up.html
<button block dark (click)="showAlert()">Help Window</button>
pop-up.ts
import { Component } from '#angular/core';
import { Alert, NavController, NavParams} from 'ionic-angular';
#Component({
templateUrl: 'build/pages/pop-up/pop-up.html',
})
export class PopUpPage {
static get parameters() {
return [[NavController]];
}
constructor(private nav: NavController) {
this.nav = nav;
}
showAlert() {
let alert = Alert.create({
title: 'Help Window!',
subTitle: 'Mindfulness is here for you and your soul. We are intended to stablish your connection to All Mighty.',
buttons: ['Cancle']
});
this.nav.present(alert);
}
}
And that work fine for me.
Hope it will work for you too.
It seems that is not yet ready ...
investigating the code
this.nav.present(alert);
it is passing here and returns :
if (rootNav['_tabs']) {
// TODO: must have until this goes in
// https://github.com/angular/angular/issues/5481
void 0;
return;
}