how to retrieve coordinates of a Place by query string | google-maps angular

99 Views Asked by At

In my Angular 15 application I have imported @angular/google-maps version 15.2.9.

I have a custom typeahead and I managed to use Places API to retrieve suggestions with the following code:
map.service

if (!input) return of({ predictions: [] });
const AutocompleteService = new google.maps.places.AutocompleteService();
const req: AutocompletionRequest = {
    input,
};
return from(AutocompleteService.getPlacePredictions(req));

My typeahead emits an event when the user click on a suggestion, and I want to get the position of the selected suggestion.
I tried the following:
map.service

const req: FindPlaceFromQueryRequest = {
    fields: ['geometry'],
    query,
};
const place = new google.maps.places.PlacesService(this.map).findPlaceFromQuery(req);

Map is always undefined so I don't get any results. I'm setting map with this code:
map.component

<google-map #map (mapInitialized)="onMapInitialized($event)"></google-map>
@ViewChild('map', { static: false }) private map!: GoogleMap;
onMapInitialized(event: unknown) {
    this.map = event as GoogleMap;
    if (this.map.googleMap) this.mapService.map = this.map.googleMap
}

I don't know if findPlaceFromQuery is the right function, my ultimate goal is to center the map to the new coordinates.
I also would prefer avoid using a function that requires Map, so I don't have to export it from the component. I just need a way to get coordinates of a Place based on a query: string input

UPDATE
I noticed the problem is that the package initializes the map.googleMap object asynchronously, so it is not directly available at the execution of onMapInitialized.
I still don't know how to access when it is initialized.

1

There are 1 best solutions below

1
Joe - Check out my books On

Obtaining the map within onMapInitialized is one thing and I suppose others can help you out with that.

I'd only point out that you actually don't need the a Google map instance to use the Places Service!

Extracted from my handbook:

The new google.maps.places.PlacesService constructor requires you to provide a HTMLDivElement or a google.maps.Map instance. While including the map container is often advantageous, you can pass in an arbitrary (and even a hidden) HTML element — provided that you render the attributions elsewhere programmatically.

The only remaining thing to do is make sure that req — the argument you pass onto findPlaceFromQuery — conforms to the FindPlaceFromQueryRequest interface.