Ionic2: Unable to set distance and duration from google directions service API - google-maps

Need help with Google Directions Service with ionic2. I am trying to set the distance and duration variables after calculating it via the route function. The value is coming as undefined when i access in another method (like the onClickMap here).
Below is the code that I have created:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
declare var google;
#IonicPage()
#Component({
selector: 'page-activity-detail',
templateUrl: 'activity-detail.html',
})
export class ActivityDetailPage {
public dist: any;
public dur: any;
latLng: any;
directionsDisplay = new google.maps.DirectionsRenderer;
constructor(public navCtrl: NavController, public navParams: NavParams, public geolocation: Geolocation) {
}
ionViewDidLoad() {
this.geolocation.getCurrentPosition().then((position) => {
this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let destination = new google.maps.LatLng(this.activity.address.latitude, this.activity.address.longitude);
let directionService = new google.maps.DirectionsService;
directionService.route({
origin: this.latLng,
destination: destination,
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.IMPERIAL,
provideRouteAlternatives: false
}, function(response, status) {
if (status == 'OK') {
let t = 0;
let d = 0;
let myroute = response.routes[0];
console.log(myroute);
for (let i = 0; i < myroute.legs.length; i++) {
t += myroute.legs[i].distance.value;
d += myroute.legs[i].duration.value;
}
this.dist = t / 1000;
this.dur = d /60;
} else {
console.log(status);
}
});
}, (err) => {
console.log(err);
});
}
onClickMap(){
alert(this.dist);
alert(this.dur);
}
}

Related

Googlmap.getCameraPosition() not working for iOS

Googlemap.getCameraPosition() doesn't do any thing for iOS , neither it goes to then block or catch bolck and doesn't console anything inside it.
But on android it is working perfectly fine.
Also other methods of GoogleMap is not working for iOS, the pointer never goes to this.map.on(GoogleMapsEvent.MAP_READY) in case of iOS
import { Component, ViewChild, ElementRef, OnInit, AfterViewInit } from '#angular/core';
import { NavController,NavParams,Events, ViewController, Platform } from 'ionic-angular';
import { GoogleMap, GoogleMapsEvent, GoogleMapsLatLng,CameraPosition, Geolocation } from 'ionic-native';
import _ from 'lodash';
#Component({
selector: 'page-map-modal',
templateUrl: 'map-modal.html'
})
export class MapModalPage implements OnInit,AfterViewInit {
#ViewChild('map') mapElement: ElementRef;
lat: any;
lng: any;
map:GoogleMap;
target:any;
position:any;
constructor(public navCtrl: NavController,
public viewCtrl: ViewController,
public platform: Platform,
public events: Events,
private alert:AlertController,
private navParam: NavParams) {
this.target = this.navParam.get('location');
}
//get current location of user
ngOnInit() {
Geolocation.getCurrentPosition().then((result)=>{
this.position = result;
},(error)=>{
// console.log(error,"error occured while getting geolocation");
})
}
ngAfterViewInit(){
this.platform.ready().then(() => {
this.loadMap();
});
}
loadMap(){
let location = null;
if(this.target['lat'] && this.target['lng']){
location = new GoogleMapsLatLng(Number(this.target['lat']),Number(this.target['lng']));
}else{
location = new GoogleMapsLatLng(24.795464,46.699796);
}
this.map = new GoogleMap('map', {
'backgroundColor': 'white',
'controls': {
'compass': true,
'myLocationButton': true,
'indoorPicker': true,
'zoom': true
},
'gestures': {
'scroll': true,
'tilt': false,
'rotate': true,
'zoom': true
},
'camera': {
'latLng': location,
'tilt': 20,
'zoom': 15,
'bearing': 50
}
});
this.map.setCenter(location);
this.map.on(GoogleMapsEvent.MAP_READY).subscribe(() => {
this.map.refreshLayout();
this.map.clear();
if((_.isEmpty(this.target['lat']) || this.target['lat'] == '0') && (_.isEmpty(this.target['lng']) || this.target['lng'] == '0')){
this.map.getMyLocation().then((target)=>{
location = new GoogleMapsLatLng(target.latLng.lat,target.latLng.lng);
let position: CameraPosition = {
target: location,
zoom: 15,
tilt: 30,
bearing: 50
};
// // move the map's camera to position
this.map.moveCamera(position);
this.map.setCenter(location);
// console.log(target.latLng.lat, target.latLng.lng,"current user location");
},(error)=>{
// console.log(error,"error in getting current location");
})
}
});
}
dismiss(){
this.navCtrl.pop();
}
pickLocationAndDismiss(){
let target;
this.map.getCameraPosition().then((data)=>{
target = data.target;
this.events.publish('latlng:map',target);
}).catch(err=>{
console.log(err)
});
this.navCtrl.pop();
}
}

Show country name on app

Im getting cordova notification on the console when I try to see my current country name on the browser.
There's something method or alternative to show me that on my tests.html, like in an input field (in the browser)?
On the other hand, if exist another alternative to show actual country name, please tell me.
tests.ts
import { Component, ViewChild, ElementRef } from "#angular/core";
import { NavController, IonicPage, NavParams } from "ionic-angular";
import {
NativeGeocoder,
NativeGeocoderReverseResult
} from "#ionic-native/native-geocoder";
import { Geolocation } from "#ionic-native/geolocation";
declare var google;
#IonicPage()
#Component({
selector: "page-tests",
templateUrl: "tests.html"
})
export class TestsPage {
#ViewChild("mapSmall") mapElement: ElementRef;
map: any;
message: any;
location: any;
gmLocation: { lat: number; lng: number } = { lat: 0, lng: 0 };
constructor(
public navCtrl: NavController,
private geolocation: Geolocation,
private nativeGeocoder: NativeGeocoder,
public navParams: NavParams,
) {
this.onLocateUser();
}
onLocateUser() {
this.geolocation
.getCurrentPosition()
.then(location => {
console.log(
"position gotten: long:",
location.coords.longitude,
" lat:",
location.coords.latitude
);
this.location = location;
this.gmLocation.lat = location.coords.latitude;
this.gmLocation.lng = location.coords.longitude;
this.nativeGeocoder.reverseGeocode(location.coords.latitude,location.coords.longitude)
.then((result: NativeGeocoderReverseResult) => console.log(JSON.stringify(result.countryName)))
.catch((error: any) => console.log(error));
})
.catch(error => {
console.log("Error getting location", error);
});
}
ionViewDidLoad() {
let latlng = new google.maps.LatLng(
this.gmLocation.lat,
this.gmLocation.lat
);
setTimeout(() => {
this.loadMap(latlng);
this.addMarker(this.gmLocation.lat, this.gmLocation.lng);
}, 100);
}
...
}

Data are not showing when two api called in` iondidenter`

I have one screen, which have two gridview . each grid view will populate some value after api calling. so my page will have 2 api calling. so when i call my api call method under constructor or ionViewDidEnter its not working. it allowing only one method to exeute.
here is my two api call method on one page .ts
Even i put under my constructor. But its not showing the data. so if i want to call the both api and need to display the data means how can i do that.please help me out. i was not able to find it out !!
Thanks in advance
updated:
import { Component, ViewChild } from '#angular/core';
import { AlertController, App, FabContainer, ItemSliding, List, ModalController, NavController, ToastController, LoadingController, Refresher } from 'ionic-angular';
import { CategoryDetailPage } from '../categorydetail/categorydetail';
import { ConferenceData } from '../../providers/conference-data';
import { UserData } from '../../providers/user-data';
import { SessionDetailPage } from '../session-detail/session-detail';
import { ScheduleFilterPage } from '../schedule-filter/schedule-filter';
import {Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
import { AuthService } from '../../providers/AuthService';
#Component({
selector: 'page-speaker-list',
templateUrl: 'speaker-list.html'
})
export class SpeakerListPage {
loading: any;
data: any;
Catdata: any;
Catdatanames: any;
resdata: any;
resCatdata: any;
resCatdatanames: any;
loginData: {username?: string} = {};
resloginData: {username?: string} = {};
constructor(
public alertCtrl: AlertController,
public app: App,
public loadingCtrl: LoadingController,
public modalCtrl: ModalController,
public navCtrl: NavController,
public toastCtrl: ToastController,
public confData: ConferenceData,
public user: UserData,
public http:Http,
public authService: AuthService
) {
}
ionViewDidEnter() {
this.show();
this.another();
}
show() {
this.showLoader();
this.authService.subs(this.loginData).then((result) => {
this.loading.dismiss();
this.data = result;
if(this.data.status == 1)
{
this.Catdata = this.data.SubjectList;
//this.Catdata.forEach(category => console.log(category.CatID));
for(let i=0; i<this.Catdata.length; i++) {
// console.log(this.Catdata[i].SubjectName);
}
}
else if(this.data.status == 0) {
let alert = this.alertCtrl.create({
title: 'Error',
subTitle: 'Please Enter Valid Username & Password',
buttons: ['OK']
});
alert.present();
}
}, (err) => {
this.loading.dismiss();
});
}
another() {
this.authService.allresources(this.resloginData).then((result) => {
this.resdata = result;
if(this.resdata.status == 1)
{
this.resCatdata = this.resdata.SubjectList;
for(let i=0; i<this.resCatdata.length; i++) {
// console.log(this.resCatdata[i].FileName);
}
}
else if(this.resdata.status == 0) {
let alert = this.alertCtrl.create({
title: 'Error',
subTitle: 'Please Enter Valid Username & Password',
buttons: ['OK']
});
alert.present();
}
}, (err) => {
});
}
showLoader(){
this.loading = this.loadingCtrl.create({
content: 'Authenticating...'
});
this.loading.present();
}
}

Angular 2 HTTP GET with TypeScript google geocode service

I am new to angular2 and trying to find the coordinates(latitude,longitude) using the location.
here is my code,
GeoService.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class GeoService {
constructor(private http: Http) { }
getLocation(term: string) {
return this.http.get('http://maps.google.com/maps/api/geocode/json?address=' + term + 'CA&sensor=false').map
((response) => response.json());
}
// tslint:disable-next-line:eofline
}
app.component.html
<!DOCTYPE HTML>
<h1> {{title}} </h1>
<input type="text" [(ngModel)]="location" />
<button (click)="findLocation($event)">Find location</button>
<sebm-google-map
[latitude]="lat"
[longitude]="lng"
[zoom]="zoom"
[disableDefaultUI]="false"
[zoomControl]="false"
(mapClick)="mapClicked($event)">
<sebm-google-map-marker
*ngFor="let m of markers; let i = index"
(markerClick)="clickedMarker(m.label, i)"
[latitude]="m.lat"
[longitude]="m.lng"
[label]="m.label"
[markerDraggable]="m.draggable"
(dragEnd)="markerDragEnd(m, $event)">
<sebm-google-map-info-window>
<strong>InfoWindow content</strong>
</sebm-google-map-info-window>
</sebm-google-map-marker>
<sebm-google-map-circle [latitude]="lat + 0.3" [longitude]="lng"
[radius]="5000"
[fillColor]="'red'"
[circleDraggable]="true"
[editable]="true">
</sebm-google-map-circle>
</sebm-google-map>
app.component.ts
import { Component } from '#angular/core';
import { GeoService } from './GeoService';
#Component({
selector: 'my-app',
moduleId: module.id,
templateUrl: `./app.component.html`,
styleUrls: ['/app.componenet.css'],
providers :[GeoService]
})
export class AppComponent {
title = 'Angular2 google map test';
lat: number = 51.673858;
lng: number = 7.815982;
zoom: number = 8;
markers: marker[] = [
{
lat: 51.673858,
lng: 7.815982,
label: 'A',
draggable: true
},
{
lat: 51.373858,
lng: 7.215982,
label: 'B',
draggable: false
},
{
lat: 51.723858,
lng: 7.895982,
label: 'C',
draggable: true
}
];
location: string;
findLocation(): void {
this.result= this.geoService.getLocation(this.location);
}
constructor(private geoService: GeoService) {
}
clickedMarker(label: string, index: number) {
}
mapClicked($event: MouseEvent) {
}
markerDragEnd(m: marker, $event: MouseEvent) {
console.log('dragEnd', m, $event);
}
}
// tslint:disable-next-line:class-name
interface marker {
lat: number;
lng: number;
label?: string;
draggable: boolean;
}
how to get the result in app.component.ts?
findLocation(): void {
this.result= this.geoService.getLocation(this.location);
}
Hopefully you are not still stuck on this. While this might no longer help you, hopefully it will help someone else. Here is what I did just now. First change the getLocation function to this. This is for the current Angular2 release.
getLocation(term: string):Promise<any> {
return this.http.get('http://maps.google.com/maps/api/geocode/json?address=' + term + 'CA&sensor=false')
.toPromise()
.then((response) => Promise.resolve(response.json()));
.catch((error) => Promise.resolve(error.json()));
}
And then in app.component.ts, change it to this.
findLocation(): void {
this.geoService.getLocation(this.location)
.then((response) => this.result = response.results[0])
.catch((error) => console.error(error));
}
I added some error control because that is always good to have. And I had a results array return inside response so clarify with the user which address they want if there is more than one returned.
angular 7.1.4 httpclient is used. getLocation returns obserable
location.service.ts renamed GeoService.ts
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { Observable } from "rxjs";
#Injectable({
providedIn: "root"
})
export class LocationService {
constructor(private http: HttpClient) {}
getLocation(term: string): Observable<any> {
return this.http.get(
"http://maps.google.com/maps/api/geocode/json?address=" +
term +
"CA&sensor=false&key=API_KEY"
);
}
}
location.component.ts
/// <reference types="#types/googlemaps" />
import { Component, OnInit, AfterContentInit, ViewChild } from "#angular/core";
import { LocationService } from "../location.service";
declare let google: any;
#Component({
selector: "app-location",
templateUrl: "./location.component.html",
styleUrls: ["./location.component.scss"],
providers: [LocationService]
})
export class LocationComponent implements OnInit {
#ViewChild("gmap") gmapElement: any;
map: google.maps.Map;
latitude: number;
longitude: number;
marker: google.maps.Marker;
locationStr: string;
public result: any;
countMarkers = 0;
constructor(public geoService: LocationService) {}
ngOnInit() {
this.setCurrentPosition();
// tslint:disable-next-line:prefer-const
let mapProp = {
center: new google.maps.LatLng(0, 0),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
};
this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
}
setCenter(e: any) {
e.preventDefault();
this.map.setCenter(new google.maps.LatLng(this.latitude, this.longitude));
}
setCurrentPosition() {
navigator.geolocation.getCurrentPosition(position => {
console.log("Set position", position.coords);
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.map.setCenter(new google.maps.LatLng(this.latitude, this.longitude));
const location = new google.maps.LatLng(this.latitude, this.longitude);
this.map.panTo(location);
if (!this.marker) {
this.marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: false,
title: "You Loation!"
});
this.marker.setLabel("You");
this.marker.setMap(this.map);
} else {
this.marker.setPosition(location);
}
});
}
setMarker(label = ".") {
const location = new google.maps.LatLng(this.latitude, this.longitude);
this.map.panTo(location);
if (!this.marker) {
this.marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: false,
title: "You Loation!"
});
this.marker.setLabel(label);
this.marker.setMap(this.map);
} else {
this.marker.setLabel(label);
this.marker.setPosition(location);
}
}
addMarker(label = "") {
const location = new google.maps.LatLng(this.latitude, this.longitude);
// this.map.panTo(location);
const newMarker = new google.maps.Marker({
position: location,
map: this.map,
draggable: false,
title: "You Loation!"
});
this.countMarkers++;
label = this.countMarkers.toString();
newMarker.setLabel(label);
newMarker.setMap(this.map);
}
findLocation(): void {
this.geoService
.getLocation(this.locationStr)
.subscribe(
(data: any) => (
(this.result = data.results[0].geometry.location),
console.log(data.results[0].geometry.location),
(this.latitude = data.results[0].geometry.location.lat),
(this.longitude = data.results[0].geometry.location.lng),
this.map.setCenter(
new google.maps.LatLng(this.latitude, this.longitude)
),
this.addMarker()
),
(err: any) => console.log(err),
() => console.log("All done getting location.")
);
}
}

Angular2/ionic2 angular2-google-maps error Cannot find name 'google'

I followed the this example (click here) to make a field of address with autocompletion of google map Places,
But it's giving the following error:
Can not find name 'google'.
L53: this.mapsAPILoader.load (). Then (() => {
L54: let autocomplete = new google.maps.places.Autocomplete
(this.searchElementRef.nativeElement, {
I tried to install google-maps types npm install --save #types/google-maps but it is without results.
After installing #types/google-maps the build is ok but when I luanch i have this error :
Cannot find name 'google' after installing #types/google-maps
My Code :
import { FormControl } from '#angular/forms';
import { Component, ViewChild, OnInit, ElementRef } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { MapsAPILoader } from 'angular2-google-maps/core';
#Component({
selector: 'page-page2',
templateUrl: 'page2.html'
})
export class Page2 implements OnInit {
latitude: number = 51.678418;
longitude: number = 7.809007;
zoom: number = 4;
searchControl: FormControl;
#ViewChild("search")
searchElementRef: ElementRef;
constructor(public navCtrl: NavController, public navParams: NavParams, private mapsAPILoader: MapsAPILoader) {
// some not related to this question code
}
ngOnInit() {
//create search FormControl
this.searchControl = new FormControl();
//set current position
this.setCurrentPosition();
//load Places Autocomplete
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
//set latitude and longitude
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
});
});
}
private setCurrentPosition() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 12;
});
}
}
}
Run typings install dt~google.maps --global
as found here