2016-04-21 108 views
0

我正在嘗試填充Google Map。這是我的一些代碼。爲什麼這個Ajax請求不起作用?當我把它全部放在document.ready()中作爲一個匿名函數時,它工作的很好,但我想重用這段代碼,所以我需要能夠調用它。調用在document.ready之外的ajax函數

$(document).ready(function(){ 

    var map = new google.maps.Map(document.getElementById('map'), { 
     center: {lat: 49.105, lng: -97.568}, 
     zoom: 4 
     }); 

getTornadoes("test", "test", "yes");    

}); 

// Get the tornado JSON file 
    function getTornadoes (test, test2, test3) {//These are not my real parameters 

     $.getJSON('water_pollutants.php', function(data){ 

      $.each(data.features, function(index, feature){ 

       var longitude = feature.properties.LONGITUDE; 
       var latitude = feature.properties.LATITUDE; 
       ... 

我得到錯誤InvalidValueError:setMap:不是Map的一個實例;而不是StreetViewPanorama的一個實例。不過,我認爲這不是Google地圖的問題。在嘗試引用在document.ready()之外聲明的ajax函數時,過去我遇到過類似的問題。

+0

廣場外面什麼現成的功能?如果它是谷歌地圖代碼,它使用'getElementById',它要求元素在它可以得到之前就存在? – adeneo

+0

getElementById像div id存在嗎? –

+0

@adeneo我的ajax調用在document.ready()之外。當我將它用作document.ready()中的匿名函數時,google map的工作狀態非常好,但我不想匿名使用它。 –

回答

0

我使用谷歌地圖API還,這裏是一個建議:

變化

$(document).ready(function(){ 

     var map = new google.maps.Map(document.getElementById('map'), { 
     center: {lat: 49.105, lng: -97.568}, 
     zoom: 4 
     }); 

到:

var map; 

$(document).ready(function(){ 

     map = new google.maps.Map(document.getElementById('map'), { 
     center: {lat: 49.105, lng: -97.568}, 
     zoom: 4 
     }); 
+0

謝謝。這很有效,但我在評論中更喜歡Adeneo的方法。那樣,我就避開了全球範圍。不過,我喜歡你在代碼中展示我。我只是把我的整個map語句放在getTornadoes函數中。 –

相關問題