Vue.js Get Geolocation


We can use navigator geolocation property to get the current location of visitor(user) in JavaScript. You can use the same native JavaScript geolocation property in Vue.js.


Vue.js Get Geolocation | Lat | Lon Example

Using geolocation property we can get user’s lattitude and longitude. You can use navigator geolocation property in Vue.js Simply as below-

Example:

<div id="app">
	<p>Lat = {{lat}} Lon ={{lon}}</p>
	<p>{{error}}</p>
	<button @click="myFunction()">Click Me</button>
</div>
<script>
 new Vue({
 el: '#app',
  
  data: {
	  error: '',
	  lat:'',
	  lon:''
  },  
   methods:{
    myFunction: function () {		
	 if(navigator.geolocation){
	 navigator.geolocation.getCurrentPosition(this.showPosition);
	 }else{
	 this.error = "Geolocation is not supported."; 
		 
	 }
    },
	showPosition:function (position) {	
		this.lat = position.coords.latitude;
		this.lon = position.coords.longitude;
	}
	}

});
</script>   

Try it »

Note : This property works with SSL enabled urls.
Note : This property supports read only.

Advertisements

Add Comment

📖 Read More