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

JavaScript跨函数访问变量问题:变量值返回null

Hey there! No worries at all—we all start somewhere, and async behavior trips up even experienced devs sometimes. Let's figure out why your coordinates are returning null and fix it.

The Root Cause: Asynchronous Execution

The google.maps.Geocoder.geocode() method is asynchronous. That means it kicks off a request to Google's API and immediately moves on to run the rest of your code (the part where you initialize the map). The callback function getCoordinates only runs later, once the API sends back the geocoding results.

So when you create uluru and initialize the map, latitude and longitude are still stuck at their initial 0 values—because the callback hasn't had a chance to update them yet. If you didn't have that status check commented out, you'd also avoid cases where results[0] is undefined (like invalid addresses), which would throw errors and make those variables null.

Fix 1: Move Map Initialization Into the Callback

The simplest fix is to wait until you have the valid coordinates before setting up the map. We'll also restore that critical status check to handle errors:

function initAutocomplete() { 
  var geocoder = new google.maps.Geocoder(); 
  var address = document.getElementById("geocode").value; 
  
  geocoder.geocode({ 'address': address }, function getCoordinates(results, status) { 
    // Always validate the API response first!
    if (status == google.maps.GeocoderStatus.OK) {
      const latitude = results[0].geometry.location.lat(); 
      const longitude = results[0].geometry.location.lng(); 
      
      // Now we have valid coordinates—initialize the map
      const uluru = {lat: latitude, lng: longitude}; 
      const map = new google.maps.Map(document.getElementById('map'), { 
        center: uluru, 
        zoom: 17, 
        mapTypeId: 'roadmap' 
      }); 
    } else {
      // Handle failed requests (e.g., invalid address)
      alert(`Geocode failed: ${status}`);
    }
  }); 
}

Fix 2: Use Promises for Cleaner Async Flow

If you need more flexibility (like chaining multiple async operations), wrap the geocode call in a Promise and use async/await to control execution order:

// Wrap geocoding in a Promise
function fetchCoordinates(address) {
  return new Promise((resolve, reject) => {
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address }, (results, status) => {
      if (status === google.maps.GeocoderStatus.OK) {
        const coords = {
          lat: results[0].geometry.location.lat(),
          lng: results[0].geometry.location.lng()
        };
        resolve(coords);
      } else {
        reject(new Error(`Geocode failed: ${status}`));
      }
    });
  });
}

// Use async/await to wait for results
async function initAutocomplete() { 
  try {
    const address = document.getElementById("geocode").value; 
    const coordinates = await fetchCoordinates(address);
    
    // Initialize map once coordinates are ready
    const map = new google.maps.Map(document.getElementById('map'), { 
      center: coordinates, 
      zoom: 17, 
      mapTypeId: 'roadmap' 
    }); 
  } catch (err) {
    alert(err.message);
  }
}

Key Takeaways

  • Never skip the status check—it prevents crashes when the API can't find the address.
  • Async code runs out of order: always execute code that depends on async results inside the callback or use async/await to wait for the promise to resolve.

内容的提问来源于stack exchange,提问作者Yung-LX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:56:47