Javascript 选择器无法更改可见细节

问题描述 投票:0回答:0

我有一个代码可以生成两点之间的距离,从而生成旅行时间和各种价格,但是代码没有在正确的空间中显示结果。更改类和 ID 没有用,也没有弄乱 ID:

// Set up the map and geocoder objects
var map;
var geocoder;

// Get the user's current location and set it as the starting point
function getCurrentLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var latlng = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      geocoder.geocode({
        'location': latlng
      }, function(results, status) {
        if (status === 'OK') {
          if (results[0]) {
            // Set the origin field in the mapping API
            document.getElementById('origin').value = results[0].formatted_address;
          } else {
            alert('No results found');
          }
        } else {
          alert('Geocoder failed due to: ' + status);
        }
      });
    }, function() {
      alert('Unable to retrieve your location');
    });
  } else {
    alert('Geolocation is not supported by this browser.');
  }
}

// Calculate the estimated route and cost for the trip


// Get the input fields for the origin and destination
const originInput = document.getElementById("origin-input");
const destinationInput = document.getElementById("destination-input");

// Create a new Google Maps Distance Matrix service
const distanceService = new google.maps.DistanceMatrixService();

// When the user selects a destination, calculate the distance and display it
destinationInput.addEventListener("change", function() {
  const origin = originInput.value;
  const destination = destinationInput.value;

  // Call the Distance Matrix API to calculate the distance
  distanceService.getDistanceMatrix({
    origins: [origin],
    destinations: [destination],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
  }, function(response, status) {
    if (status === "OK") {

      if (response && response.rows && response.rows.length > 0 && response.rows[0].elements && response.rows[0].elements.length > 0 && response.rows[0].elements[0].distance) {
        const distance = response.rows[0].elements[0].distance.value / 1000; // Convert to km
      } else {
        console.log('Error: Invalid API response');
      }

      // Get the distance and duration from the response
      const distance = response.rows[0].elements[0].distance.value / 1000; // Convert to km
      //   const distance = response.rows[0].elements[0].distance.value / 1609.34;
      const duration = response.rows[0].elements[0].duration.text;

      // Calculate the ride price based on the distance
      const pricePerKmExecutive = 20; // Pricing: $20 per kilometer for executive ride
      const pricePerKmClassic = 10; // Pricing: $10 per kilometer for classic ride
      const deliveryPrice = 15; // Flat delivery fee: $15

      const executiveRidePrice = distance * pricePerKmExecutive;
      const classicRidePrice = distance * pricePerKmClassic;

      // Format the ride prices and delivery price as currency strings
      const formattedExecutivePrice = executiveRidePrice.toLocaleString("en-US", {
        style: "currency",
        currency: "NGN"
      });
      const formattedClassicPrice = classicRidePrice.toLocaleString("en-US", {
        style: "currency",
        currency: "NGN"
      });
      const formattedDeliveryPrice = deliveryPrice.toLocaleString("en-US", {
        style: "currency",
        currency: "NGN"
      });

      // Display the distance, duration, and ride prices in the HTML
      const aboutSectionTitle1 = document.querySelector(".about-section-1 .about-section-title");
      aboutSectionTitle1.innerHTML = `Executive Ride: <strong>${formattedExecutivePrice}</strong> / ${distance.toFixed(2)} km / <span class="black-text">${duration}</span>`;

      const ridePriceElement1 = document.querySelector(".about-section-1 #ride-price");
      ridePriceElement1.innerHTML = `<strong>${formattedExecutivePrice}</strong>`;

      const distanceElement1 = document.querySelector(".about-section-1 #distance");
      distanceElement1.innerHTML = `${distance.toFixed(2)} km`;

      const durationElement1 = document.querySelector(".about-section-1 #duration");
      durationElement1.innerHTML = `${duration}`;



      const aboutSectionTitle2 = document.querySelector(".about-section-2 .about-section-title");
      aboutSectionTitle2.innerHTML = `Classic Ride: <strong>${formattedClassicPrice}</strong> / ${distance.toFixed(2)} km / <span class="black-text">${duration}</span>`;

      const ridePriceElement2 = document.querySelector(".about-section-2 #ride-price");
      ridePriceElement2.innerHTML = `<strong>${formattedClassicPrice}</strong>`;

      const distanceElement2 = document.querySelector(".about-section-2 #distance");
      distanceElement2.innerHTML = `${distance.toFixed(2)} km`;

      const durationElement2 = document.querySelector(".about-section-2 #duration");
      durationElement2.innerHTML = `${duration}`;



      const aboutSectionTitle3 = document.querySelector(".about-section-3 .about-section-title");
      aboutSectionTitle3.innerHTML = `Delivery Services: <strong>${formattedDeliveryPrice}</strong> / ${distance.toFixed(2)} km / <span class="black-text">${duration}</span>`;

      const ridePriceElement3 = document.querySelector(".about-section-3 #ride-price");
      ridePriceElement3.innerHTML = `<strong>${formattedClassicPrice}</strong>`;

      const distanceElement3 = document.querySelector(".about-section-3 #distance");
      distanceElement3.innerHTML = `${distance.toFixed(2)} km`;

      const durationElement3 = document.querySelector(".about-section-3 #duration");
      durationElement3.innerHTML = `${duration}`;
    }
  });
});
<div class="about-section">

  <div id="executive-ride" class="about-section-1 hidden">
    <div class="about-section-title"> Executive Ride: <strong id="ride-price">₦NaN</strong> / <span id="distance"></span> km / <span class="black-text" id="duration"></span>
      <div id="total-price"></div>
      <div class="about-section-more">
        NOTE: This is an approximate estimate. Actual cost may vary according to the traffic.
      </div>
    </div>
  </div>

  <div id="classic-ride" class="about-section-2 hidden">
    <div class="about-section-title">
      Classic Ride: <strong id="ride-price">₦NaN</strong> / <span id="distance"></span> km / <span class="black-text" id="duration"></span>
      <div id="total-price"></div>

      <div class="about-section-more">
        NOTE: This is an approximate estimate. Actual cost may vary according to the traffic.
      </div>
    </div>
  </div>


  <div id="service-delivery" class="about-section-3 hidden">
    <div class="about-section-title">
      Service Delivery: <strong id="ride-price">₦NaN</strong> / <span id="distance"></span> km / <span class="black-text" id="duration"></span>
      <div id="total-price"></div>
      <div class="about-section-more">
        NOTE: This is an approximate estimate. Actual cost may vary according to the traffic.
      </div>
    </div>
  </div>
</div>

javascript css-selectors
© www.soinside.com 2019 - 2024. All rights reserved.