0

I am trying to grab geolocation for my app. Geolocation should be grabbed on created hook.

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(displayLocationInfo);
}

function displayLocationInfo(position) {
  const lng = position.coords.longitude;
  const lat = position.coords.latitude;

  console.log(`longitude: ${ lng } | latitude: ${ lat }`);
}

But my console is empty.

1
  • my console prints longitude: 90.3979008 | latitude: 23.765811199999998 after giving permission Commented Sep 30, 2018 at 8:35

1 Answer 1

1

The real way to use Geolocation API is to check the availability of it on your device/browser before using it, so just add an else block to your existing code. Hope it'll help :) See more at MDN

if ("geolocation" in navigator) {
  /* geolocation is available */
  navigator.geolocation.getCurrentPosition(displayLocationInfo);
  
  function displayLocationInfo(position) {
    const lng = position.coords.longitude;
    const lat = position.coords.latitude;

    console.log(`longitude: ${ lng } | latitude: ${ lat }`);
  }
} else {
  /* geolocation IS NOT available  */
  console.log('geolocation IS NOT available on your browser');
}

Sign up to request clarification or add additional context in comments.

5 Comments

"geolocation" in navigator and navigator.geolocation are fairly equivalent as far as boolean expressions go
@Phil totally agreed with you Sir, Edited, Thankz :)
i know what is the problem. I added Timeout for 5 sec. And after 5 sec it says: "Uncaught (in promise) no position access"
Ohh , but you didn't provide full code with timeout. Ok best of luck
Try it over HTTPS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.