如何通过JS将后端JSON返回的坐标传入Google Roads API的path参数?
Solution: Inject Backend Coordinates into Google Roads API Request
Got it, let's work through this properly. The main thing to watch out for here is the asynchronous behavior of AJAX requests—you need to wait until you've fetched the backend coordinate data before building and calling the Google Roads API URL. Here's how to adjust your code:
var speeddata = []; function getSpeedData() { // First, fetch the backend coordinate data var url = $('#getData').data('request-url'); $.getJSON(url, function (data) { speeddata = data; console.log("Backend coordinate data:", speeddata); // Only proceed if we have valid data if (!speeddata || speeddata.length === 0) { console.error("No coordinate data received from backend"); return; } // Convert the backend coordinates to Google's path format (lat,lng|lat,lng...) var pathString = speeddata.map(function(coord) { // Assuming each item in speeddata has 'lat' and 'lng' properties // Adjust property names here if your backend returns different keys (e.g., latitude/longitude) return `${coord.lat},${coord.lng}`; }).join('|'); // Build the Google Roads API URL with the dynamic path var googleurl = `https://roads.googleapis.com/v1/speedLimits?path=${encodeURIComponent(pathString)}&key=8IAceOk43NpWKpczMAzN5dVosUI=`; // Now fetch speed limits from Google $.getJSON(googleurl, function (speedLimitsData, status) { console.log("Google speed limits data:", speedLimitsData); // Do something with the speed limits data here }).fail(function() { console.error("Failed to fetch data from Google Roads API"); }); }).fail(function() { console.error("Failed to fetch coordinate data from backend"); }); }
Key Details to Note:
- Asynchronous Order: We moved the Google API request inside the backend request's callback. This ensures we only build the path once we actually have the coordinate data (since AJAX requests don't run in order synchronously).
- Coordinate Format Conversion: The
map()function converts each coordinate object inspeeddatato thelat,lngstring format Google expects, thenjoin('|')combines them with pipes to form the full path parameter.- If your backend returns coordinates with different property names (like
latitudeinstead oflat), make sure to update thecoord.lat/coord.lngparts to match your actual data structure.
- If your backend returns coordinates with different property names (like
- URL Encoding: We used
encodeURIComponent()on the path string to handle any special characters (though coordinates usually don't have them, it's a good practice to avoid URL errors). - Error Handling: Added
.fail()callbacks for both AJAX requests to catch and log failures—this helps debug if something goes wrong with either API call.
内容的提问来源于stack exchange,提问作者Old Balance
相关产品推荐
相关产品推荐

