2017-07-17 50 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