-1

I want to display latitude and longitude but he some error come :- Here is my code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello everyone</h1>
    <script>
        
        if ('geolocation' in navigator) {
            console.log('gelocation is availabe');
            navigator.geolocation.getCurrentPosition((position) => {
                const lat=position.coords.latitude;
                const lon=position.coords.latitude;
                document.getElementById('latitude').textContent=lat;
                document.getElementById('longitutde').textContent=lon;

                // console.log(position);
});
  
} else {
  console.log('geolocation IS NOT available ');
}
    </script>
</body>
</html>

Here is error comes

I want to display latitude and longitude

  • `const lon=position.coords.latitude;` is a typo; you mean `const lon=position.coords.longitude;`. Where do you expect to display anything? None of the elements with the IDs you’ve specified exist. – Sebastian Simon Nov 11 '22 at 07:50

1 Answers1

0

You should wait for the DOM to be loaded because before the script in the HTML no element with id longitude neither latiture exist. Encapsulate your if/else code in a document.addEventListener('DOMContentLoaded', () => { ... }) callback.

Then textContent does not exist, use .innerText = ...

<script>
    document.addEventListener('DOMContentLoaded', () => {
        if ('geolocation' in navigator) {
            console.log('gelocation is availabe');
            navigator.geolocation.getCurrentPosition((position) => {
                const lat=position.coords.latitude;
                const lon=position.coords.latitude;
                document.getElementById('latitude').innerText = lat;
                document.getElementById('longitutde').innerText = lon;

                // console.log(position);
            });

         } else {
             console.log('geolocation IS NOT available ');
         }
    });
</script>
GregThB
  • 283
  • 1
  • 7