角形Google地图无法在Firefox中运行,但可以在Chrome浏览器中完美运行

时间:2018-07-29 07:58:29

标签: angular google-maps firefox

我已将google map添加到我的项目中,并且在chrome中工作正常。但谈到Firefox浏览器时,GoogleMapsLoader无法到达并显示灰色区域。但是在chrome中,googlemaploader功能可以完美实现,并且地图上的所有其他功能也可以正常工作。

home.component.ts

import { Component, OnInit, ElementRef,NgZone, ViewChild } from '@angular/core';
import { HomeService } from './home.service';
import { Consultant } from './consultant';
import { Router } from '@angular/router';
import { AlertService } from '../../_services';
import * as GoogleMapsLoader from 'google-maps';
import { MapsAPILoader } from '@agm/core';
import {} from '@types/googlemaps';

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  location;
  key;
  public consultantList: any;
  public branchList: any;
  public locationslist: any;
  public map:any;
  public contentinfo:any;
  public markersArray = [];
  public branch = [];
  // lat = 6.9271;
  // lng = 79.8612
  lat;
  lng;

  @ViewChild('search') public searchElement: ElementRef;

  constructor(private homeServise: HomeService, private router: Router, private alertService: AlertService, private _elementRef:ElementRef, private _ngZone: NgZone, private mapsAPILoader: MapsAPILoader) { }

  ngOnInit() {
    if (navigator.geolocation) {

      this.mapsAPILoader.load().then(
        () => {
         let autocomplete = new google.maps.places.Autocomplete(this.searchElement.nativeElement, { types:["address"] });

          autocomplete.addListener("place_changed", () => {
          this._ngZone.run(() => {
           let place: google.maps.places.PlaceResult = autocomplete.getPlace();
           if(place.geometry === undefined || place.geometry === null ){
            return;
           }
          });
          });
        }
           );

      window["angularComponentRef"] = { component: this, zone: this._ngZone };

      navigator.geolocation.getCurrentPosition(position => {
        // console.log(position.coords.longitude); 
        console.log("Long " + this.precisionRound(position.coords.longitude, 1));
        console.log("Lat " + this.precisionRound(position.coords.latitude, 1));

        this.lng = this.precisionRound(position.coords.longitude, 1);
        this.lat = this.precisionRound(position.coords.latitude, 1);


        let el = this._elementRef.nativeElement.querySelector('.google-maps');

            GoogleMapsLoader.load((google) => {
               this.map = new google.maps.Map(el, {
                center: new google.maps.LatLng(this.lat, this.lng),
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
                
              });
            });
      });
    }
  }

  precisionRound(numb, precision): any {
    const factor = Math.pow(10000, precision);
    return Math.round(numb * factor) / factor;
  }

  dataSubmit(): void {
    this.clearMarkers();
    this.alertService.clear();
    console.log(this.location + " - " + this.key);

    if ((this.key === ``) || (this.key === undefined)) {
      this.alertService.error("Please enter a Keyword to search", true);
    } else {

      if ((this.location === ``) || (this.location === undefined)) {

        this.homeServise.searchConsultantFromCurrentLocation(this.lat, this.lng, this.key).subscribe(
          (data) => {
            console.log(data.response);
            this.consultantList = data.response; 
            this.loadingMap(this.consultantList); 
        },
          err => {
            this.alertService.warn("Given keyword is not found", true);
            this.consultantList = null;
          },
        );

      } else {

        this.homeServise.searchBranch(this.location, this.key).subscribe(
          (data) => {
            console.log(data.response);
            this.branchList = data.response;
            
            this.loadingMap(this.branchList); 
          },
          err => {
            this.alertService.warn("Given keyword is not found", true);
            this.branchList = null;
          },
        );

      }

    }

  }

  onClicker():any {
    //console.log("Ishfaaq rocks");
    localStorage.setItem('branchId', '1');
    localStorage.setItem('consultantId', '1');
    localStorage.setItem('consultantFirstName', 'Chathura');
    localStorage.setItem('consultantLastName', 'Jayasekara');
    this.router.navigate(['/pages/appointment'])
  }

  loadingMap(branchList):any{
   branchList = this.branchList;
    //let el = this._elementRef.nativeElement.querySelector('.google-maps');
  
    // TODO: do not load this each time as we already have the library after first attempt
    GoogleMapsLoader.load((google) => {
       
      this.map.setCenter({lat: this.branchList[0].lat, lng: this.branchList[0].lng});
      
      var infowindow = new google.maps.InfoWindow({});
    
      var marker, i;
      
      for (i = 0; i < this.branchList.length; i++) {
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(this.branchList[i].lat, this.branchList[i].lng),
          map: this.map
        });
    
        let infoContent: string = '<div class="button-wrapper" align="center"> <button class="btn btn-primary" onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.onClicker();})">Book Now</button> </div>';
        
        this.markersArray.push(marker);
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
          return function () {
            //branchList = this.branchList;
            infowindow.setContent('<h4 class="header4" align="center"> '+ branchList[i].name + '</h4>' +'<H6 class="header4" align="center"> '+ branchList[i].addressLine1 + '</H6>'+'<H6 class="header4" align="center"> '+ branchList[i].addressLine2 + '</H6>'+'<H6 class="header4" align="center"> '+ branchList[i].city + '</H6>' +'<br/>'+ infoContent);
            infowindow.open(this.map, marker);
          }
        })(marker, i));
      }
      
    });

  }

  clearMarkers():any{
    for (var i = 0; i < this.markersArray.length; i++ ) {
      this.markersArray[i].setMap(null);
    }
    this.markersArray.length = 0;
  }

  

}

home.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { HomeRoutingModule } from './home-routing.module';
import { HomeComponent } from './home.component';
import { HomeService } from './home.service';
import { AppTranslationModule } from '../../app.translation.module';
import { AlertModule } from '../../_directives/alert.module';
import { AlertService } from '../../_services';
import { AgmCoreModule } from '@agm/core';


@NgModule({
  imports: [
    CommonModule,
    HomeRoutingModule,
    AppTranslationModule,
    AlertModule,
    AgmCoreModule.forRoot({
      apiKey: 'AIzaSyAjZ_vpVPbhqTU5ih6DPrKbQPS-evfpW6w',
      libraries: ["places"]
})
   
  ],
  declarations: [HomeComponent],
  providers: [HomeService],

})
export class HomeModule { }

home.component.html

<!--<div class="row"> -->
<!--<div class="auth-block">-->

  <form class="form-horizontal">
    <div class="form-group row">
  
      <label for="inputmobile3" class="col-sm-2 control-label">Location</label>
  
      <div class="col-sm-10">
        <input type="text" class="form-control" [(ngModel)]="location" name="location" autocorrect="off" autocapitalize="off" spellcheck="off" #search>
      </div>
  
      <label for="inputmobile3" class="col-sm-2 control-label">Service</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" [(ngModel)]="key" name="key">
      </div>
  
      <div class="offset-sm-2 col-sm-10">
        <!--<button [disabled]="!form.valid" type="submit" class="btn btn-default btn-auth" translate>Search</button> -->
        <button class="btn btn-default btn-auth" (click)="dataSubmit()">Search</button>
  
      </div>
  
    </div>
  </form>
  
  <!--</div>-->

  <alert></alert>
    <ba-card cardTitle="">
      <div class="google-maps"></div>
    </ba-card>  

我通过在mapsAPILoader而不是googleMapLoader内调用地图解决了问题。它对我来说很好。您可以在下面看到我所做的更改供您参考

import { Component, OnInit, ElementRef,NgZone, ViewChild, AfterViewInit } from '@angular/core';
import { HomeService } from './home.service';
import { Consultant } from './consultant';
import { Router } from '@angular/router';
import { AlertService } from '../../_services';
import * as GoogleMapsLoader from 'google-maps';
import { MapsAPILoader } from '@agm/core';
import {} from '@types/googlemaps';
@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit, AfterViewInit{

  location;
  key;
  public consultantList: any;
  public branchList: any;
  public locationslist: any;
  public map:any;
  public contentinfo:any;
  public markersArray = [];
  public branch = [];
  // lat = 6.9271;
  // lng = 79.8612
  lat;
  lng;

  @ViewChild('search') public searchElement: ElementRef;

  constructor(private homeServise: HomeService, private router: Router, private alertService: AlertService, private _elementRef:ElementRef, private _ngZone: NgZone, private mapsAPILoader: MapsAPILoader) { }

  ngOnInit() {
    if (navigator.geolocation) {

      this.mapsAPILoader.load().then(() => {
         let autocomplete = new google.maps.places.Autocomplete(this.searchElement.nativeElement, { types:["address"] });

          autocomplete.addListener("place_changed", () => {
          this._ngZone.run(() => {
           let place: google.maps.places.PlaceResult = autocomplete.getPlace();
           if(place.geometry === undefined || place.geometry === null ){
            return;
           }
          });
          });
        }
           );

      window["angularComponentRef"] = { component: this, zone: this._ngZone };

      navigator.geolocation.getCurrentPosition(position => {
        // console.log(position.coords.longitude); 
        console.log("Long " + this.precisionRound(position.coords.longitude, 1));
        console.log("Lat " + this.precisionRound(position.coords.latitude, 1));

        this.lng = this.precisionRound(position.coords.longitude, 1);
        this.lat = this.precisionRound(position.coords.latitude, 1);

      });
    }
  }



  ngAfterViewInit(){

    
    this.mapsAPILoader.load().then(() => {

      let el = this._elementRef.nativeElement.querySelector('.google-maps');
      this.map = new google.maps.Map(el, {
        center: new google.maps.LatLng(6.9333, 79.8431),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        
      });

    });

  }

  precisionRound(numb, precision): any {
    const factor = Math.pow(10000, precision);
    return Math.round(numb * factor) / factor;
  }

  dataSubmit(): void {
    this.clearMarkers();
    this.alertService.clear();
    console.log(this.location + " - " + this.key, this.lat, this.lng);

    if ((this.key === ``) || (this.key === undefined)) {
      this.alertService.error("Please enter a Keyword to search", true);
    } else {  

      if ((this.location === ``) || (this.location === undefined)) {

        this.homeServise.searchbranchFromCurrentLocation(this.lat, this.lng, this.key).subscribe(
          (data) => {
            console.log(data.response);
            this.branchList = data.response; 
            this.loadingMap(this.branchList); 
        },
          err => {
            this.alertService.warn("Given keyword is not found", true);
            this.branchList = null;
          },
        );

      } else {

        this.homeServise.searchBranch(this.location, this.key).subscribe(
          (data) => {
            console.log(data.response);
            this.branchList = data.response;
            
            this.loadingMap(this.branchList); 
          },
          err => {
            this.alertService.warn("Given keyword is not found", true);
            this.branchList = null;
          },
        );

      }

    }

  }

  onClicker(branch):any {
    console.log('branchId', branch);
    localStorage.setItem('branchId', branch);
    //localStorage.setItem('branchId', '1');
    // localStorage.setItem('consultantId', '1');
    // localStorage.setItem('consultantFirstName', 'Chathura');
    // localStorage.setItem('consultantLastName', 'Jayasekara');
    this.router.navigate(['/pages/appointment'])
  }

  loadingMap(branchList):any{
   branchList = this.branchList;
   
    //let el = this._elementRef.nativeElement.querySelector('.google-maps');
  
    // TODO: do not load this each time as we already have the library after first attempt
    this.mapsAPILoader.load().then(() => {
       
      this.map.setCenter({lat: this.branchList[0].lat, lng: this.branchList[0].lng});
      
      var infowindow = new google.maps.InfoWindow({});
    
      var marker, i;

      var icon = {
        //url: "../../../assets/images/marker.png", // url
        url:"assets/images/marker.png",
        scaledSize: new google.maps.Size(50, 50), // scaled size
        origin: new google.maps.Point(0,0), // origin
        anchor: new google.maps.Point(0, 0) // anchor
    };

      
      for (i = 0; i < this.branchList.length; i++) {
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(this.branchList[i].lat, this.branchList[i].lng),
          map: this.map,
          icon:icon
        });
    
        let infoContent: string = '<div class="button-wrapper" align="center"> <button class="btn btn-primary" onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.onClicker(\'' + branchList[i].id + '\');})">Book Now</button> </div>';
        
        this.markersArray.push(marker);
        google.maps.event.addListener(marker, 'click', (function(marker, i){
          return function ()  {
            //branchList = this.branchList;
            infowindow.setContent('<h4 class="header4" align="center"> '+ branchList[i].name + '</h4>' +'<H6 class="header4" align="center"> '+ branchList[i].addressLine1 + '</H6>'+'<H6 class="header4" align="center"> '+ branchList[i].addressLine2 + '</H6>'+'<H6 class="header4" align="center"> '+ branchList[i].city + '</H6>' +'<br/>'+ infoContent);
            infowindow.open(this.map, marker);
          }
        })(marker, i));
      }
      
    });

  }

  clearMarkers():any{
    for (var i = 0; i < this.markersArray.length; i++ ) {
      this.markersArray[i].setMap(null);
    }
    this.markersArray.length = 0;
  }

  

}

0 个答案:

没有答案