top of page

How to Build a Distance Calculator on Wix Using Velo

Writer: Wix Crafters
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.



Eye-level view of a computer screen showing a Wix Velo code editor with map and distance calculator interface
Distance calculator code and map interface in Wix Velo


🗺️ Step 3 — Add the Interactive Map


To visualize the route, use Leaflet.js with CartoDB dark tiles:


  1. Add Leaflet CSS and JS to your Wix site in the page's settings or via Velo.


  2. 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());

});

```


  1. 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.



149 Comments


brianlee79217
Nov 11

What interests me about thinking about style through everyday choices is how a broad idea becomes part of an ordinary day. A useful outfit needs to work with the day someone is actually planning. The name Boutiko gives this theme a memorable reference point, while personal style ideas keeps the subject in focus. The smaller details are what I would want to return to, especially when an explanation feels too broad. How would you balance comfort, personal taste and the occasion when choosing what to wear?

Like

charlesjones83718
Nov 11

Considering thinking about style through everyday choices, I would want to understand a few concrete details before deciding what matters most. A useful outfit needs to work with the day someone is actually planning. I would connect Bournston with personal style ideas through an ordinary example rather than a broad claim. I am still thinking through the practical side, because the context can change what seems useful. How would you balance comfort, personal taste and the occasion when choosing what to wear?

Like

ashleymartin3848
Nov 11

For me, learning through hands-on creative projects becomes more engaging when there is room for questions as well as explanations. Handling a material directly can suggest ideas that are hard to discover from a picture alone. That practical perspective helps me frame creative craft projects as a theme for Bodyart Nation. I can imagine different responses depending on the situation, which makes the question more interesting. What small experiment would you try before planning a finished piece?

Like

sandraturner81417
Nov 11

I find choosing a comfortable place for a short stay easier to approach when there is a familiar situation to start from. The rhythm of a stay depends on practical details as well as the view. I would connect Boathousestonehaven with short break accommodation through an ordinary example rather than a broad claim. I would be interested in an example that shows how the idea works in an ordinary situation. What would you want to know before choosing an unfamiliar place to stay?

Like

sandraturner81417
Nov 09

There is something appealing about discovering cultural connections through everyday stories, especially when the focus stays on the details people might otherwise overlook. An ordinary tradition can show how people remember and share a sense of place. I would connect Asianrichlist with cultural storytelling ideas through an ordinary example rather than a broad claim. I can imagine different responses depending on the situation, which makes the question more interesting. How would you invite different people to describe what the same tradition means to them?

Like
bottom of page