将多个自定义标记与Ionic 2 + Google Maps集成

时间:2017-01-21 20:23:26

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

我已经在网上搜索了好几个小时,似乎无法找到问题,这看起来非常简单。

简单地说,icon google.maps.Marker属性似乎在我ionic serve应用时无所作为,尽管其他一切都很好。

换句话说,Ionic 2与Google Maps Javascript API一起使用什么,允许它定义自定义标记的图标图像?

我会在这里提供我所有的相关代码,但我觉得这对这样的问题可能没什么帮助。 根据我对Ionic 2的了解,我已经能够将谷歌地图,它的在线/离线状态以及一些默认标记集成到我的应用程序的页面中。

顺便说一句,我的测试图像文件与google-maps.ts位于同一个文件夹中(我现在只是这样做,因为我知道发生了什么)。

初始化谷歌地图和创建addMarker功能的所有代码都位于这一个文件中(这里放置了一大段代码以防万一,跳过下面的代码到下一个片段,看看它最相关的部分):

的src /提供商/谷歌maps.ts

 import { Injectable } from '@angular/core';
import { Connectivity } from './connectivity';
import { Geolocation } from 'ionic-native';

/*
  Generated class for the GoogleMaps provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/

declare var google;

@Injectable()

export class GoogleMaps {

mapElement: any;
pleaseConnect: any;
map: any;
mapInitialised: boolean = false;
mapLoaded: any;
mapLoadedObserver: any;
markers: any = [];
apiKey: string;
styles: any;

  constructor(public connectivityService: Connectivity) {

  }

  init(mapElement: any, pleaseConnect: any): Promise<any> {

    this.mapElement = mapElement;
    this.pleaseConnect = pleaseConnect;

    return this.loadGoogleMaps();
  }

  loadGoogleMaps(): Promise<any> {

      return new Promise((resolve) => {

        if(typeof google == "undefined" || typeof google.maps == "undefined") {

          console.log("Google maps Javascript needs to be loaded");
          this.disableMap();

          if(this.connectivityService.isOnline()) {

            window['mapInit'] = () => {

              this.initMap().then(() => {
                resolve(true);
              });

              this.enableMap();
            }

            let script = document.createElement("script");
            script.id = "googleMaps";

            if(this.apiKey) {
              script.src = 'http://maps.google.com/maps/api/js?key=' + this.apiKey 
                + '&callback=mapInit';
            } else {
              script.src = 'http://maps.google.com/maps/api/js?callback=mapInit';
            }

            document.body.appendChild(script);
          }
        }
        else {
          if(this.connectivityService.isOnline()) {
            this.initMap();
            this.enableMap();
          } else {
            this.disableMap();
          }
        }

        this.addConnectivityListeners();
      })
  }

  initMap(): Promise<any> {

    this.mapInitialised = true;

    return new Promise((resolve) => {

      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,    -Doesn't seem necessary anymore
          styles: [
  {
    "featureType": "poi.business",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "road",
    "elementType": "labels.icon",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "transit",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  }
]
        }

        this.map = new google.maps.Map(this.mapElement, mapOptions);
        resolve(true);
      });
    });
  }

  disableMap(): void {

    if(this.pleaseConnect) {
      this.pleaseConnect.style.display = "block";
    }

  }

  enableMap(): void {

    if(this.pleaseConnect) {
      this.pleaseConnect.style.display = "none";
    }
  }

  addConnectivityListeners(): void {

    document.addEventListener('online', () => {

      console.log("online");

      setTimeout(() => {

        if(typeof google == "undefined" || typeof google.maps == "undefined") {
          this.loadGoogleMaps();
        }
        else {
          if(!this.mapInitialised) {
            this.initMap();
          }

          this.enableMap();
        }

      },2000);
    }, false);
  }

//Setting up custom Google Maps markers

//iconBase: any = 'https://maps.google.com/mapfiles/kml/shapes/'; -Probably not necessary


icons: any = {
  partner: {
    icon: 'partner.png'
  },
  boughtFrom: {
    icon: 'boughtFrom.png'
  }
}

  addMarker(lat: number, lng: number, feature: any): void {

    let latLng = new google.maps.LatLng(lat, lng);

    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: latLng,
      icon: this.icons[feature].icon
    });

    this.markers.push(marker);

  }

}

不适合我的部分是&#34; icon&#34;最后一次分配&#34; addMarker()&#34;功能:

  addMarker(lat: number, lng: number, feature: any): void {

    let latLng = new google.maps.LatLng(lat, lng);

    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: latLng,
      icon: this.icons[feature].icon    //Doesn't do anything
    });

    this.markers.push(marker);

  }

目前,我尝试为不同的地点调用不同类型的标记,但即使我只是将其替换为partners.png{ url: 'partners.img' },它仍然无法识别任何内容

如果这很重要,这些也是我在地图上以默认样式显示的两个测试标记:

的src /资产/数据/ locations.json

{
    "locations": [

        {
            "latitude": 40.79567309999999,
            "longitude": -73.97358559999998,
            "type": "partner"
        },
        {
            "latitude": 40.8107211,
            "longitude": -73.95413259999998,
            "type": "boughtFrom"
        }
    ]
}

我还会包含整合所有这些信息的地图页面:

的src /页/ home.ts

import { Component, ElementRef, ViewChild } from '@angular/core';
import { Locations } from '../../providers/locations';
import { GoogleMaps } from '../../providers/google-maps';
import { NavController, Platform } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

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

  constructor(public navCtrl: NavController, public maps: GoogleMaps, 
              public Platform: Platform, public locations: Locations) {

  }

  ionViewDidLoad() {

    this.Platform.ready().then(() => {

      let mapLoaded = this.maps.init(this.mapElement.nativeElement, this.pleaseConnect.nativeElement);
      let locationsLoaded = this.locations.load();

      Promise.all([
        mapLoaded,
        locationsLoaded
      ]).then((result) => {

        let locations = result[1];

        for(let location of locations) {
          this.maps.addMarker(location.latitude, location.longitude, location.type);
        }
      })
  });
  }

}

感谢您的时间!

感谢任何和所有帮助。

1 个答案:

答案 0 :(得分:0)

  

换句话说,Ionic 2与Google Maps Javascript API一起使用什么,允许它定义自定义标记的图标图像?

无。 Ionic对此无任何责任。

  

顺便说一句,我的测试图像文件与google-maps.ts位于同一个文件夹中(现在正好这样做,因为我弄清楚发生了什么)。

这就是问题所在。构建过程从一个地方获取打字稿文件并将它们编译成一个文件。在构建www / build / main.js。

这些图像与main.js不同 将图像移动到资源文件夹并提供正确的路径。

例如:

  icon: 'assets/icon1.png'