I'm new to stack overflow , I signed up since I ran into an error. This is for my upcoming high school project !
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form>
<input type="button" value="Result" onclick="getGeolocation" />
<input type="button" value="Result" onclick="getUserCoodinates" />
</form>
<script type="text/javascript">
// <![CDATA[
//run this code when the page loads
jQuery(document).ready(function() {
getGeolocation();
});
//determine if the user's browser has location services enabled. If not, show a message
function getGeolocation() {
if (navigator.geolocation) {
//if location services are turned on, continue and call the getUserCoordinates function below
navigator.geolocation.getCurrentPosition(getUserCoodinates);
} else {
alert('You must enable your device\'s location services in order to run this application.');
}
}
//function is passed a position object which contains the lat and long value
function getUserCoodinates(position) {
//set the application's text inputs LAT and LONG = to the user's lat and long position
jQuery("#LAT").val(position.coords.latitude);
jQuery("#LONG").val(position.coords.longitude);
}
</script>
</body>
</html>
Where have I gone wrong ? ? ?
I'm trying to use this for a mobile web-app.
In your code getUserCoodinates is a callback function so it should not be invoked directly using a button click so that portion of the HTML can be removed. As per the comment from @Darkbee - the webserver should be running the page over SSL/https otherwise this will fail.
The second argument that you can supply to getCurrentPosition is for processing errors - seems to make sense here to use that to try to identify the issue. The following runs perfectly on my test system which does run ssl with a self-signed certificate.
document.querySelector('[type="button"]').addEventListener('click',(e)=>{
if( navigator.geolocation ){
const getUserCoodinates=(pos)=>{
$('#LAT').val(pos.coords.latitude);
$('#LONG').val(pos.coords.longitude);
};
const showError=(error)=>{
let msg='An unknown error occurred.';
switch( error.code ) {
case error.PERMISSION_DENIED:
msg='User denied the request for Geolocation.'
break;
case error.POSITION_UNAVAILABLE:
msg='Location information is unavailable.'
break;
case error.TIMEOUT:
msg='The request to get user location timed out.'
break;
default:break;
}
alert(msg);
};
navigator.geolocation.getCurrentPosition(getUserCoodinates,showError);
}
});
<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<form>
<input id='LAT' />
<input id='LONG' />
<input type='button' value='Result' />
</form>