2017-03-13 43 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); 

所以,一旦你添加的所有標記,地圖會自動調整以適應他們所有;-)。