在Ionic Application中将标记添加到谷歌地图

时间:2018-02-11 08:40:51

标签: angularjs typescript ionic-framework google-maps-api-3

我一直在关注这个有用的教程 - https://www.joshmorony.com/ionic-2-how-to-use-google-maps-geolocation-video-tutorial/

一切都很好。但是,此示例提示用户通过单击按钮将标记添加到谷歌地图。我希望在视图中加载地图后自动添加标记。

但是,我收到错误cannot read propery of getCentre of undefined 我非常确定这是在告诉我它正在尝试在加载地图之前添加标记。下面是我的页面TypeScript文件中的代码:

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as $ from "jquery";
import Shuffle from 'shufflejs';
import { Geolocation } from '@ionic-native/geolocation';

declare var google;

@Component({
  selector: 'page-locator',
  templateUrl: 'locator.html'
})
export class LocatorPage {

  @ViewChild('map') mapElement: ElementRef;
  map: any;

  constructor(public navCtrl: NavController, public geolocation: Geolocation) {
  }

  ionViewDidLoad() {
    // Load the google map
    this.loadMap();
  }

  // Function to add marker at current location
  addMarker(){

    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: this.map.getCenter()
    });

    let content = "<h4>Information!</h4>";

    this.addInfoWindow(marker, content);

  }

  addInfoWindow(marker, content){

    let infoWindow = new google.maps.InfoWindow({
      content: content
    });

    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.open(this.map, marker);
    });
  }

  // Function for loading the google map and getting geolocation coords
  loadMap(){

    this.geolocation.getCurrentPosition().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(this.mapElement.nativeElement, mapOptions);

    }, (err) => {
      console.log(err);
    });
    //automatically place marker at current location
    this.addMarker();    
  }
}

有人有解决方案吗?就像地图完成加载后触发的触发器一样?我似乎找不到可以运行钩子的离子生命周期事件。请注意,我在this.addMarker()完成后尝试运行loadMap()功能

1 个答案:

答案 0 :(得分:1)

this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

下面调用添加标记

喜欢

this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
this.addMarker(); 

或者您可以将map作为参数传递给map函数

this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
this.addMarker(this.map);

和您的addMarker功能

addMarker(map:any){

let marker = new google.maps.Marker({
  map: map,
  animation: google.maps.Animation.DROP,
  position: map.getCenter()
});

let content = "<h4>Information!</h4>";

this.addInfoWindow(marker, content);



}