Array Length From Google Geolocation (Ionic) - google-maps

Could someone point me in the direction of the correct syntax to use to return the value of results from Google Place Search. Like if my search returned 5 locations, I would like to pull the value of 5 from my array and display that information in my app "5 places have been found!". I have managed to get a list of places nearby. But I am not sure how to get a value.
Right now I use this code to access the array of Google Places Search Results
goToDirectionPage(index){
console.log(this.places);
console.log("index" + index);
let selectedPlace = this.places[index].geometry.location;
console.log(selectedPlace);
this.navCtrl.push(DirectionPage, {
origin: this.currentLocation,
destination: selectedPlace
});
}
Here is the code to the Google Places Search
import { Component} from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
/**
* Generated class for the DirectionPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
declare var google;
#Component({
selector: 'page-direction',
templateUrl: 'direction.html',
})
export class DirectionPage {
origin: any;
destination: any;
map: any;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.origin = navParams.get('origin');
this.destination = navParams.get('destination');
this.map = navParams.get('map');
}
ionViewDidLoad() {
this.calculateRoute();
console.log('ionViewDidLoad DirectionPage');
}
calculateRoute(){
let mapOptions = {
center: this.origin,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById("directionMap"), mapOptions);
let directionsService = new google.maps.DirectionsService();
let directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(this.map);
let request = {
origin: this.origin,
destination: this.destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status){
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById('directionPanel'));
}else{
console.warn(status);
}
});
}
}
Desired Result

In places.html
<ion-card>
<ion-item ng-if = "places" >
Places Found: {{places?.length}}
</ion-item>
</ion-card>
<ion-card id="result"> </ion-card>
<button ion-item *ngFor = "let place of places; let i = index" (click)="goToDirectionPage(i)">
{{place.name}} + <br/> {{place.vicinity}} <br /> Average Rating: {{place.rating}}
</button>
</ion-list>

Related

How to display route with native google maps on Ionic 3

I'm building a project in Ionic 3, I'm using the native maps plugin for Ionic, I can show the map and I can add a marker in a selected address, but I have not managed to show the recommended route on the map.
HTML:
<div id="map"></div>
TS:
loadMap(){
var lat = this.placeInfo.latitudeFrom;
var lng = this.placeInfo.longitudeFrom;
let mapOptions: GoogleMapOptions = {
camera: {
target: {
lat: lat,
lng: lng,
gestureHandling: 'none',
zoomControl: true
},
zoom: 18,
tilt: 30,
}
};
this.map = GoogleMaps.create('map', mapOptions);
this.map.one(GoogleMapsEvent.MAP_READY)
.then(() => {
let marker: Marker = this.map.addMarkerSync({
title: 'Ionic',
icon: 'blue',
animation: 'DROP',
position: {
lat: lat,
lng:lng
}
});
})
.catch(error =>{
console.log('error: ', error);
});
}
I'm trying this, but does not work
displayRoutev2() {
this.directionsService.route({
origin: this.placeInfo.startPoint,
destination: this.placeInfo.endPoint,
travelMode: 'DRIVING'
}, (response, status) => {
if (status === 'OK') {
this.directionsDisplay.setDirections(response);
this.directionsDisplay.setMap(this.map);
} else {
window.alert('No se encontraron rutas disponibles.' + status);
}
});
var service = new google.maps.DistanceMatrixService();
}
Can I use the var "service" to call any function? Or I need to try another way?
I can show route with another way that is not the better way, I need to use this native way, someone knows whats I can do?
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '#angular/core';
import {FormBuilder, FormGroup, Validators} from '#angular/forms';
declare var google;
#Component({
selector: 'app-direction',
templateUrl: './direction.page.html',
styleUrls: ['./direction.page.scss'],
})
export class DirectionPage implements OnInit, AfterViewInit {
#ViewChild('mapElement') mapNativeElement: ElementRef;
#ViewChild('directionsPanel') directionsPanel: ElementRef;
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
directionForm: FormGroup;
constructor(private fb: FormBuilder) {
this.createDirectionForm();
}
ngOnInit() {
}
createDirectionForm() {
this.directionForm = this.fb.group({
source: ['', Validators.required],
destination: ['', Validators.required]
});
}
ngAfterViewInit(): void {
const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
this.directionsDisplay.setMap(map);
directionsDisplay.setPanel(this.directionsPanel.nativeElement);
}
DisplayRoute(formValues) {
const that = this;
this.directionsService.route({
origin: formValues.source,
destination: formValues.destination,
travelMode: 'DRIVING'
}, (response, status) => {
if (status === 'OK') {
that.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
==In home.page.ts==
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button></ion-menu-button>
</ion-buttons>
<ion-title>Direction</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<form [formGroup]="directionForm" (ngSubmit)="DisplayRoute(directionForm.value)">
<ion-item>
<ion-label position="floating">Source</ion-label>
<ion-input formControlName="source"></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating">Destination</ion-label>
<ion-input formControlName="destination"></ion-input>
</ion-item>
<ion-button expand="full" type="submit" [disabled]="directionForm.invalid">Get Direction</ion-button>
</form>
<ion-card>
<ion-card-content>
<div #directionsPanel></div>
</ion-card-content>
</ion-card>
<div #mapElement class="map"></div>
</ion-content>

Google API to detect location closest to the user from a list of locations

I have a phone app developed in Ionic which supposedly only supports a few stores. What I want to do is to use Cordova Geolocation to fetch the user's current location, and use it to find a store in our support list closest to their location. What would be the best Google API to use for this, Google Maps or Google Places? Also what would be the easiest way for me to achieve this?
Other than finding the store I don't need to use any other map functionality.
Place Search Requests (https://developers.google.com/places/web-service/search#PlaceSearchRequests)
A Nearby Search query
https://maps.googleapis.com/maps/api/place/nearbysearch/json?parameters
Required parameters in above query
key : Your applications API key.
location : The latitude/longitude around which to retrieve place information.
radius : Defines the distance (in meters) within which to return place results
rankby : distance
type : Restricts the results to places matching the specified type. list of supported types (https://developers.google.com/places/web-service/supported_types)
Example
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=store&key=YOUR_API_KEY
IONIC IMPLIMENTATION
Install the Cordova and Ionic Native plugins
`$ ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"`
`$ npm install --save #ionic-native/geolocation`
HTML
<ion-header>
<ion-navbar>
<ion-title>
Google Maps NearBy Search
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<div #map id="map"></div>
</ion-content>
js
import { Component, ElementRef, ViewChild } from '#angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
import { googlemaps } from 'googlemaps';
declare var google;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
#ViewChild('map') mapElement: ElementRef;
map: any;
latLng: any;
options: any;
infowindow: any;
constructor(private ngZone: NgZone, private geolocation: Geolocation) {}
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public geolocation: Geolocation) {}
ionViewDidLoad() {
this.initMap();
}
initMap() {
this.geolocation.getCurrentPosition().then((resp) => {
this.latLng = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
this.options = {
center: this.latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(this.mapElement.nativeElement, this.options);
let service = new google.maps.places.PlacesService(this.map);
service.nearbySearch({
location: this.latLng,
radius: 1000,
type: ['store']
}, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
this.createMarker(results[i]);
}
}
});
}).catch((error) => {
console.log('Error getting location', error);
});
}
createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: placeLoc
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
}

Ionic 2 Google Maps:: Uncaught (in promise): TypeError: Cannot read property 'firstChild' of null

I'm using ionic 2 and trying to load google map using its JS API.
Here is my code:
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController, Platform, NavParams } from 'ionic-angular';
declare var google;
#Component({
selector: 'page-map',
templateUrl: 'map.html',
})
export class MapPage {
#ViewChild('map') mapElement: ElementRef;
map: any;
latitude : any;
longitude : any;
constructor(public platform: Platform, public navCtrl: NavController,public navParams: NavParams) {
this.platform = platform;
this.initializeMap();
}
ionViewDidLoad(){
this.initializeMap();
}
initializeMap() {
this.platform.ready().then(() => {
var minZoomLevel = 12;
this.map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var position = new google.maps.LatLng("23.032612699999998", "72.56187790000001");
var dogwalkMarker = new google.maps.Marker({position: position, title: "Testing"});
dogwalkMarker.setMap(this.map);
});
}
}
I have also added reference of the JS in my index.html file before cordova.js:
<script src="http://maps.google.com/maps/api/js"></script>
Here is my html:
<ion-header>
<ion-navbar hideBackButton side="left">
<ion-title style="margin-left: 0px;"><span class="menuTitle">Map</span></ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<div #map id="map"></div>
</ion-content>
The code does not display any error but when I try to load this page it displays error like:
Uncaught (in promise): TypeError: Cannot read property 'firstChild' of null
Use mapElement
Typescript file
let minZoomLevel = 12;
let mapOptions = {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

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

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

Ionic2 google maps image layer

I am building an Ionic2 app where I am using google maps as an orientation map and I need to put an image layer on top of the map. I am trying to put building layout image over the building complex in Google maps.
I found this solution for javascript here, which is exactly what I need: Google maps js API
I am quite new to Ionic2 and Anglular2 and having no luck figuring it out so far.
Any advice appreciated
My code :
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
declare var google;
#Component({
selector: 'map',
templateUrl: 'map.html'
})
export class MapPage {
#ViewChild('map') mapElement: ElementRef;
map: any;
lat : any ;
lng : any ;
constructor(public navCtrl: NavController, public geolocation: Geolocation) {
this.getGeoLocation();
}
initializeMap() {
var minZoomLevel = 17;
let mapOptions =
{
zoom: minZoomLevel,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
getGeoLocation(){
this.geolocation.getCurrentPosition().then((position) => {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
this.initializeMap();
}, (err) => {
console.log(err);
});
}
Well, apparently it was easier than I thought. You just define image boundaries and create an instance of an overlay and then add it to the map like this...
var oldBuilding = {
north: 53.27959,
west: -9.01287,
south: 53.278038,
east: -9.00876
};
this.oldBuildingOverLay = new google.maps.GroundOverlay('../assets/Map.png', oldBuilding);
this.oldBuildingOverLay.setMap(this.map);
Declare oldBuildingOverlay: any; and you're up and running.