I am able to click photos in my phone but image not displaying on my page.
I have installed the plugins from official ionic framework doc:
$ ionic cordova plugin add cordova-plugin-camera
$ npm install --save #ionic-native/camera
This is my code:
getPic()
{
const options: CameraOptions = {
quality: 70,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
this.myPhoto = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
});
}
I have declared myPhoto:any; inside my class.
This is where I am showing my Image:
<ion-content no-bounce padding>
<button ion-button (click)="getPic()">Take A Picture</button>
<p align="center"><img src="{{ myPhoto }}"></p>
</ion-content>
I don't know where I am doing the mistake. Please Help me. Thanks!
private OpenCamera(): void{
const options: CameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
correctOrientation: true,
sourceType: this.camera.PictureSourceType.CAMERA,
saveToPhotoAlbum: true
}
this.camera.getPicture(options).then((imageData) => {
this.AddIssueObj.file.push(s);
this.uploadcount=this.AddIssueObj.file.length;
}, (err) => {
// Handle error
});
}
for HTML:
<ion-scroll scrollX="true" class="m-slider__scroll" scroll-avatar>
<span *ngFor="let v of photoList">
<img src="{{v}}" alt="slider image1" class="m-slider__img" />
</span>
</ion-scroll>
Related
I'm developing an ionic 3 application in which I need to show the camera interface inside the app screen and camera-preview seems to be the right and only solution to go with at this moment. However, when I trigger the startCamera function, I always get the error ' Object(...) is not a function at CameraPreview.startCamera'. Any help would be much appreciated.
Here are the steps I used for the installation:
From CLI:
ionic cordova plugin add https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git
npm install #ionic-native/camera-preview
2.Add to the provider list in module.ts file
import { CameraPreview } from '#ionic-native/camera-preview/ngx';
.....
providers: [
CameraPreview, ...
]
Below is the page where I would use the plugin:
import { Component, NgZone } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { CameraPreview, CameraPreviewPictureOptions, CameraPreviewOptions, CameraPreviewDimensions } from '#ionic-native/camera-preview/ngx';
#Component({
selector: 'page-submitdata2',
templateUrl: 'submitdata2.html',
})
export class Submitdata2Page {
public getWidth: number;
public getHeight: number;
public calcWidth: number;
cameraPreviewOpts: CameraPreviewOptions =
{
x: 40,
y: 100,
width: 220,
height: 220,
toBack: false,
previewDrag: true,
tapPhoto: true,
camera: this.cameraPreview.CAMERA_DIRECTION.BACK
}
constructor(
public cameraPreview: CameraPreview, private zone: NgZone,
public navCtrl: NavController, public navParams: NavParams) {
this.zone.run(() => {
this.getWidth = window.innerWidth;
this.getHeight = window.innerHeight;
});
console.log('width', this.getWidth);
this.calcWidth = this.getWidth - 80;
console.log('calc width', this.calcWidth);
}
ionViewDidLoad() {
console.log('ionViewDidLoad Submitdata2Page');
}
startCamera() {
debugger
this.cameraPreview.startCamera(this.cameraPreviewOpts).then(
(res) => {
console.log(res)
},
(err) => {
console.log(err)
});
}
stopCamera() {
this.cameraPreview.stopCamera();
}
takePicture() {
this.cameraPreview.takePicture()
.then((imgData) => {
(<HTMLInputElement>document.getElementById('previewPicture')).src = 'data:image/jpeg;base64,' + imgData;
});
}
SwitchCamera() {
this.cameraPreview.switchCamera();
}
showCamera() {
this.cameraPreview.show();
}
hideCamera() {
this.cameraPreview.hide();
}
}
The HTML:
<ion-header>
<ion-navbar>
<ion-title>Preview Page</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h5>This is camera Preview Application..</h5>
<div class="displaybottom">
<button ion-button (click)="startCamera()"> Start Camera</button>
<button ion-button (click)="stopCamera()"> Stop Camera</button>
<button ion-button (click)="takePicture()"> Take Picture Camera</button>
<button ion-button (click)="SwitchCamera()"> Switch Camera</button>
<button ion-button (click)="showCamera()"> Show Camera</button>
<button ion-button (click)="hideCamera()"> Hide Camera</button>
</div>
<div class="pictures">
<p><img id="previewPicture" width="200" /></p>
<!--<p><img id="originalPicture" width="200"/></p>-->
</div>
</ion-content>
My Development Enviroment:
I am developing a simple mobile maid android based app using Ionic framework and I am using laravel for my backend. I am getting ‘Response with status: 0 for URL: null’ this error when I run it in web or android simulator.
I could not be able to register a new user, when I used POSTMAN to check my restful API it works and I could be a able to register a new user. But when I run this app in simulator it keep on showing this ‘Response with status: 0 for URL: null’ error.
**auth-service.ts file**
import { Injectable } from '#angular/core';
import {Http, Headers} from '#angular/http'
import 'rxjs/add/operator/map';
let apiUrl = 'http://fypBackend.test/api/';
#Injectable({
providedIn: 'root'
})
export class AuthServiceService {
constructor(public http: Http) { }
register(data){
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(apiUrl+'users', JSON.stringify(data), {headers: headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
console.log('Not Working')
reject(err);
});
});
}
}
**register.ts file**
import { Component} from '#angular/core';
import { NavController,LoadingController, ToastController } from '#ionic/angular';
import {AuthServiceService} from '../auth-service.service';
#Component({
selector: 'page-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss'],
})
export class RegisterPage{
loading: any;
regData = {name: '', icNumber: '', email: '',
password: '', phone: '', address: '',
cityState: '', houseType: '', category:''};
constructor(public navCtrl: NavController, public authService: AuthServiceService, public loadingCtr: LoadingController, private toastCtrl: ToastController) { }
doSignup(){
this.authService.register(this.regData).then((result)=>{
this.loading.dismiss();
this.navCtrl.pop();
}, (err) => {
this.presentToast(err);
});
}
async presentToast(msg){
const toast = await this.toastCtrl.create({
message: msg,
duration: 3000,
position: 'top',
color: 'dark',
});
toast.present();
}
}
**register.html file**
<ion-content padding>
<h2>Register Here</h2>
<form (submit) = "doSignup()">
<ion-item>
<ion-label stacked>Username</ion-label>
<ion-input [(ngModel)] = "regData.name" name = "name" type="text" placeholder = "Your Name"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>IC-Number</ion-label>
<ion-input [(ngModel)] = "regData.icNumber" name = "icNumber" type="number" placeholder = "Your IC-Number"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>E-mail</ion-label>
<ion-input [(ngModel)] = "regData.email" name = "email" type="email" placeholder = "Your E-Mail"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Password</ion-label>
<ion-input [(ngModel)] = "regData.password" name = "password" type="password" placeholder = "Your Password"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Handphone Number</ion-label>
<ion-input [(ngModel)] = "regData.phone" name = "phone" type="tel" placeholder = "Your Phone Number"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Address</ion-label>
<ion-input [(ngModel)] = "regData.address" name = "address" type="text" placeholder = "Your Address"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>City/State</ion-label>
<ion-input [(ngModel)] = "regData.cityState" name = "cityState" type="text" placeholder = "Your City/State"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>House Type</ion-label>
<ion-input [(ngModel)] = "regData.houseType" name = "houseType" type="text" placeholder = "Your House Type"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Category</ion-label>
<ion-select [(ngModel)] = "regData.category" name = "category" type="text" placeholder = "Your Category">
<ion-select-option value="1" selected>Maid</ion-select-option>
<ion-select-option value="2" selected>Customer</ion-select-option>
</ion-select>
</ion-item>
<button ion-button block type = "submit">
SignUp
</button>
</form>
</ion-content>
This seems like a CORS issue, To avoid CORS problem you must use #ionic-native/HTTP plugin which is actually Advanced HTTP plugin for API calls.
Follow below steps to use this plugin
Step 1: Add Http native plugin
$ ionic cordova plugin add cordova-plugin-advanced-http
$ npm install --save #ionic-native/http
Installation Link : HTTP
Step 2: Import HTTP native plugin in your file where you wants to call API.
import { HTTP, HTTPResponse } from '#ionic-native/http';
Step 3: How to use this plugin for API call ?
constructor(public httpPlugin: HTTP) {
}
//Set header like this
this.httpPlugin.setHeader("content-type", "application/json");
//Call API
this.httpPlugin.get(this.url, {}, {}).then((response) => {
//Got your server response
}).catch(error => {
//Got error
});
I want to create an map in my application to show my location with a marker.
I'm using ionic 2 but got blanco page:
http://prntscr.com/dx5czu
This is my code in map.html:
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Map</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-buttons end>
<button ion-button (click)="addMarker()"><ion-icon name="add"></ion-icon>Add Marker</button>
</ion-buttons>
<div #map id="map"></div>
</ion-content>
And my code in map.ts:
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from 'ionic-native';
declare var google;
#Component({
selector: 'page-map',
templateUrl: 'map.html'
})
export class Map {
#ViewChild('map') mapElement: ElementRef;
map: any;
constructor(public navCtrl: NavController) {
}
ionViewDidLoad(){
this.loadMap();
}
loadMap(){
Geolocation.getCurrentPosition().then((position) => {
let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}, (err) => {
console.log(err);
});
}
addMarker(){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: this.map.getCenter()
});
let content = "<h4>Information!</h4>";
this.addInfoWindow(marker, content);
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
}
There are no errors given.
This plugin just wordk in device mobile
The thing is your code is perfect except the following lines
ionViewDidLoad(){
this.loadMap(); }
ionViewDidLoad is in the old version of ionic. To make it working you can push this.loadMap(); in the constructor. So the new code will look like
constructor(public navCtrl: NavController) {
this.loadMap();
}
For more information, you can visit my github repository https://github.com/darpanpathak/LocationTrackerApp
I am trying to develop a mobile application with Ionic framework. It works in the web application, but when it is installed in smartphone, it does not work any more.
code index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" >
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngstorage/ngStorage.min.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyAXp19GmxccWT5A5vVgtQK5NHCaZDb_W0I">
</script>
</head>
<body ng-app="phonegp">
<div class="tabs tabs-icon-top">
<a class="tab-item" ui-sref="actualite">
<i class="icon ion-document-text"></i>
Actualité
</a>
<a class="tab-item" ui-sref="contact">
<i class="icon ion-star"></i>
Contact
</a>
<a class="tab-item" ui-sref="geo">
<i class="icon ion-location"></i>
Géo Localisation
</a>
<a class="tab-item" ui-sref="config">
<i class="icon ion-gear-b"></i>
Settings
</a>
</div>
<ion-side-menus>
<ion-side-menu-content>
<ion-nav-bar class="bar-energized">
<ion-nav-back-button></ion-nav-back-button>
<ion-nav-buttons>
<button menu-toggle="left" class="button button-icon ion-navicon"></button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-nav-view>
</ion-nav-view>
</ion-side-menu-content>
<ion-side-menu side="left">
<ion-item menu-close ui-sref="actualite">Actualite</ion-item>
<ion-item menu-close ui-sref="contact">Contact</ion-item>
<ion-item menu-close ui-sref="geo">Géo Localisation</ion-item>
<ion-item menu-close ui-sref="config">Settings</ion-item>
</ion-side-menu>
</ion-side-menus>
</body>
</html>
code app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
app = angular.module('phonegp', ['ionic','ngCordova','ngStorage'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
app.config(function($stateProvider,$urlRouterProvider){
$stateProvider.state("actualite",{
url : "/actualite",
templateUrl : "templates/actualite.html",
controller:"getactualites"
});
$stateProvider.state("infoActualite",{
url : "/infoAlite",
templateUrl : "templates/infoActualite.html",
controller:"infoActualiteCtrl"
});
$stateProvider.state("contact",{
url : "/contact",
templateUrl : "templates/contact.html"
});
$stateProvider.state("geo",{
url : "/geo",
templateUrl : "templates/geo.html",
controller:"GeoCtrl"
});
$stateProvider.state("config",{
url : "/config",
templateUrl : "templates/config.html"
});
//pour afficher page index
$urlRouterProvider.otherwise("actualite");
})
app.factory("StorageService",function($localStorage){
$localStorage = $localStorage.$default({
trajet: []
});
return {
savePosition:function(pos) {
$localStorage.trajet.push(pos);
},
getAllPositions:function(){
return $localStorage.trajet;
}
}
});
app.controller("getactualites",function($scope,$http,$stateParams){
$http.get('http://192.168.1.4/pfe/web/app_dev.php/api/users')
.then(function successCallback( response ) {
$scope.data = response;
}, function errorCallback(response) {
console.log(response);
alert('error');
})
});
app.controller("infoActualiteCtrl",function($scope,$http){
});
app.controller("GeoCtrl",function($scope,$cordovaGeolocation,StorageService){
var counter;
var currentLatitude;
var currentLongitude;
var markers = [];
var options = {
timeout:10000,
enableHighAccuracy:true
};
$cordovaGeolocation.getCurrentPosition(options)
.then(function(position){
currentLatitude = position.coords.latitude;
currentLongitude = position.longitude;
$scope.position = position;
var latLng= new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
theMap = new google.maps.Map(document.getElementById('map'),mapOptions);
$scope.map=theMap;
$scope.newMarker(position,theMap);
$scope.watchPosition(theMap);
},
function(err) { console.log(err); }
);
$scope.watchPosition=function(theMap){
var watchOptions = {
timeout: 2000,
enableHighAccuracy: true
};
watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
//console.log(err);
},
function(position){
//console.log(position);
if ((position.coords.longitude!=currentLongitude) &&
(position.coords.latitude!=currentLatitude)){
$scope.position = position;
$scope.newMarker(position,theMap);
}
}
);
}
$scope.newMarker=function(position,theMap){
latLng= new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
);
marker = new google.maps.Marker({
position:latLng,
title: "Position"+(++counter),
label: "H"
});
marker.setMap(theMap);
markers.push(marker);
StorageService.savePosition({
lat:position.coords.latitude,
lng: position.coords.longitude
});
}
$scope.showMarker=function(p){
latLng = new google.maps.LatLng(p.lat, p.lng);
marker = new google.maps.Marker({
position:latLng,
label: "H"
});
marker.setMap($scope.map);
markers.push(marker);
}
$scope.hideMarkers=function(){
markers.forEach(function(m){
m.setMap(null);
})
}
$scope.showTrajet= function () {
traj =StorageService.getAllPositions();
traj.forEach(function(p){
$scope.showMarker(p);
});
}
});
code style.css
.contact h5 {
font-weight: bold;
color:#444;
margin-left: 30px;
padding: 8px;
}
.image img {
margin:30px 0 0 40px;
border-radius: 50%;
width:150px;
height:150px;
padding: 10px;
}
.scroll {
height: 100%;
}
#map {
width:100%; height: 100%;
}
.icon {
text-align: center;
padding: 10px;
}
.icon img {
margin-right: 10px;
}
this is screenshot of problemes
enter image description here
Is yout plugins folder in your app's root/main (Same directory as WWW) if not
keep plugins folder in your app's Root directory then create platform with
ionic platform add android
and later app with
ionic build android
try this out
note: replace android with ios in above commands according to your requirement
I am trying to create a sample application that will either take a picture from camera, or load an image from gallery on the screen.
Can someone help me for the same.
You can use $cordovaCamera of ngCordova to take a photo and save it.
Register ngCordova as dependency in app.js:
angular.module('starter', ['ionic', 'starter.controllers', 'ngCordova'])
controller.js:
.controller('PhotosCtrl', function($scope, $cordovaCamera) {
/**
* Add a photo.
*/
$scope.addPhoto = function(){
var options = {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation:true
};
$cordovaCamera.getPicture(options).then(function(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}, function(err) {
console.log("Error while getting the image!", err)
});
};
});
template.html:
<ion-view view-title="Photos">
<ion-content>
<button type="button" class="button" ng-click="addPhoto()">Add photo</button>
<img id="myImage" />
</ion-content>
</ion-view>