Hello, i am facing problem of getting latitude and longitude of my current location. Please explain why is this happening to me.
Here is my Fiddle
https://jsfiddle.net/mustajab/2dd3p35k/11/
Thanks in advance. Reply soon. I am waiting
Hello, i am facing problem of getting latitude and longitude of my current location. Please explain why is this happening to me.
Here is my Fiddle
https://jsfiddle.net/mustajab/2dd3p35k/11/
Thanks in advance. Reply soon. I am waiting
Hi mustajab,
For some reason the onclick event in your button thinks the getLocation function is not defined.
As far as I can see the function is global, so not sure why it does that. But you may want to drop the inline javascript (i.e. js within HTML) anyway and swap it for an event listener at the end of your javascript code:
document.getElementById(_button id_).addEventListener("click", getLocation, false)
Here is more info on why inline js is not a good idea: https://www.reddit.com/r/javascript/comments/3kamqn/why_is_inline_onclickfunction_considered_such_a/?st=je480tjb&sh=ca07e579
Hi @pwkrz
Just as an FYI, the reason it’s showing as undefined is because technically it isn’t global. JSfiddle sticks your code inside the window.onload
function, so when it hits the browser, it’s scoped to that function and not in the global scope:
//<![CDATA[
window.onload=function(){
/* $(document).ready(function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$(".data").html("Latitude: " + position.coords.latitude + "<br>Longitude : " + position.coords.longitude);
});
}
}); */
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";}
}
function showPosition(position) {
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
}//]]>
Hi joesmith100.
Can you please give a link of fiddle because by applying windows.onload=function() {} still i am not getting the cordinates. Thanks
Read @pwkrz post, I was just pointing out why the onclick function wasn’t picking up the getLocation
method
Hi pwkrz. Thanks for replying.
I am new to these freecodecamp challenges so it will be really helpful if you paste your fiddle link for this problems solution
Oh my bad. So joesmith100 please suggest me solution of this.
As @pwkrz said, you want to use addEventListener, rather then in lining the onclick function. Like this: https://jsfiddle.net/2dd3p35k/31/
Thanks joesmith100. My problem is solved now