Search code examples
javascriptvue.jsvuejs2vuex

Get current latitude and longitude in vuejs


I want to get latitude and longitude from current location dynamically. Is there any plugin or custom code to do that?


Solution

  • You can use Web Geolocation API as follows:

    const vueComp = new Vue({
    
        data () {
            return {
                /* Reactive properties */
            };
        },
    
        created() {
    
            const success = (position) => {
                const latitude  = position.coords.latitude;
                const longitude = position.coords.longitude;
    
                // Do something with the position
            };
    
            const error = (err) => {
                console.log(error)
            };
    
            // This will open permission popup
            navigator.geolocation.getCurrentPosition(success, error);
        }
    
    });
    

    Also, if you need a promisified plugin, you can use vue-browser-geolocation plugin.