2013-10-19 57 views
0

檢索值我有一個非常基本的功能,抓住用戶當前的位置。當我提醒或記錄geoCoder變量時,我成功獲取一個值。我試圖把這個geoCoder值放入我的JSON調用中。jQuery從功能

function userLocation(location, callback) { 
    var geoCoder = new google.maps.Geocoder(); 
     geoCoder.geocode({ 
      location: location 
     } 
    console.log(geoCoder); 
} 

var jsonCall; 
jsonCall = '/bin/userlocation/locations.' + geoCoder + '.json' 

當我運行這個時我得到一個geoCoder沒有定義js錯誤。我將如何去獲取geoCoder變量的值?我是一個新手,所以代碼示例表示讚賞。

+0

什麼是你想用這個代碼來完成?只需對地址進行地理編碼? –

+0

異步問題本質上與此相同:http://stackoverflow.com/q/14220321/139010 –

+0

當我警告或記錄geoCoder變量時,只更正geoCode地址我成功獲取值我只需要外部值的函數放在我的JSON調用。 –

回答

1
var jsonCall; //declaring outside and before a function means the var will be accessible inside and outside of the function 

function userLocation(location, callback) { 
    var geoCoder = new google.maps.Geocoder(); 
     geoCoder.geocode({ 
      location: location 
     } 
    console.log(geoCoder); 
    jsonCall = '/bin/userlocation/locations.' + geoCoder + '.json' 
} 

console.log(jsonCall); 
+0

內部和外部的範圍內,這是行不通的。 'geocode'調用是** A **同步。 –

+0

切換變量,所以它現在可以工作,謝謝! –

+0

@BrianOgden謝謝!這工作,但出於好奇,爲什麼我不能把我的jsonCall在userLocation函數之外,仍然調用geocoder變量? –

0

您正在創建您的變量函數,並試圖達到超出函數的範圍。嘗試從函數中定義它,並在任何你想要的地方賦值。

定義爲var geoCoder;出功能。 並填寫geoCoder的功能。

var geoCoder; 
function blabla(){ 
geocoder = dosomething 
} 

console.log(geoCoder); // this returns null 
blabla(); 
console.log(geoCoder); // now u can see it is not empty 
+0

好吧,我是一個新手,我該如何去做,你可以請提供一個代碼示例,如我的問題所述。謝謝! –

+0

好吧,我添加了一個代碼示例。 – obayhan

+0

請注意安德魯·惠特克所說的,地理編碼調用是一個異步函數,請參閱我的答案,我只是在函數調用之前聲明瞭jsonCall var,所以它在函數 –