How to Build a Distance Calculator on Wix Using Velo
- Wix Crafters
- Apr 26
- 4 min read
🎯 Introduction
Adding a distance calculator to your Wix website can significantly improve user experience for businesses in logistics, travel, real estate, and delivery services. Visitors can quickly find out how far two locations are, estimate travel time, and visualize routes—all without leaving your site. This feature helps users make informed decisions, plan trips, or calculate delivery costs with ease.
In this post, you will learn how to build a fully functional distance calculator on Wix using Velo. The tool will include live autocomplete for locations, real road distances in kilometers and miles, travel time for driving, walking, and cycling, an interactive map showing the route, and straight-line distance. Best of all, this solution uses free APIs and requires no paid keys.
📦 What You Will Build
Your distance calculator will offer:
Live autocomplete for location input fields, making it easy for users to find places.
Real road distance displayed in both kilometers and miles.
Travel time estimates for driving, walking, and cycling.
An interactive map showing the route between two points.
Straight-line distance as a quick reference.
All features powered by free, open-source APIs—no API keys needed.
This setup is perfect for Wix site owners and beginner Velo developers who want to add practical, user-friendly tools without extra costs.
✅ Prerequisites
Before starting, make sure you have:
Wix Dev Mode enabled on your site to access Velo coding features.
Basic JavaScript knowledge to understand and customize the code.
No need for paid APIs or subscriptions; all services used here are free.
📦 Step 1 — APIs We Use
To build this calculator, we rely on three main free services:
Nominatim for geocoding
Converts location names into latitude and longitude coordinates. It uses OpenStreetMap data and requires no API key.
OSRM (Open Source Routing Machine) for routing
Calculates real road routes, distances, and travel times for driving, walking, and cycling.
Leaflet.js for the interactive map
A lightweight JavaScript library to display maps and routes with customizable markers and lines. We will use dark-themed map tiles from CartoDB for a modern look.
💻 Step 2 — The Velo Code
Here is a simplified example of how to fetch location coordinates and route data using Velo code:
```javascript
// Function to get coordinates from Nominatim
async function getCoordinates(location) {
const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(location)}`);
const data = await response.json();
if (data.length === 0) throw new Error('Location not found');
return { lat: data[0].lat, lon: data[0].lon };
}
// Function to get route info from OSRM
async function getRoute(start, end, profile = 'driving') {
const url = `https://router.project-osrm.org/route/v1/${profile}/${start.lon},${start.lat};${end.lon},${end.lat}?overview=full&geometries=geojson`;
const response = await fetch(url);
const data = await response.json();
if (data.code !== 'Ok') throw new Error('Route not found');
const route = data.routes[0];
return {
distanceMeters: route.distance,
durationSeconds: route.duration,
geometry: route.geometry
};
}
//
Convert meters to kilometers and miles
function convertDistance(meters) {
return {
km: (meters / 1000).toFixed(2),
miles: (meters / 1609.34).toFixed(2)
};
}
// Convert seconds to minutes
function convertDuration(seconds) {
return (seconds / 60).toFixed(1);
}
//
Example usage
async function calculateDistanceAndTime(fromLocation, toLocation, travelMode) {
try {
const start = await getCoordinates(fromLocation);
const end = await getCoordinates(toLocation);
const route = await getRoute(start, end, travelMode);
const distance = convertDistance(route.distanceMeters);
const duration = convertDuration(route.durationSeconds);
console.log(`Distance: ${distance.km} km (${distance.miles} miles)`);
console.log(`Estimated travel time: ${duration} minutes`);
// You can now pass route.geometry to the map for drawing
} catch (error) {
console.error(error.message);
}
}
```
This code fetches coordinates for two locations, requests the route for the selected travel mode, and converts the results into user-friendly units.

🗺️ Step 3 — Add the Interactive Map
To visualize the route, use Leaflet.js with CartoDB dark tiles:
Add Leaflet CSS and JS to your Wix site in the page's settings or via Velo.
Initialize the map with dark tiles:
```javascript
import { onReady } from 'wix-window';
onReady(() => {
const map = L.map('map').setView([0, 0], 2);
L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
attribution: '© OpenStreetMap contributors © CartoDB',
maxZoom: 18
}).addTo(map);
// Add markers for start and end points
const startMarker = L.marker([start.lat, start.lon], { icon: blueIcon }).addTo(map);
const endMarker = L.marker([end.lat, end.lon], { icon: greenIcon }).addTo(map);
// Draw route polyline
const routeLine = L.geoJSON(route.geometry, { color: 'blue' }).addTo(map);
// Fit map to route bounds
map.fitBounds(routeLine.getBounds());
});
```
Use custom blue and green markers for start and end points to improve clarity.
This map will show the route clearly, helping users visualize their journey.
🐛 Common Issues
| Issue | Solution |
|-------------------|-------------------------------------------|
| Location not found | Use a more specific query including city or region name |
| Map not showing | Ensure Leaflet CSS loads before JS scripts |
| Route not found | OSRM only calculates routes on roads, not off-road paths |
| CORS error | Test the feature on your published Wix site, not in preview mode |
💡 Pro Tips
Add a 300ms debounce on autocomplete input to reduce API calls and improve performance.
Use dark CartoDB tiles to match modern website themes.
Cache recent searches to speed up repeated queries.
Make the map height 200px on mobile devices for better responsiveness.
🚀 Conclusion
Building a distance calculator on Wix with Velo is straightforward using free APIs like Nominatim, OSRM, and Leaflet.js. This tool enhances your site by providing real-time distance and travel time information with an interactive map, all without extra costs.
If you want expert help to add this or other custom features to your Wix site, contact WixCrafters. Our 5-star rated team specializes in Wix Velo development and can deliver tailored solutions quickly.
Visit wixcrafters.com or email us at wixcrafters@gmail.com to get started today.




Comments