mraz
mraz

Reputation: 205

Google Map not showing up Javascript Ionic 4

I've been trying to insert a Google Map on my Ionic 4 Webiste, but I've been unable to because the map is not showed up.

Here's my code below

  ionViewDidEnter(){
    console.log('creating map')
    // var latlng = new google.maps.LatLng(39.305, -76.617);
    this.map = new google.maps.Map(document.getElementById("map"), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 8
    });    
}

This is how I'm inserting it on the HTML file

<div id="map" class="map"></div>

Any hint or help will be greatly appreciated.

Upvotes: 0

Views: 179

Answers (1)

Rich Tillis
Rich Tillis

Reputation: 1571

Josh Morony has a great blog post that walks through how to build out a map component. Basically it goes something like this:

Install the types for Google maps

 npm install @types/googlemaps --save-dev

Initialize the map in your component

/// <reference types="@types/googlemaps" />
import { Component, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements AfterViewInit {

  constructor() {}

  async ngAfterViewInit() {
    const googleMaps = await getGoogleMaps("YOUR-API-KEY-HERE");
    this.initMap();
  }
  initMap() {
    const POSITION = {lat: -25.344, lng: 131.036};

    const map = new google.maps.Map(document.getElementById("map"), {
      zoom: 4,
      center: POSITION || { lat: 22, lng: 22 }
    });
  }
}

function getGoogleMaps(apiKey: string): Promise<any> {
  const win = window as any;
  const googleModule = win.google;
  if (googleModule && googleModule.maps) {
    return Promise.resolve(googleModule.maps);
  }

  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}`;
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);
    script.onload = () => {
      const googleModule2 = win.google;
      if (googleModule2 && googleModule2.maps) {
        resolve(googleModule2.maps);
      } else {
        reject("google maps not available");
      }
    };
  });
}

The first line /// <reference types="@types/googlemaps" /> of the component is to address a Typescript related issue (details here)

Lastly, make make sure your CSS is setup to render the map.

#map {
    width: 100%;
    height: 100%;
    display: contents;
}

Hope this helps.

Upvotes: 1

Related Questions