Show country name on app - google-maps

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);
}
...
}

Related

How to get JSON data into Dialog Component

Before this, the JSON Data appears when hovering over the info icon. Now i wish to pass the JSON Data into a dialog when click the info icon. But i dont know how.
HTML
<h2 mat-dialog-title>Info</h2>
<mat-dialog-actions>
<button mat-button (click)="matDialogRef.close()">Ok</button>
</mat-dialog-actions>
Dialog-Component.ts
import { Component, OnInit, Input, Inject, ViewEncapsulation, HostListener } from '#angular/core';
import { MAT_DIALOG_DATA, MatDialogRef} from '#angular/material';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
import { PlannerProject } from 'app/services/planner-projects/planner-project';
#Component({
selector: 'app-my-dialog',
templateUrl: './my-dialog.component.html',
styleUrls: ['./my-dialog.component.scss']
})
export class MyDialogComponent implements OnInit {
#Input() project: PlannerProject;
projectData: string;
constructor(public matDialogRef: MatDialogRef<MyDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
}
ngOnChanges(event): void {
if (event.project !== undefined) {
this.projectData = JSON.stringify(this.project, null, 2);
}
}
ok(): void {
this.matDialogRef.close();
}
}
Delivery-Order.Component.ts
import { DeliveryOrderEditComponent } from './../delivery-order-edit/delivery-order-edit.component';
import { SelectionModel } from '#angular/cdk/collections';
import { Component, OnInit, ViewChild, OnDestroy, ElementRef, Input, OnChanges } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { PlannerProjectsService } from 'app/services/planner-projects/planner-projects.service';
import { map, switchMap, tap, debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { DeliveryOrdersService } from '../delivery-orders.service';
import { Observable, of, Subscription, fromEvent } from 'rxjs';
import * as moment from 'moment';
import { MatPaginator, MatSort, PageEvent, MatTableDataSource, MatDialog } from '#angular/material';
import * as _ from 'lodash';
import { FuseSidebarService } from '#fuse/components/sidebar/sidebar.service';
import { DeliveryOrder } from '../delivery-order';
import { MyDialogComponent } from './../my-dialog/my-dialog.component';
import { PlannerProject } from 'app/services/planner-projects/planner-project';
import { FuseConfirmDialogComponent } from '#fuse/components/confirm-dialog/confirm-dialog.component';
import { UploadExcelService } from 'app/services/upload-excel.service';
#Component({
selector: 'app-delivery-orders',
templateUrl: './delivery-orders.component.html',
styleUrls: ['./delivery-orders.component.scss']
})
export class DeliveryOrdersComponent implements OnInit, OnDestroy, OnChanges {
#Input() project: PlannerProject;
#ViewChild(MatPaginator) paginator: MatPaginator;
#ViewChild(MatSort) sort: MatSort;
selection: SelectionModel<DeliveryOrder>;
importId: string;
dataTable;
sub: Subscription;
projectData : string;
// _filter: string;
_sortBy: string;
_sortOrder = 'asc';
_pageSize = 10;
_pageIndex = 1;
_options = {
pageSize: 100,
pageSizeOptions: [100, 150, 200, 250]
};
_displayedColumns = [
{ displayName: 'Location Name', column: 'locationName', sort: true },
{ displayName: 'Delivery Address', column: 'address', sort: false },
{ displayName: 'Is Valid', column: 'isValid', sort: false },
{ displayName: 'Import At', column: 'importedAt', sort: false },
{ displayName: 'File Name', column: 'importFileName', sort: false },
// { displayName: '', column: '' },
// { displayName: '', column: '' },
];
_displayColumns: string[] = ['selectRow', 'locationName', 'address', 'quantity', 'weight', 'volume', 'remarks', 'importedAt', 'actions'];
_actions = [
{
text: 'Edit',
action: (row) => {
console.log(`row`, row);
}
}
];
_dataSource: MatTableDataSource<DeliveryOrder>; // = new DeliveryOrdersDataSource(this.deliveryOrderService, '');
_filter: string | Observable<string>;
// #ViewChild('listHeader') listHeader: PageListTemplateComponent;
#ViewChild('search') search: ElementRef;
constructor(private route: ActivatedRoute,
private router: Router,
private projectService: PlannerProjectsService,
private deliveryOrderService: DeliveryOrdersService,
private uploadExcelService: UploadExcelService,
private _matDialog: MatDialog) { }
openDialog(): void {
const Ref = this._matDialog.open(MyDialogComponent, {
});
Ref.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log(result);
});
}
ngOnInit(): void {
this.initDataTable();
}
ngOnDestroy(): void {
console.log(`destroy`);
if (this.sub) {
this.sub.unsubscribe();
}
}
ngOnChanges(): void {
if (this.project !== undefined) {
this.projectData = JSON.stringify(this.project, null, 2);
this.loadList(this.project.importId).toPromise().then((data) => {
console.log(`data`, data);
_.map(data, this.formatData.bind(this));
this.dataTable = data;
this._dataSource.data = this.dataTable;
this.selection = new SelectionModel<DeliveryOrder>(true, []);
});
}
So when i click the info icon, it shall display the JSON data in the dialog box. i also added the Delivery-order.component. I dont know much about JSON, so im very weak in trying to solve this problem to make the JSON values show up
When you create your dialog in delivery-component you can define input data for your dialog component, in this way:
const Ref = this._matDialog.open(MyDialogComponent, {
data: { id: 'id-value' }
});
Then you can recover your data in your dialog component:
constructor(public matDialogRef: MatDialogRef<MyDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) {
console.log(this.data.id);
}
In this example this.data will contain the data passed from your main component to dialog, the id field is only an example, you can pass whatever you want to dialog component.
Try something like this.
First method will open dialog and will pass all the data of the project
openDialog(): void {
const Ref = this._matDialog.open(MyDialogComponent, { data: this.project });
And in the dialog just use as the #Simo said
This will Inject the passed data from component to dialog
constructor(public matDialogRef: MatDialogRef<MyDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) {
console.log(this.data);
}

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.")
);
}
}

Use Google maps NodeJS geocode callback function results to draw map on AngularJS 2 component template

Hi all I am using the googles maps nodejs client web api and would like to display a map on my HTMLviews through AngularJS 2.
I have this server export that returns an object to my AngularJS2 client service
const googleMapsClient = require('#google/maps').createClient({
key: 'AIzaSyCYcyd0vCGRY6Pq5E0u_ECTFi4I9VmUE4o'
});
module.exports = (req, res) => {
googleMapsClient.geocode({
address: 'Cosmo City, Roodepoort USA street'
}, function(err,response) {
if(err) {
console.log("There was an error geocoding the address", err)
} else {
console.log("Here is the maps response", response.json.results)
var obj = {
name: "Thabo",
age: 23,
maps: response.json.results
};
res.json({obj});
}
});
}
The Angular2 services looks like this
#Injectable()
export class MyService {
constructor(private http: Http) { }
getMessage(): Promise<mma> {
return this.http.get('/map-moving-agents')
.toPromise()
.then((res)=> {
console.dir(res.json().maps);
return res.json().obj;
})
.catch(this.handleError);
}
Everything seems to be fine, I get the expected response from the server, now i would like to use this response to draw a map on my component template.
And then here is my AngularJS2 component
#Component({
moduleId:module.id,
selector: 'map-moving-agents',
templateUrl: 'moving-agents.html',
styleUrls: ['moving-agents.css'],
providers: [ MyService ]
})
export class MapMovingAgents implements OnInit{
msg : mma;
constructor(private myService: MyService ){}
getMessage(): void {
this.myService.getMessage().then((res) => {
this.msg = res;
console.log(this.msg.name);
})
}
ngOnInit(): void {
this.getMessage();
}
}
I have used the angular2-google-maps package, i now have this In my component class
export class MapMovingAgents implements OnInit{
map: any;
lat: number;
lng: number;
zoom: number = 18;
constructor(private myService: MyService ){}
getMessage(): void {
this.myService.getMessage().then((res) => {
this.map = res;
this.lat = this.map.maps[0].geometry.location.lat;
this.lng = this.map.maps[0].geometry.location.lng;
console.log(this.lat,this.lng);
})
}
And have this in my tempate
<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
<sebm-google-map-marker [latitude]="lat" [longitude]="lng"></sebm-google- map-marker>
</sebm-google-map>
I have also updated my app module by importing the module and passed it the api key
import { AgmCoreModule } from 'angular2-google-maps/core';
imports: [... AgmCoreModule.forRoot({
apiKey: 'AIzMSNPY'
})...]
You can read through the angular2-google-maps here

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