Using GoogleMaps API in JavaScript, I am trying to get the name (and the location) of city clicked on my map.
Firstly, I though I could use the PointOfInterest Event
feature as explained in this example, however cities do not seem to provide the placeId
required.
Secondly, I tried to use the reverse geocoding mechanism described here to get the complete address of the location, and from here, extract the name of the city (locality):
this.map.addListener('click', (event) => {
this.geocoder.geocode({
location: event.latLng,
}, (results, status) => {
if(status === 'OK')
{
if(results && results.length)
{
const addressResult = results[0];
if(addressResult.address_components)
{
addressResult.address_components.forEach((component) => {
if(component.types.includes('locality'))
{
console.log(component.long_name);
}
});
}
}
}
});
});
This method gave me pretty good results however it also showed some issues:
Despite setting the map locale to
en
, I am still getting the name of the city as it appears in the address returned by the geocoder. For example, I got Genève (french name of Geneva) instead of Geneva, I got Munchen (german name of Munich) instead of MunichClicking on a city, I sometime get another city if the location clicked belong to another locality.
Any advise to get the name of the city clicked would be much appreciated.