Difficulty with checking if locations are within a route using Google Maps API using JS

I’ve implemented Google Maps API to show a map with the user’s current location and allow them to search for a destination.
I use DirectionsService to calculate and display a driving route from the user’s location to the destination.
I’m fetching XML data for bike stations, bus stops, and tube stations and trying to place markers for those that are close to the route.

Despite using checkDistanceToRoute, which calculates distances accurately for other points of interest (e.g., bike stations, bus stops), the function consistently determines that tube stations are not within the route, even when they should be visibly close on the map, even when I am checking for a radius of 1km of the route.

let map;
let geocoder;
let directionsService;
let directionsRenderer = null;
let markers = [];
let userLocation;
let destinationLocation;

function initMap() {
  navigator.geolocation.getCurrentPosition(function (position) {
    const userLat = position.coords.latitude;
    const userLng = position.coords.longitude;
    userLocation = new google.maps.LatLng(userLat, userLng);

    map = new google.maps.Map(document.getElementById("map"), {
      center: userLocation,
      zoom: 15,
    });

    const userMarker = new google.maps.Marker({
      map: map,
      position: userLocation,
      title: "Your Location",
    });

    markers.push(userMarker);

    geocoder = new google.maps.Geocoder();
    directionsService = new google.maps.DirectionsService();

    document.getElementById("searchButton").addEventListener("click", function () {
      searchPlace();
    });

    document.getElementById("showBikePointsButton").addEventListener("click", function () {
      showBikeStations();
    });

    document.getElementById("showBusLocationsButton").addEventListener("click", function () {
      showBusLocations();
    });

    document.getElementById("showTubeLocationsButton").addEventListener("click", function () {
      showTubeLocations();
    });

  });
}

function searchPlace() {
  if (directionsRenderer) {
    directionsRenderer.setMap(null);
  }
  clearMarkers();
  clearBikePointMarkers();

  const destinationName = document.getElementById("searchInput").value;

  geocoder.geocode({ address: destinationName }, function (results, status) {
    if (status === google.maps.GeocoderStatus.OK && results.length > 0) {
      destinationLocation = results[0].geometry.location;

      const directionsRequest = {
        origin: userLocation,
        destination: destinationLocation,
        travelMode: google.maps.TravelMode.DRIVING,
      };
      directionsService.route(directionsRequest, function (response, status) {
        if (status === google.maps.DirectionsStatus.OK) {
          if (!directionsRenderer) {
            directionsRenderer = new google.maps.DirectionsRenderer();
          }
          directionsRenderer.setMap(map);
          directionsRenderer.setDirections(response);

          // Calculate and display the distance
          calculateAndDisplayDistance(userLocation, destinationLocation);
        } else {
          alert("Oops, couldn't find directions due to " + status);
        }
      });

      const destinationMarker = new google.maps.Marker({
        map: map,
        position: destinationLocation,
        title: destinationName,
      });

      markers.push(destinationMarker);
    } else {
      alert("Oops, couldn't find that place. Try something else!");
    }
  });
}

function clearMarkers() {
  for (let i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers = [];
}

function showBikeStations() {
  clearMarkers();
  clearBikePointMarkers();
  const xhr = new XMLHttpRequest();
  const apiUrl = "https://tfl.gov.uk/tfl/syndication/feeds/cycle-hire/livecyclehireupdates.xml";

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      const xmlDoc = xhr.responseXML;
      const stations = xmlDoc.getElementsByTagName("station");

      for (let i = 0; i < stations.length; i++) {
        const station = stations[i];
        const stationName = station.getElementsByTagName("name")[0].textContent;
        const stationLat = parseFloat(station.getElementsByTagName("lat")[0].textContent);
        const stationLng = parseFloat(station.getElementsByTagName("long")[0].textContent);

        const stationLocation = new google.maps.LatLng(stationLat, stationLng);

        const isWithinRange = checkDistanceToRoute(stationLocation);

        if (isWithinRange) {
          const stationMarker = new google.maps.Marker({
            map: map,
            position: stationLocation,
            title: stationName,
            icon: {
              url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png",
            },
          });

          markers.push(stationMarker);
        }
      }
    }
  };

  xhr.open("GET", apiUrl, true);
  xhr.send();
}

function showBusLocations() {
  clearMarkers();
  clearBikePointMarkers();

  // Replace 'bus_locations.xml' with the actual path to your XML file
  const xmlFile = "bus_locations.xml";
  const xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      const xmlDoc = xhr.responseXML;
      const locationElements = xmlDoc.getElementsByTagName("location");

      if (directionsRenderer && directionsRenderer.getDirections()) {
        const route = directionsRenderer.getDirections().routes[0];

        for (let i = 0; i < locationElements.length; i++) {
          const location = locationElements[i];
          const stopName = location.getElementsByTagName("name")[0].textContent;
          const stopLat = parseFloat(location.getElementsByTagName("latitude")[0].textContent);
          const stopLng = parseFloat(location.getElementsByTagName("longitude")[0].textContent);

          const busStopLocation = new google.maps.LatLng(stopLat, stopLng);

          const isWithinRange = checkDistanceToRoute(busStopLocation, route);

          if (isWithinRange) {
            const busStopMarker = new google.maps.Marker({
              map: map,
              position: busStopLocation,
              title: stopName,
            });

            markers.push(busStopMarker);
          }
        }
      }
    }
  };

  xhr.open("GET", xmlFile, true);
  xhr.send();
}

function showTubeLocations() {
  clearMarkers();
  clearBikePointMarkers();
  console.log("TUBE WORKS");

  const xmlUrl = "tubes22.xml"; // Replace with your XML file URL

  fetch(xmlUrl)
    .then((response) => response.text())
    .then((xmlData) => {
      // Parse the XML data
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(xmlData, "application/xml");
      const records = xmlDoc.getElementsByTagName("Record");

      console.log("Parsed XML data:", records); // Debugging line

      if (directionsRenderer && directionsRenderer.getDirections()) {
        const route = directionsRenderer.getDirections().routes[0];

        for (let i = 0; i < records.length; i++) {
          const record = records[i];
          const row = record.getElementsByTagName("Row")[0];
          const stationName = row.getAttribute("A");
          const latitude = parseFloat(row.getAttribute("B"));
          const longitude = parseFloat(row.getAttribute("C"));

          console.log("Station Name:", stationName); // Debugging line
          console.log("Latitude:", latitude);         // Debugging line
          console.log("Longitude:", longitude);       // Debugging line

          const tubeStopLocation = new google.maps.LatLng(latitude, longitude);

          const isWithinRange = checkDistanceToRoute(tubeStopLocation, route);

          console.log("Is Within Range:", isWithinRange); // Debugging line

          if (isWithinRange) {
            const tubeStopMarker = new google.maps.Marker({
              map: map,
              position: tubeStopLocation,
              title: stationName,
            });

            markers.push(tubeStopMarker);
          }
        }
      }
    })
    .catch((error) => {
      console.error("Error fetching or parsing XML data: ", error);
    });
}


// Adjust the distance threshold (300 meters in this example) in checkDistanceToRoute() according to your specific requirements.
function checkDistanceToRoute(location, route) {
  const routePath = route.overview_path;

  for (let i = 0; i < routePath.length; i++) {
    const point = routePath[i];
    const distance = google.maps.geometry.spherical.computeDistanceBetween(location, point);
    if (distance <= 1000) {
      return true;
    }
  }
  
  return false;
}

function clearMarkers() {
  markers.forEach(marker => marker.setMap(null));
  markers = [];
}


function calculateAndDisplayDistance(origin, destination) {
  const service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: [destination],
      travelMode: google.maps.TravelMode.DRIVING,
    },
    function (response, status) {
      if (status === google.maps.DistanceMatrixStatus.OK) {
        const distanceText = response.rows[0].elements[0].distance.text;
        document.getElementById("distanceText").textContent = `Distance to destination: ${distanceText}`;
      } else {
        alert("Error calculating distance: " + status);
      }
    }
  );
}

function checkDistanceToRoute(location) {
  if (directionsRenderer && directionsRenderer.getDirections()) {
    const route = directionsRenderer.getDirections().routes[0];
    for (let i = 0; i < route.legs.length; i++) {
      const leg = route.legs[i];
      const steps = leg.steps;
      for (let j = 0; j < steps.length; j++) {
        const step = steps[j];
        const path = step.path;
        for (let k = 0; k < path.length; k++) {
          const point = path[k];
          const distance = google.maps.geometry.spherical.computeDistanceBetween(location, point);
          if (distance <= 300) {
            return true;
          }
        }
      }
    }
  }
  return false;
}

function clearBikePointMarkers() {
  markers.forEach((marker) => {
    if (marker.getTitle()) {
      marker.setMap(null);
    }
  });

  markers = markers.filter((marker) => !marker.getTitle());
}

New contributor

Sidar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật