2017-03-13 42 views
0

我想在我的本地Ionic 2应用程序的地图上放置多个标记。Ionic 2 Angular 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

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

回答

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); 
}); 

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

我还没有测试过这个确切的代码,但真正类似的东西,它的工作原理。

作为奖励,我已经添加了这些指令:

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

所以,一旦你添加的所有标记,地图会自动调整以适应他们所有;-)。