For those looking to implement this in React without the need for an additional script, here is the ES2015 code snippet tailored for React, eliminating the reliance on the HTML code provided above. Simply import the function. A big shoutout to the original post for inspiring this solution.
const showPosition = position =>{
let loc = `Latitude:${position.coords.latitude} logitude:
${position.coords.longitude}`
console.log(loc)
return loc
}
const getLocation = () => {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(showPosition);
}
return false
}
Now, you can easily import and utilize the function in your application.
If you are looking to retrieve the state and zip code, leveraging the Google API is a viable option. Below is the code snippet that fetches the geolocation data, sends it to Google, and provides you with the state and address details. Don't forget to enable the Google geolocation API.
//Docs - https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding
const getData = async (url) => {
let res = await fetch(url)
let json = await res.json()
console.log(json);
return json
}
const showPosition = async position =>{
let loc = `Latitude:${position.coords.latitude} logitude: ${position.coords.longitude}`
let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.coords.latitude},${position.coords.longitude}&key={GOOGLE_API_key}`
console.log(loc)
let address = await getData(url)
console.log(`results`,address)
return address
}
const getLocation = async () => {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(showPosition);
}
return false
}