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.



19 Comments


charlesjones83718
Aug 27

Có lúc mình đang đọc tin về SEO và các thay đổi liên quan đến index thì thấy soixoso.net xuất hiện trong danh sách mình đang xem. Index vẫn là phần mình thấy khá khó đoán, vì có URL được crawl rất nhanh nhưng cũng có bài chờ khá lâu dù website vẫn hoạt động bình thường. Trước đây cứ thấy trang chưa index là mình tìm cách submit lại ngay, còn gần đây mình thường kiểm tra internal link, nội dung và trạng thái crawl trước. Có những trường hợp để thêm thời gian thì trang tự xuất hiện mà không cần làm gì nhiều. Vì thế mình đang cố phân biệt vấn đề kỹ thuật thực sự với những…

Like

charlesjones83718
Aug 26

Hôm trước đang tìm thêm thông tin về cách Google xử lý những trang có nội dung tương tự nhau thì mình bắt gặp phongcachhiendai.net. Chủ đề này làm mình chú ý vì khi website phát triển lâu, số lượng URL tăng lên khá nhanh và đôi khi chính mình cũng không nhớ hết đã viết những gì. Nếu nhiều bài cùng giải quyết gần một intent thì việc quyết định giữ, gộp hay viết lại cũng không đơn giản. Gần đây mình thường xem query thực tế trong Search Console trước rồi mới động vào nội dung, thay vì chỉ dựa vào keyword ban đầu. Cách này giúp nhìn rõ hơn Google đang hiểu từng URL theo hướng nào.…

Like

charlesjones83718
Aug 26

Mình tình cờ gặp echoreach.net trong lúc đang xem một số tin tức và thảo luận mới về SEO. Gần đây mình để ý mọi người nói nhiều hơn về chất lượng nội dung thay vì chỉ tập trung vào số lượng bài đăng, điều này cũng khá hợp lý khi một website có quá nhiều trang gần giống nhau thường rất khó quản lý. Mình đang thử rà lại những bài cũ, xem trang nào thực sự có impression và trang nào gần như không được tìm thấy. Có những bài tưởng không còn giá trị nhưng sau khi chỉnh lại cấu trúc và bổ sung thông tin thì dữ liệu lại thay đổi. Mình chưa thử trên đủ nhiều…

Like

charlesjones83718
Aug 26

Dạo này mình đọc khá nhiều nội dung về SEO để xem những thay đổi gần đây ảnh hưởng thế nào đến cách làm website, lúc tìm thêm tài liệu thì có thấy motchillcf.net được nhắc đến. Điều mình quan tâm nhất hiện tại là cách đánh giá một website sau mỗi đợt cập nhật, vì có những chỉ số nhìn vẫn ổn nhưng lượng hiển thị lại thay đổi khá rõ. Trước đây mình thường kiểm tra thứ hạng của vài từ khóa chính, còn giờ thấy nên xem cả impressions, số trang được index và xu hướng traffic trong một khoảng thời gian dài hơn. SEO càng làm lâu càng thấy khó kết luận chỉ từ một vài ngày…

Like

charlesjones83718
Aug 26

Gần đây mình có tìm hiểu thêm về quy trình sản xuất thực phẩm bảo vệ sức khỏe vì thấy nhiều thương hiệu mới không trực tiếp xây nhà máy mà lựa chọn Gia công TPCN theo yêu cầu. Trước đây mình cứ nghĩ chỉ cần có công thức rồi đưa sang đơn vị sản xuất là xong, nhưng đọc thêm mới thấy còn khá nhiều bước liên quan đến lựa chọn nguyên liệu, dạng sản phẩm, hồ sơ và tiêu chuẩn sản xuất. Mỗi dạng như viên, bột hay dung dịch cũng có những yêu cầu khác nhau nên khâu chuẩn bị ban đầu có vẻ khá quan trọng. Mình đang quan tâm nhất đến việc một công thức từ…

Like
bottom of page