If you are using agm-map then its quite easy to fetch address using lattitude and longitude.
Below function will work to get city name from lat lng.
if you are getting error like google not defined or its not able to find google map then install below dependency.
Below function will work to get city name from lat lng.
public latLngToCityName(latitude, longitude) { let _this = this; const cityDetails = { city: '', lat: latitude, lng: longitude }; this.geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(latitude, longitude); this.geocoder.geocode({ 'latLng': latlng }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { //formatted address for (var i = 0; i < results[0].address_components.length; i++) { for (var b = 0; b < results[0].address_components[i].types.length; b++) { //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate if (results[0].address_components[i].types[b] == "administrative_area_level_1") { //this is the object you are looking for let city = results[0].address_components[i]; cityDetails.city = city.long_name; _this.cityDetails = cityDetails; } } } } else { cityDetails.city = ''; } } else { cityDetails.city = ''; console.log('Failed'); } }); }
if you are getting error like google not defined or its not able to find google map then install below dependency.
npm i @types/googlemaps
No comments:
Post a Comment