I am getting two results when I run the below code. Note how the Lat/Long are different.
- Why am I getting two different results?
- Why are both results actually wrong? I live 3km away from 28 Dean Ave, Barrie, ON L4N 0C4, Canada.
Thank you.
window.getGeolocationAndAddress = function () {
const apiKey = 'MY GoogleMaps API Key';
return new Promise((resolve, reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(async (position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
// Try to get address
const geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${apiKey}`;
try {
const response = await fetch(geocodeUrl);
const data = await response.json();
const address = (data.status === "OK" && data.results.length > 0)
? data.results[0].formatted_address
: null;
resolve({
latitude,
longitude,
address
});
} catch (error) {
// If address lookup fails, still return coordinates
resolve({
latitude,
longitude,
address: null
});
}
}, (error) => {
reject(error.message);
});
} else {
reject('Geolocation is not supported by this browser.');
}
});
};