Local Weather App-LatLong is not working

Local Weather App-LatLong is not working
0

#1

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


#2

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


#3

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;
}
}//]]> 

#4

Hi joesmith100.
Can you please give a link of fiddle because by applying windows.onload=function() {} still i am not getting the cordinates. Thanks


#5

Read @pwkrz post, I was just pointing out why the onclick function wasn’t picking up the getLocation method


#6

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


#7

Oh my bad. So joesmith100 please suggest me solution of this.


#8

As @pwkrz said, you want to use addEventListener, rather then in lining the onclick function. Like this: https://jsfiddle.net/2dd3p35k/31/


#9

Thanks joesmith100. My problem is solved now