Google Maps API地理编码获取GPS坐标:JS函数返回值问题咨询
Hey there! I see the issue with your geocoding functions—let's break down why they aren't returning the coordinates you expect, and fix it up.
The main problem here is that the Google Maps Geocoder uses asynchronous operations. When you call get_lat() or get_lng(), the function sends off the geocoding request to Google's API, then immediately finishes running—way before the API sends back your results. The return statement inside your callback function only sends the value back to that callback, not to the outer get_lat/get_lng functions. That's why you're not getting the GPS values you're expecting.
Solution 1: Use a Callback Function
Let's adjust your code to use a callback that will receive the coordinates once the API responds. I'll also combine the two functions into one since you almost always need both latitude and longitude—no need to make two separate API calls!
function getLatLng(address, callback) { geocoder.geocode({ 'address': address }, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { const latitude = results[0].geometry.location.lat(); const longitude = results[0].geometry.location.lng(); console.log(`Latitude: ${latitude}, Longitude: ${longitude}`); // Pass the coordinates to our callback function callback(null, { lat: latitude, lng: longitude }); } else { // If something goes wrong, pass an error to the callback callback(new Error(`Geocoding failed with status: ${status}`), null); } }); } // How to use it: getLatLng("1600 Amphitheatre Parkway, Mountain View, CA", function(error, coords) { if (error) { console.error("Oops, something went wrong:", error); return; } // Now you can use the coordinates here! console.log("Got coordinates:", coords.lat, coords.lng); });
Solution 2: Use Promises (Modern, Cleaner Approach)
Promises make asynchronous code easier to read and manage, especially if you need to chain multiple operations together. Here's how to rewrite the function using Promises, plus an example with async/await for even cleaner code:
function getLatLng(address) { return new Promise((resolve, reject) => { geocoder.geocode({ 'address': address }, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { const lat = results[0].geometry.location.lat(); const lng = results[0].geometry.location.lng(); console.log(`Lat: ${lat}, Lng: ${lng}`); resolve({ lat, lng }); } else { reject(new Error(`Geocoding failed: ${status}`)); } }); }); } // Using .then() and .catch(): getLatLng("1600 Amphitheatre Parkway, Mountain View, CA") .then(coords => { console.log("Retrieved coordinates:", coords.lat, coords.lng); // Use your coordinates here }) .catch(error => { console.error("Error getting coordinates:", error); }); // Or with async/await (even more readable): async function fetchMyCoordinates() { try { const coords = await getLatLng("1600 Amphitheatre Parkway, Mountain View, CA"); console.log("Got coordinates:", coords.lat, coords.lng); // Do something with the coordinates here } catch (error) { console.error("Failed to get coordinates:", error); } } fetchMyCoordinates();
Quick Notes to Remember
- Async operations like geocoding don't "wait" for the API response—your outer function will finish before the callback runs. Never try to return values directly from an async callback!
- Always handle error cases (when the status isn't
OK)—this will prevent your code from breaking if the address is invalid or the API request fails. - Combining the lat/lng functions into one saves you from making duplicate API calls, which is more efficient.
内容的提问来源于stack exchange,提问作者Café

