Right now, I have an event listener so a user can type in their location and it can grab their coordinates. My function looks like this for the selector:
searchBox.addListener('places_changed', () => {
const place = searchBox.getPlaces()[0]
if (place == null) return
const latitude = place.geometry.location.lat()
const longitude = place.geometry.location.lng()
/* MY WEATHER FETCH FUNCTION HERE */
}).then(res => res.json()).then(data => {
setWeatherData(data, place.formatted_address)
})
})
The weather data is then passed down, along with formatted address from google maps. But a div is set with the user's current location that they typed in.
function setWeatherData(data,place){
locationElement.textContent = place
statusElement.textContent = titleCase(data.weather[0].description)
}
What really matters in this code, is the locationElement.textContent = place part. It sets the locationElement to the "place" of which address they typed in using the formatted_address.
But, I want to be able to grab their current location using navigator.geolocation.getCurrentPosition(), if they grant the location permission. If they do grant it, it will then set the locationElement to whatever location it grabbed using the longitude and longitude it received from the geolocation javascript API.
Ideally, I'd like to run a function that:
If the user grants location permissions, autocomplete the searchBox with their coordinates and then that will trigger the event listener.
Right now I am using
navigator.geolocation.getCurrentPosition(grabLocation, onError, options);
The grabLocation function currently looks like
function grabLocation(pos) {
var crd = pos.coords;
/* My WEATHER FETCH FUNCTION HERE */
}).then(res => res.json()).then(data => {
setWeatherData(data,place)
})
}
But, unfortunately, I am not sure how to pass down "place" with searchBox.getPlaces()[0] as I was doing in the event listener as the geolocation javascript API only can get cords.
How can I achieve this?