Reputation: 11
I am trying to place multiple markers on a map in my native Ionic 2 app.
//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
At the moment the long and lat figures are made up coordinates. I have a locations database containing user email, lat and lng data. I have this data in my console log:
I am wondering how I can access this data and use it to plot multiple different markers on my map.
Upvotes: 1
Views: 1526
Reputation: 10253
Assuming that the msg
variable is the one you dumped in the pasted picture, you should loop over the records once you get them all, that is, for instance:
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);
});
The tricky part is the __infowindow
field of the object passed to the Marker constructor. It's a workaround to avoid JS errors - i.e. if we used let infowindow =...
, the variable would be destroyed after the for loop; if we used a var infowindow = ...
, it would be set to the last infowindow created in the for loop.
I haven't tested this exact code, but something really similar, and it works.
As a bonus, I've added these instructions:
var bounds = new google.maps.LatLngBounds();
...
bounds.extend(marker.getPosition());
...
this.map.fitBounds(bounds);
so that once you added all the markers, the map will autoresize to fit them all ;-).
Upvotes: 2