Create Distance Calculator between 2 cities in html

Here’s an example of a basic distance calculator in HTML that calculates the distance between two cities based on their names:

<!DOCTYPE html>
    <title>Distance Calculator</title>
    <script src=""></script>
    <h1>Distance Calculator</h1>
      City A: <input type="text" id="city1"><br><br>
      City B: <input type="text" id="city2"><br><br>
      <button onclick="calculateDistance()">Calculate Distance</button>
    <p>Distance: <span id="distance"></span> km</p>
      function calculateDistance() {
        var cityA = document.getElementById("city1").value;
        var cityB = document.getElementById("city2").value;
        var service = new google.maps.DistanceMatrixService();
          origins: [cityA],
          destinations: [cityB],
          travelMode: 'DRIVING',
        }, callback);

        function callback(response, status) {
          if (status == 'OK') {
            var distance = response.rows[0].elements[0].distance.text;
            document.getElementById("distance").innerHTML = distance;
          } else {
            alert('Error: ' + status);

This will create a simple webpage with a form that prompts the user to enter the names of two cities (City A and City B). The form includes a button labeled “Calculate Distance” that, when clicked, runs a JavaScript function to use the Google Maps Distance Matrix API to calculate the distance between the two cities in kilometers. The result will be shown on the page.

Make sure you have the valid API key for Google maps JavaScript API, replace ‘API_KEY’ in the script with your own. You can handle the error message if city names not found or you could add validation for the inputs for better user experience.

It’s a basic example, but it can be improved to suit your needs and make it more user-friendly.