Search code examples
vue.jsgetlocation

Vue 3 composition API get value from RefImpl


I utilized the useGeolocation function from @vueuse/core to access the user's current location. However, upon attempting to retrieve the latitude and longitude coordinates, it returned an Infinity value. What could be causing this issue? How can it return real value?

Code:

    <script setup>
    import { onBeforeMount, onMounted, ref } from "vue";
    import { useGeolocation } from "@vueuse/core";
    const { coords, locatedAt, error, resume, pause } = useGeolocation();

    const form = ref({
        coords: null,
    })

    onMounted(() => {
        form.value.coords = {
            latitude: coords.value.latitude,
            longitude: coords.value.longitude
        }
        console.log(coords);
    })
   </script>

Solution

  • Because geolocation is async it takes time to update its value. you can use the watch to set your reactive form variable. here is the code.

    <script setup>
    import {onMounted, ref, watch} from "vue";
    import {useGeolocation} from "@vueuse/core";
    
    const {coords, locatedAt, error, resume, pause} = useGeolocation();
    
    const form = ref({
        coords: null,
    })
    
    onMounted(() => {
        setGeolocationCoords()
    })
    
    const setGeolocationCoords = async () => {
        if (coords.value?.latitude !== Infinity) {
            form.value.coords = {
                latitude: coords.value.latitude,
                longitude: coords.value.longitude
            }
            
            console.log(coords.value)
        }
    }
    
    watch(() => coords.value.latitude, () => {
        setGeolocationCoords()
    })
    </script>
    

    you can see the coords object in the console now.