To get the user's current location use the getCurrentPosition() method. This method contains two parameters, first parameter is success for providing locationd and second one is error to handle errors for ex: getCurrentPosition(success,error)
<script>
/* Get current location*/
function getCurrentLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success,showError);
} else {
alert("Geolocation is not supported on your browser!");
}
function success(position) {
alert("Latitude: " + position.coords.latitude +" Longitude: " + position.coords.longitude);
}
function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
alert("Comments are only permitted when location sharing is enabled- you have denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Comments are only permitted when location sharing is enabled- Location information is unavailable.");
break;
case error.TIMEOUT:
alert("Comments are only permitted when location sharing is enabled- the request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("Comments are only permitted when location sharing is enabled- An unknown error occurred.");
break;
}
}
}
</script>
In the above example: Check if Geolocation is supported
- If supported, run the
getCurrentPosition() method. If not,
display a message to the user.
- If the getCurrentPosition() method is successful, it returns a
coordinates object to the function
specified in the first parameter (
success )
- The success() function displays the Latitude and Longitude
- If the getCurrentPosition() method fails to get the user's
location it returns the error object
to the function specified in second
parameter (showError)
- The showError() functiona displays the error message.
Hope this will help you:)
0 Comment(s)