Ionic 2 with Google maps - Blank screen appear - google-maps

I guess it should be simple for the ionic/Angular people.
from some reason, I can't get this simple script to work (Ionic2 with GMaps).
Here is my code:
Map.html:
<ion-navbar *navbar>
<button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Google Map</ion-title>
<ion-buttons end>
<button (click)="addMarker()">
<ion-icon name="add"></ion-icon>Add Marker
</button>
</ion-buttons>
</ion-navbar>
<ion-content padding class="map">
<div id="map"></div>
</ion-content>
Map.ts:
import {Page, NavController, Platform} from 'ionic-angular';
import {Geolocation} from 'ionic-native';
/*
Generated class for the MapPage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Page({
templateUrl: 'build/pages/map/map.html',
})
export class MapPage {
constructor(public nav: NavController, platform: Platform) {
this.nav = nav;
this.map = null;
// this.platform = platform;
// this.initializeMap();
this.platform = platform;
platform.ready().then(() => {
this.loadMap();
});
}
loadMap(){
let options = {timeout: 10000, enableHighAccuracy: true};
Geolocation.getCurrentPosition(options).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(document.getElementById("map"), mapOptions);
});
}
}
I have added my code here (Ionic2 project with Gmap inside):
http://plnkr.co/edit/ERnCxooM1IWD3qVLMQ1K?p=preview
you can find inside: "home.ts" the script, I have comment the code below, since in the moment I'm adding it back All of my ionic project is down, you can try and uncomment it.
I also have found Angular2 with Gmap project, But I couldn't find Ionic2 project with Gmap. here:
Angular2 Gmap
Anyone can see what is wrong there?
Thank you very much!
Eran.

Check if you installed the plugin a correct way.
Validate your API keys at console.developers.google.com
Be sure the HTML element where the maps get injected into has a
predefined height property.
Be sure you run your app on a connected or virtual
device.
If that doesn't work: I've created an Ionic 2.0.0-rc.5 starter with minimal functionality https://github.com/0x1ad2/ionic2-starter-google-maps

I have created an example app with ionic2 and google map.
https://github.com/nazrul104/google-map-with-ionic2. It may help you!

Thanks to #Nazrul here is the changes I made in my ts page file:
export class Page1 {
constructor() {
this.loadMap();
}
loadMap(){
let options = {timeout: 10000, enableHighAccuracy: true};
//ENABLE THE FOLLOWING:
Geolocation.getCurrentPosition(options).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(document.querySelector('#map'), mapOptions);
var x = document.querySelector('#map');
console.log(x);
});
}
}
Now I can see the map :)

My solution was, do not initialize the map on the constructor, initialize it on the ionViewDidLoad.
ionViewDidLoad() {
console.log('ionViewDidLoad Maps');
setTimeout(()=>{
this.loadMap();
}, 1000)
}

Related

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

Google Map not showing with Ionic 2 native google-maps plugin

I am trying to embed a google map on my Ionic 2 app, but the map is not showing.
I took the code from https://ionicframework.com/docs/native/google-maps/
Here is my code :
home.html
<ion-content>
<div id="map_canvas" class="map"></div>
<button ion-button (click)="loadMap()"></button>
</ion-content>
home.ts
import {
GoogleMaps,
GoogleMap,
GoogleMapsEvent,
GoogleMapOptions,
CameraPosition,
MarkerOptions,
Marker
} from '#ionic-native/google-maps';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
map: GoogleMap;
constructor(public navCtrl: NavController,
public appService: AppService,
public apiService: ApiService,
public util: Util,
private geolocation: Geolocation,
private googleMaps: GoogleMaps
) {
}
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!');
// Now you can use all methods safely.
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');
});
});
});
}
As mentioned I installed the plugin with these 2 commands :
ionic plugin add cordova-plugin-googlemaps
npm install --save #ionic-native/google-maps
Of course I specified my Android and iOS API keys.
From the package.json, #ionic-native/google-maps version 4.3.3 and the cordova-plugin-googlemaps version is 2.1.1
When my page loads, I have my div which is blank. When I trigger the little button to load the map, I have a console log saying "Map is ready", no error, and my requests are present on the API console
There is not the shape of the map, there is no Google logo, there is just a blank screen, nothing loads.
Thank in advance for any help !
To add Ionic Native to your app, run following command to install the core package:
npm install #ionic-native/core --save
Keep in mind that many ionic Native Plugins only works with real device. It will not work if you run on web.
You can check this up for more information about using google map with ionic 2.

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

NavController's push doesn't show Google Maps

I am trying to draw a map when a button is clicked. However, it doesn't seem to work when I use NavController.push(), but only with NavController.setRoot(). I don't get any errors, so I can't figure out what causes this.
This is the class that draws the map:
declare var google: any;
#Component({
selector: 'page-Map',
templateUrl: 'Map.html'
})
export class MapPage {
public directionsService: any;
public directionsDisplay: any;
public directions: any;
map: any;
markers = [];
constructor(private _theme: ThemeService, private shareService: ShareService, public ajaxService: AjaxService) {
let rendererOptions = { draggable: true };
this.directionsService = new google.maps.DirectionsService;
let googleDiplay = new google.maps.DirectionsRenderer(rendererOptions);
this.directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
this.initMap();
}
//initialises the map
initMap() {
var point = { lat: 12.65, lng: 12.5683 };
let divMap = (<HTMLInputElement>document.getElementById('map'));
this.map = new google.maps.Map(divMap, {
center: point,
zoom: 15,
disableDefaultUI: true,
draggable: true,
zoomControl: true,
});
let locationOptions = { timeout: 30000, enableHighAccuracy: true, maximumAge: 0 };
navigator.geolocation.getCurrentPosition((position) => {
this.map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
}, (error) => { }, locationOptions);
//create marker and set to initialised map
var myLatLng = this.map.getCenter();
this.directionsDisplay.setMap(this.map);
}
}
This is the HTML:
<ion-header>
<ion-navbar>
<ion-title>Location</ion-title>
</ion-navbar>
</div>
</ion-header>
<ion-content>
<div id="map"></div>
</ion-content>
Try initializing the map after a platform.ready()
import { Platform } from 'ionic-angular';
constructor(public platform: Platform){
// ...ALL YOUR CODE...
platform.ready().then(() => {
this.initMap();
});
}
And be sure your map has the size it needs via css
#map {
width: 100%;
height: 100%; // 'auto' might work too
}
I have fixed the problem. The reason why it didn't work was that the id='map' was already in use, so I changed the id to id=map3 in the Map.html. So now my HTML file looks like this:
enter code here
I also changed
let divMap = (<HTMLInputElement>document.getElementById('map'));
to
let divMap = (<HTMLInputElement>document.getElementById('map3'));
and the CSS:
#map3 {
height: 100%;
}
and the HTML:
<ion-header>
<ion-navbar>
<ion-title>Location</ion-title>
</ion-navbar>
</div>
</ion-header>
<ion-content>
<div id="map3"></div>
</ion-content>

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.