Карты Google очень полезны для многих приложений, таких как

  • Приложение такси
  • Приложение для определения местоположения членов семьи
  • Бизнес-приложения (для отображения местоположения компании)
  • SOS-приложения
  • Приложения электронной коммерции

Есть несколько плагинов, доступных для интеграции Карт Google с проектом Ionic Angular, но у них меньше функций. С помощью Javascript API Карт Google вы сможете выполнять любые функции. Следуйте этому пошаговому руководству, чтобы добавить Карту Google в свой Ionic. приложение.

1) Установка

Импортируйте скрипт карты на страницу index.html. Здесь будет использоваться Javascript API Карт Google. Сначала вы должны получить ключ API Карт Google и заменить YOUR_API_KEY.

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

2) Настройка интерфейса карты

Создайте компонент HTML на странице карты, чтобы отобразить карту

MapPage.html

<div class="map-div" #gmap></div>

Объявить Карты Google на MapPage.ts.Viewchild, AfterViewInit и ElementRef также необходимо импортировать

MapPage.ts

  import { Component, OnInit, ViewChild, ElementRef,AfterViewInit } from '@angular/core';
  declare const google: any;

Используйте Viewchild и Elementref, чтобы выбрать HTML-элемент карты, который мы создали.

MapPage.ts

  export class MapPage {
      @ViewChild('gmap') gmap!: ElementRef;
      myMap:any; 
   }

Мы должны загрузить карту Google после загрузки всех основных компонентов angular.

MapPage.ts

  ngAfterViewInit() {
      this.loadMap()
     }
   
     public loadMap() {
       let mapOptions = {
         center: new google.maps.LatLng(37.7833, -122.4167), // Initial camera center of the map
         zoom: 12, //Camera zoom value
         mapTypeId: google.maps.MapTypeId.ROADMAP, //Select the Google Map Type 
         disableDefaultUI: true //Disabled the default layout which contains zoom in and out buttons
       }
   
       this.myMap = new google.maps.Map(this.gmap.nativeElement, mapOptions);//'gmap' is the html element 
   }

3) Добавить маркер

MapPage.ts

 //Adding a marker
   const marker = new google.maps.Marker({
      position: { lat: 35.7833, lng: -120.4167 }, //Latitude and longitude of the marker
      map: this.myMap 
    });

4) Полный код

MapPage.ts

  
      import { Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
      declare const google: any;


      @Component({
        selector: 'map-page',
        templateUrl: 'mapPage.page.html',
        styleUrls: ['mapPage.page.scss']
      })
      export class MapPage implements AfterViewInit{

        @ViewChild('gmap') gmap!: ElementRef;

        myMap: any;

        constructor() {
        }

        ngAfterViewInit() {
          this.loadMap()
        }

        public loadMap() {
          let mapOptions = {
            center: new google.maps.LatLng(37.7833, -122.4167), // Initial camera center of the map
            zoom: 12, //Camera zoom value
            mapTypeId: google.maps.MapTypeId.ROADMAP, //Select the Google Map Type 
            disableDefaultUI: true //Disabled the default layout which contains zoom in and out buttons
          }

          this.myMap = new google.maps.Map(this.gmap.nativeElement, mapOptions);//'gmap' is the html element 

          //Adding a marker
          const marker = new google.maps.Marker({
            position: { lat: 35.7833, lng: -120.4167 }, //Latitude and longitude of the marker
            map: this.myMap
          });
        }

      }

Да! Мы добавили карту Google с маркером. Я надеюсь, что это руководство помогло вам и не потратило ваше драгоценное время впустую.

Время — самое ценное для программиста.