Ionic 2 Angular 2 Google Maps从数据库坐标添加多个标记

时间:2017-03-13 15:12:30

标签: angularjs google-maps typescript ionic-framework

我正在尝试在我的原生Ionic 2应用程序中将多个标记放在地图上。

    //Connecting to locations database
    this.db.connect();
    let locations = this.db.collection('locations');

    //Retrieving all the locations of users from database
    locations.fetch().subscribe(msg => console.log(msg));

    //loop through all the locations, adding markers at each position
    for (let i = 0; i < 10; i++) {

        let pin = locations[i];
        let location: any;

        let marker = new google.maps.Marker({
                map: this.map,
                animation: google.maps.Animation.DROP,
                position : {"lat": 2433, "lng": 234}
        });

        //Content displayed in window on Map
        let content = 
        //User profile information
        '<h3>Name: </h3>' + this.user.details.name + 
        '<h3>Email: </h3>' + this.user.details.email + 
        '<h3>Image: </h3>' + '<img src='+this.user.details.image+'>' +
        '<button id="sendRequest()" (click)>Request Walk</button>';

        this.addInfoWindow(marker, content);
    }
    //end of locations loop

目前长和纬线的数字是坐标。我有一个包含用户电子邮件,lat和lng数据的位置数据库。我在控制台日志中有这些数据: console log displaying locations array

我想知道如何访问这些数据并使用它在我的地图上绘制多个不同的标记。

1 个答案:

答案 0 :(得分:2)

假设msg变量是您在粘贴图片中转储的变量,您应该在获取所有记录后循环遍历记录,例如:

locations.fetch().subscribe(msg:Array => {
  var bounds = new google.maps.LatLngBounds();

  for (let record of msg) {    
    var marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: { lat: record.lat, lng: record.long }
      __infowindow: new google.maps.InfoWindow({
        content: '<h3>Email: </h3>' + record.email;
      })
    });

    marker.addListener('click', ()=>{
      // this- here -is the marker
      // this.map means marker.map, we are lucky it's the same as ...Page.map
      this.__infowindow.open(this.map, this);
    });
    bounds.extend(marker.getPosition());
  }
  this.map.fitBounds(bounds);
});

棘手的部分是传递给Marker构造函数的对象的__infowindow字段。这是避免JS错误的一种解决方法 - 即如果我们使用let infowindow =...,变量将在for循环之后被销毁;如果我们使用var infowindow = ...,则会将其设置为for循环中创建的 last infowindow。

我没有测试过这个确切的代码,但有些东西非常相似,而且很有效。

作为奖励,我已添加以下说明:

var bounds = new google.maps.LatLngBounds();
...
bounds.extend(marker.getPosition());
...
this.map.fitBounds(bounds);

这样,一旦你添加了所有标记,地图就会自动调整以适应所有标记; - )。