Reputation: 1834
I am building up an Ionic 2 app using Google Maps SDK.
I want a user to be able to add markers on the map.
My code which adds markers by button click looks like this:
addMarker(){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: this.map.getCenter()
});
let content = "<h4>Information!</h4>";
this.addInfoWindow(marker, content);
}
position: this.map.getCenter() makes the Pin always added in the centre of the map.
The following function should return latitude / longitude of the clicked place on the map:
addNewPlace(){
let newPlace = new google.maps.event.addListener(this.map, 'click', (event) => latLng);
}
and I want the result from above (latLng) to be inserted into the addMarker function:
addMarker(){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: newPlace
});
let content = "<h4>Information!</h4>";
this.addInfoWindow(marker, content);
}
How can I do that? For now browser simply ignores my addNewPlace function (nothing happens, no errors in console).
Upvotes: 0
Views: 72
Reputation: 32178
You can add a click listener for map in your initialization function where you create a map. There is no need to create addNewPlace() function. Please also note that there is no constructor for google.maps.event.addListener(). No need for new operator.
https://developers.google.com/maps/documentation/javascript/reference#event
Callback function for click event returns an MouseEvent object
https://developers.google.com/maps/documentation/javascript/reference#MouseEvent
So you can create a function
addMarker(newPlace) {
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: newPlace
});
let content = "<h4>Information!</h4>";
this.addInfoWindow(marker, content);
}
In your initialization function after map creation add
google.maps.event.addListener(this.map, 'click', (event) => {
addMarker(event.latLng);
});
Upvotes: 2