Vue Js find nearest location using latitude and longitude:To find the nearest location using latitude and longitude in Vue.js, we need to calculate the distance between the user’s location and all the available locations. We can use the Haversine formula to calculate the distance.
First, we need to convert the latitude and longitude values from degrees to radians. Then, we can calculate the distance using the Haversine formula, which takes into account the curvature of the earth.
We can then compare the distances and find the closest location.
How can I use Vue js to find the nearest location based on latitude and longitude coordinates?
The code you provided uses Vue.js to find the nearest location based on user input latitude and longitude. It works by iterating over an array of locations and calculating the distance between each location and the user’s location using the getDistanceFromLatLonInKm
function, which implements the Haversine formula to calculate the distance between two points on a sphere.
Vue Js find nearest location using latitude and longitude Example
<div id="app">
<p>Enter your current latitude and longitude:</p>
<div>
<label for="latitude">Latitude:</label>
<input type="text" id="latitude" v-model="latitude">
</div>
<div>
<label for="longitude">Longitude:</label>
<input type="text" id="longitude" v-model="longitude">
</div>
<button @click="findNearestLocation">Find Nearest Location</button>
<p v-if="nearestLocation">The nearest location is {{ nearestLocation.name }} ({{ nearestDistance }} km away).
</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
latitude: '26.7814955',
longitude: '80.9152434',
nearestLocation: null,
nearestDistance: null,
locations: [
{ name: 'Location A', latitude: 37.7749, longitude: -122.4194 },
{ name: 'Location B', latitude: 37.7749, longitude: -122.4084 },
{ name: 'Location C', latitude: 37.7858, longitude: -122.4011 }
]
};
},
methods: {
findNearestLocation() {
const userLocation = {
latitude: parseFloat(this.latitude),
longitude: parseFloat(this.longitude)
};
let nearestLocation = null;
let nearestDistance = Infinity;
for (const location of this.locations) {
const distance = this.getDistanceFromLatLonInKm(userLocation.latitude, userLocation.longitude, location.latitude, location.longitude);
if (distance < nearestDistance) {
nearestLocation = location;
nearestDistance = distance;
}
}
this.nearestLocation = nearestLocation;
this.nearestDistance = nearestDistance;
},
getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
const earthRadiusKm = 6371;
const dLat = this.deg2rad(lat2 - lat1);
const dLon = this.deg2rad(lon2 - lon1);
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = earthRadiusKm * c;
return distance;
},
deg2rad(deg) {
return deg * (Math.PI / 180);
}
}
});
</script>