I have a simple question that I can't seem to get around by. I am using Google Maps javascript to show specific locations this all works well when the user accepts Geolocation services. To test Google Maps considerIp is working, allowing google maps to use the public IP address also works fine. However, when I try to do the below, the showLocationBasedOnIP() method is not even being called.
function initMap(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
showLocationsBasedOnIP();
}
}
I have tested the showLocationsBasedOnIP independently by removing the geolocation checker, but when I try to integrate it as shown above, the method is not even being triggered.
What I want to achieve is that when the user denies geolocation, my showLocationsBasedOnIP() method should be triggered, in which I have a message to display on the browser that public IP address is being used and that location services will not be accurate unless the user turns on geolocation.
Is there something am missing?
You need to set your showLocationsBasedOnIP
function as the error callback function for getCurrentPosition()
. Like this:
<!DOCTYPE html>
<html>
<body>
<button onclick="getLocation()">Try It</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showLocationsBasedOnIP);
} else {
showLocationsBasedOnIP();
}
}
function showPosition(position) {
console.log("showing position: ", position.coords.latitude, position.coords.longitude);
}
function showLocationsBasedOnIP() {
console.log("showing location based on IP");
}
</script>
</body>
</html>
Now your function will execute in both cases; when the user doesn't allow location permissions and when the user's browser doesn't support geolocation.