You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

谷歌地图距离计算脚本返回带逗号格式致车费计算$NaN问题

Fixing $NaN Fare Calculation from Google Maps Distance

Hey there, let's fix that frustrating $NaN issue you're seeing with your fare calculation! The root problem is straightforward: Google Maps returns distance text in a human-readable format (like 1,5 miles) which includes non-numeric characters (the comma separator and "miles" label) that JavaScript can't parse into a valid number for math operations.

Step-by-Step Solution

Here's how to clean up the distance value before using it for fare calculations:

  • Extract the numeric portion from Google's response, stripping out the "miles" label and any other non-digit characters.
  • Normalize the decimal separator: Google might use a comma (common in European locales) instead of a period for decimals—we'll convert that to a period so JavaScript can read it as a valid float.
  • Convert to a numeric value and format it to the 00.00 format your cost field expects.

Modified Code Example

Replace your existing distance assignment code with this:

// Grab the raw distance text from Google Maps
const rawDistance = response.routes[0].legs[0].distance.text;

// Step 1: Remove all non-numeric characters except commas/periods
const numericOnly = rawDistance.replace(/[^0-9,.]/g, '');

// Step 2: Convert comma decimal separators to periods (adjust if using thousand separators)
// If Google uses commas for thousands (e.g., "1,234.5 miles"), use numericOnly.replace(/,/g, '') instead
const cleanDistance = numericOnly.replace(',', '.');

// Step 3: Convert to a float and format to 2 decimal places
const formattedDistance = parseFloat(cleanDistance).toFixed(2);

// Update the distance field with the valid numeric format
document.getElementById("distance_road").value = formattedDistance;

// Calculate your fare (example: $2.75 per mile)
const fareRate = 2.75;
const totalFare = parseFloat(formattedDistance) * fareRate;

// Update the cost field with properly formatted fare
document.getElementById("cost_field").value = `$${totalFare.toFixed(2)}`;

Key Notes

  • Locale Adjustment: If Google returns distances with commas as thousand separators (e.g., 1,234.5 miles), swap the separator line to numericOnly.replace(/,/g, '') to remove commas instead of converting them.
  • Error Handling: Add a quick check to ensure the route exists before accessing it, to avoid crashes if no route is found:
    if (response.routes && response.routes.length > 0 && response.routes[0].legs.length > 0) {
      // Run the distance/fare code here
    } else {
      alert("No valid route found!");
    }
    

This will ensure your distance field has a valid 00.00 numeric value, so your fare calculation won't spit out $NaN anymore.

内容的提问来源于stack exchange,提问作者ben ati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:18:01