2016-03-02 111 views
1

我道歉時間提前,因爲我覺得這是這樣一個簡單的問題,但我新,所以我不太明白如何做到這一點呢!返回JavaScript對象警報「未定義」

我地理編碼的地址和我返回座標:

//Geocoder 
var geocoder = new google.maps.Geocoder(); 

//Submit listener and alert the coordinates 
submit.addEventListener('click', function() { 
    alert(geocodeAddress(geocoder, map))); 
}); 

//Geocodes an address and returns the lat lng 
function geocodeAddress(geocoder, resultsMap) { 
    geocoder.geocode({address: address.value}, function(addressLatLng, status) { 

     //Checks if status returned was ok 
     if (status === google.maps.GeocoderStatus.OK) { 

      //adds pin to map and centers map on pin 
      resultsMap.setCenter(addressLatLng[0].geometry.location); 
      var marker = new google.maps.Marker({ 
       map: resultsMap, 
       position: addressLatLng[0].geometry.location 
      }); 
      //alert(addressLatLng[0].geometry.location); 
      return(addressLatLng[0].geometry.location); 
     } else { 
      alert('No address was found, please try again!'); 
     } 
    }); 
} 

如果我提醒他們裏面的功能,它會正確地警告他們(即{20.12345,20.12345}如果我就提醒他們提交按鈕,它只是說「不確定。」我怎麼會返回正確的座標?(我最終不得不做一些與他們不只是提醒他們)謝謝!

回答

1

這應該工作

//Geocoder 
var geocoder = new google.maps.Geocoder(); 

//Submit listener and alert the coordinates 
submit.addEventListener('click', function() { //This is callback 
    geocodeAddress(geocoder, map, function(loc){ 
     alert(loc || 'No address was found, please try again!'); 
    }); 
}); 

//Geocodes an address and returns the lat lng 
function geocodeAddress(geocoder, resultsMap, cb) { 
    geocoder.geocode({address: address.value}, function(addressLatLng, status) { 

     //Checks if status returned was ok 
     if (status === google.maps.GeocoderStatus.OK) { 

      //adds pin to map and centers map on pin 
      resultsMap.setCenter(addressLatLng[0].geometry.location); 
      var marker = new google.maps.Marker({ 
       map: resultsMap, 
       position: addressLatLng[0].geometry.location 
      }); 
      //call cb with location details 
      cb(addressLatLng[0].geometry.location); 
     } else { 
      //call the callback with empty value 
      cb(''); 
     } 
    }); 
} 

希望這有助於!

+0

This Works!在看過你做了什麼以及@millerbr的評論後,現在就明白爲什麼它返回undefined了。 –

+0

太棒了!保持我的朋友的良好工作......太棒了! :) –

+0

謝謝! :) 我還有一個問題!顯示的數據以(lat.34,12.345)開始,經緯度爲第一秒。我將如何提醒一個或另一個? –

0

我相信這是一個異步的問題。你需要返回從功能的Promise,然後調用警報時的承諾得到滿足。

原因警報顯示undefined是因爲功能尚未完成,因此它沒有被顯示警報的時間返回。