How to get user's geolocation?

后端 未结 7 468
忘了有多久
忘了有多久 2021-01-03 02:34

On many sites I saw printed out my current city where I am (eg \"Hello to Berlin.\"). How they do that? What everything is needed for that? I guess the main part is here jav

7条回答
  •  梦谈多话
    2021-01-03 03:04

    If you prefer to use ES6 and promises here is another version

    function getPositionPromised() {
      function successCb(cb) {
        return position => cb(position);
      }
    
      function errorCb(cb) {
        return () => cb('Could not retrieve geolocation');
      }
    
      return new Promise((resolve, reject) => {
        if (window.navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(successCb(resolve), errorCb(reject));
        } else {
          return reject('No geolocation support');
        }
      })
    }
    

    And you can use it like this:

    getPositionPromised()
      .then(position => {/*do something with position*/})
      .catch(() => {/*something went wrong*/})
    

提交回复
热议问题