2017-07-17 49 views
-1

我試圖在我的網站上實現Google Maps v3 API。我目前使用JS腳本來加載地圖。目前,中心,縮放和其他一些東西的所有值都被硬編碼到我的腳本中。我希望能夠從JSON格式的PHP文件中提取這些值。在我目前的腳本文件,我把這個順序我的功能:重構我的代碼以避免異步.getJSON AJAX調用

function initJSON(){ 
    var answerjson = undefined; 
    var requestAnswer = $.getJSON('URL'); 
    requestAnswer.done(function (data) { 
    answerjson = data; 
    }); 
} 

function initMap() { 

    map = new google.maps.Map(document.getElementById('map'), { 
    zoom: //Would like to get data from JSON, 
    center: //Would like to get data from JSON, 
    mapTypeId: 'terrain' 
    }); 

    //Code here about creating a shape outliner, not important 

    variableDefinedAbove.addListener('click', showArrays); 

} 


function showArrays(event) { 
    var vertices = this.getPath(); 
    var contentString = //Would like to get data from JSON ;   
    infoWindow.setContent(contentString); 
    infoWindow.setPosition(event.latLng); 
    infoWindow.open(map); 
} 

當我把這個腳本,使用Javascript完成initMap()和showArrays()函數initJSON前拉取數據。我知道如何將完成的initJSON()中的數據放入其他函數中,但是當這些函數運行時,'answerjson'是未定義的,使得它們無用。有沒有一種方法可以重構我的程序,以便initJSON()必須在任何其他函數運行之前完成?我知道我可以用異步和Promises做這個,但我沒有經驗,如果有更簡單的解決方案,我寧願使用它們。

回答

2

簡單的答案是從你的getJSON通話.done打電話給你的功能 - 就像這樣:

function initJSON(){ 
    //var answerjson = undefined; dont do this, you can pass this to where you need it 
    var requestAnswer = $.getJSON('URL'); 
    requestAnswer.done(function (data) { 
     //answerjson = data; 
     //call your function here 
     initMap(data); //pass data to map function 
    }); 
} 

並更新initMap功能從服務器取數據:

function initMap(data) { 
    map = new google.maps.Map(document.getElementById('map'), { 
     zoom: data.someProperty,//replace with actual prop name 
     center: data.someOtherProperty, //replace with actual prop name 
     mapTypeId: 'terrain' 
    }); 

    //Code here about creating a shape outliner, not important 

    variableDefinedAbove.addListener('click', showArrays); 
} 
+0

是有一種方法可以打印出initMap()收到的數據的值,以驗證它是否正常工作?現在我把var abc = data;和console.log(abc);在initMap()的頂部,它仍然返回undefined。我做錯了嗎? – taurus

+0

@ user1234231 - 不,應該有效。你能否驗證從你的服務器返回的數據是你期望的實際數據?打開你的控制檯,進入「網絡」選項卡並檢查你的AJAX調用(特別是響應) – tymeJV

+0

好吧,我可以縮小到最初的initJSON()函數根本不會被調用。謝謝。 – taurus