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.
Related
I tried with ionic cordova run browser -l and maps loads just fine. it loads a white screen and no error is thrown in the console. Also, tried to build apk and white screen comes up on mobile device. how i can fix this issue. please help me.
src/app/package.json (directory)
"cordova": {
"plugins": {
"cordova-plugin-googlemaps": {
"API_KEY_FOR_ANDROID": "MY_API_KEY"
},
"cordova-plugin-whitelist": {},
"cordova-plugin-statusbar": {},
"cordova-plugin-device": {},
"cordova-plugin-splashscreen": {},
"cordova-plugin-ionic-webview": {},
"cordova-plugin-ionic-keyboard": {}
},
"platforms": [
"browser",
"android"
]
}
src/app/config.xml (directory)
<widget>
<preference name="GOOGLE_MAPS_ANDROID_API_KEY" value="MY_API_KEY" />
</widget>
src/app/home/home.page.hml (directory)
<ion-header>
<ion-toolbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<h3>google map</h3>
<div id="map_canvas">
<button ion-button (click)="onButtonClick($event)">Demo</button>
</div>
</ion-content>
src/app/home/home.page.ts (directory)
import {
ToastController,
Platform
} from '#ionic/angular';
import {
GoogleMaps,
GoogleMap,
GoogleMapsEvent,
Marker,
GoogleMapsAnimation,
MyLocation
} from '#ionic-native/google-maps';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit{
map: GoogleMap;
address:string;
constructor(public toastCtrl: ToastController,
private platform: Platform) {}
ngOnInit() {
// Since ngOnInit() is executed before `deviceready` event,
// you have to wait the event.
this.platform.ready();
}
onButtonClick()
{
this.loadMap();
}
loadMap() {
this.map = GoogleMaps.create('map_canvas', {
// camera: {
// target: {
// lat: 43.0741704,
// lng: -89.3809802
// },
// zoom: 18,
// tilt: 30
// }
});
this.goToMyLocation();
}
goToMyLocation(){
this.map.clear();
// Get the location of you
this.map.getMyLocation().then((location: MyLocation) => {
console.log(JSON.stringify(location, null ,2));
// Move the map camera to the location with animation
this.map.animateCamera({
target: location.latLng,
zoom: 17,
duration: 5000
});
//add a marker
let marker: Marker = this.map.addMarkerSync({
title: '#ionic-native/google-maps plugin!',
snippet: 'This plugin is awesome!',
position: location.latLng,
animation: GoogleMapsAnimation.BOUNCE
});
//show the infoWindow
marker.showInfoWindow();
//If clicked it, display the alert
marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => {
this.showToast('clicked!');
});
this.map.on(GoogleMapsEvent.MAP_READY).subscribe(
(data) => {
console.log("Click MAP",data);
}
);
})
.catch(err => {
//this.loading.dismiss();
this.showToast(err.error_message);
});
}
async showToast(message: string) {
let toast = await this.toastCtrl.create({
message: message,
duration: 2000,
position: 'middle'
});
toast.present();
}
}
Tip for next time, give links to the packages you're using to reduce the effort it takes people to help you.
It looks like you're using the Ionic Native google maps plugin.
Looking in their docs I can see some differences with your code:
https://github.com/ionic-team/ionic-native-google-maps/blob/master/documents/README.md
For example you are loading the map on a button click instead in the ionviewdidload event.
You're this.platform.ready() is not doing anything. It returns a promise so you could do something like ``this.platform.ready().then({ /* some code that waits for platform */ })` but the code you have just runs and goes straight onwards.
I'm wondering where you have got the code you've used so far? Is it some tutorial that you have followed? Please post the url if so - to compare if you've done anything wrong.
I'm seeing you defining API_KEY_FOR_ANDROID in your snippets above but that appears to be for an earlier release of the cordova plugin.
I suspect you have made a mess of things and would probably do better starting again with an up to date tutorial.
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);
});
}
}
Weird observation with the Ionic/Cordova Google Maps. I want to bring up the map with hybrid maps.
if(!this.map){
// const myMapType: MapType = 'HYBRID';
const mapOptions: GoogleMapOptions = {
// controls: {
// compass: false,
// myLocation: true,
// myLocationButton: false,
// mapToolbar: false,
// },
// mapType: myMapType
};
this.map = GoogleMaps.create('map_canvas', mapOptions);
this.map.setMapTypeId(GoogleMapsMapTypeId.HYBRID);
}
Fails running with Argument of type 'string' not assignable to parameter of type 'MapType'. When I disable that line, the app starts. However, a second edit to enable setMapTypeId with ionic livereload loads the map in hybrid. I do not get it. Am I not preloading something that's set in the initial load and then prevails in the simulator memory so that the second time the error is not triggered?
Running simulator with
ionic cordova run ios --consolelogs --target "iPhone-8"
Should work.
import { GoogleMaps, GoogleMap, GoogleMapsMapTypeId} from '#ionic-native/google-maps';
#IonicPage()
#Component({
selector: 'page-set-map-type-id',
templateUrl: 'set-map-type-id.html',
})
export class ExamplePage {
map: GoogleMap;
constructor() {}
ionViewDidLoad() {
this.loadMap();
}
loadMap() {
this.map = GoogleMaps.create('map_canvas', {
mapType: GoogleMapsMapTypeId.HYBRID
});
}
}
I have to add a view with Google maps map on my project. I followed the official ionic native Google maps documentation but it does not work.
I assigned background color pink to the div that contains the map (for testing), before adding the map to the div, the div shows correctly. But when the map is added to the div the background of the modal window turns to transparent, and the div disappears. But no error is shown.
I tried different ways to attach the map on the div, but the results are the same.
When I use the code of the Ionic docs I got this error message "GoogleMaps [deprecated] Please use GoogleMaps.create()". I tried using GoogleMaps.create() instead of the argument of the constructor avoiding this error message, but still not working.
My ion-content:
<ion-content fullscreen overflow-scroll="true" class="container">
<div #map id="map"></div>
</ion-content>
Part of the css:
#map {
height: 90%;
width: 100%;
border-width: 5px;
border-color: red;
background: pink;
}
And here we got fragments of the ts:
import {
GoogleMaps,
GoogleMap,
GoogleMapsEvent,
GoogleMapOptions,
CameraPosition,
MarkerOptions,
Marker
} from '#ionic-native/google-maps';
...
export class PerfilPage {
#ViewChild(Content) content: Content;
#ViewChild('map') mapElement: ElementRef;
map: GoogleMap;
...
ionViewDidLoad() {
// I use this for changing the nab-bar color
this.content.ionScroll.subscribe((scroll) => {
// console.log('user scrolled', scroll);
if ( scroll.scrollTop > 100 ) {
this.toolbar_color = "bg_search"
} else {
this.toolbar_color = "transparent"
}
this.ref.detectChanges();
});
// this.loadMap();
// this.initMap();
// this.testMap();
this.offiMap();
}
// Official Ionic documentation code
offiMap() {
let mapOptions: GoogleMapOptions = {
camera: {
target: {
lat: 43.0741904,
lng: -89.3809802
},
zoom: 18,
tilt: 30
}
};
this.map = this.googleMaps.create('map', 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');
});
});
});
}
}
PS: the API key works on other projects (not Ionic projects), so idk where is the problem.
Thanks :)
As I describe on the git repo, the maps plugin places the native map view under (or behind) the browser.
https://github.com/mapsplugin/cordova-plugin-googlemaps#how-does-this-plugin-work
That's why all parent elements of the map div becomes transparent.
If you need to set the background of application, you need to use Environment.setBackground("pink").
Since the map is displayed under the browser, this plugin CAN NOT display on dialogs.
loadMap() {
let element = document.getElementById('map');
let mapOptions: GoogleMapOptions = {
camera: {
target: {
lat: 43.0741904,
lng: -89.3809802
},
zoom: 18,
tilt: 30
}
};
let map: GoogleMap = this.googleMaps.create(element, mapOptions);
map.addMarker({
title: 'Location',
icon: 'blue',
animation: 'DROP',
position: {
lat: 43.0741904,
lng: -89.3809802
}
})
.then(marker => {
marker.on(GoogleMapsEvent.MARKER_CLICK)
.subscribe(() => {
//alert('clicked');
});
});
}
Try this
I had the exact issue as OP had when follow the Official Ionic Native Google Maps Guide
There's a misleading on the slide page Google Maps API Key. The URL in the slide is https://console.developers.google.com/projectselector/apis/library which is INCORRECT.
For generating Google Maps API Key for Android and IOS, we use Google Cloud Platforms https://cloud.google.com/maps-platform/
Here's the link I asked the same question Ionic3 ionic native google maps doesn't show map but only google logo (display grey blank map )
Hope it can help people who have the same issue.
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)
}