谷歌地图上的多个标记与离子3

时间:2017-07-27 15:05:38

标签: angular google-maps ionic-framework ionic3

我试图在简单的谷歌地图上获得几个标记。我正在使用使用Angular 4的Ionic 3.

我正在加载地图:

import { Component, ViewChild, ElementRef } from '@angular/core';
import { GoogleMaps } from '@ionic-native/google-maps';

declare var google;

export class SearchResultsPage extends BasePage {

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

constructor(public navCtrl: NavController, 
            public navParams: NavParams, 
            private translateService: TranslateService,
            private googleMaps: GoogleMaps) {}


  ionViewDidLoad() {
   setTimeout(()=>{
      this.loadMap();
   }, 1000)
  }

  loadMap() {
    let latLng = new google.maps.LatLng(48.8509695, 2.3861870000000636);
    let latLng2 = new google.maps.LatLng(48.8504541, 2.3865487000000485);

    let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

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

    var marker = new google.maps.Marker({    
        position: latLng,
        map: this.map,
        title: 'Hello World!'
    },{
        position: latLng2,
        map: this.map,
        title: 'Check the World!'
    });
}

我发现了这个(但是没有用)

addMarkers(data, callback) {
    var markers = [{
        'position': {
            lat: 48.8513735,
            lng: 2.3861292
        },
        'icon': '#ff0000'
        }];
    function onMarkerAdded(marker) {
        console.log(marker);
        markers.push(marker);

        if (markers.length === data.length) {
            callback(markers);
        } else {
            console.log('in the else');
        }
    }

    data.forEach(function(markerOptions) {
        console.log('in foreach');
        this.map.addMarker(markerOptions, onMarkerAdded);
    });
}

地图正在显示,但我没有成功添加标记 我试图遵循官方文档(v1和v2),但它不起作用。如果有人有想法,谢谢你提前。我看到很多人试图做同样的事情,但每个代码都是不同的......

1 个答案:

答案 0 :(得分:5)

loadMap() {
let latLng = new google.maps.LatLng(48.8513735, 2.3861292);

let mapOptions = {
  center: latLng,
  zoom: 15,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}

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

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}
}